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,
990 GNU_AK_NO_INSTRUMENT_FUNCTION,
991 GNU_AK_WARN_UNUSED_RESULT,
996 GNU_AK_FUNCTION_VECTOR,
998 GNU_AK_INTERRUPT_HANDLER,
1004 GNU_AK_EIGTHBIT_DATA,
1009 GNU_AK_EXTERNALLY_VISIBLE,
1010 GNU_AK_RETURN_TWICE,
1029 } gnu_attribute_kind_t;
1031 static const char *gnu_attribute_names[GNU_AK_LAST] = {
1032 [GNU_AK_CONST] = "const",
1033 [GNU_AK_VOLATILE] = "volatile",
1034 [GNU_AK_CDECL] = "cdecl",
1035 [GNU_AK_STDCALL] = "stdcall",
1036 [GNU_AK_FASTCALL] = "fastcall",
1037 [GNU_AK_DEPRECATED] = "deprecated",
1038 [GNU_AK_NOINLINE] = "noinline",
1039 [GNU_AK_NORETURN] = "noreturn",
1040 [GNU_AK_NAKED] = "naked",
1041 [GNU_AK_PURE] = "pure",
1042 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1043 [GNU_AK_MALLOC] = "malloc",
1044 [GNU_AK_WEAK] = "weak",
1045 [GNU_AK_CONSTRUCTOR] = "constructor",
1046 [GNU_AK_DESTRUCTOR] = "destructor",
1047 [GNU_AK_NOTHROW] = "nothrow",
1048 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1049 [GNU_AK_COMMON] = "coommon",
1050 [GNU_AK_NOCOMMON] = "nocommon",
1051 [GNU_AK_PACKED] = "packed",
1052 [GNU_AK_SHARED] = "shared",
1053 [GNU_AK_NOTSHARED] = "notshared",
1054 [GNU_AK_USED] = "used",
1055 [GNU_AK_UNUSED] = "unused",
1056 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1057 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1058 [GNU_AK_LONGCALL] = "longcall",
1059 [GNU_AK_SHORTCALL] = "shortcall",
1060 [GNU_AK_LONG_CALL] = "long_call",
1061 [GNU_AK_SHORT_CALL] = "short_call",
1062 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1063 [GNU_AK_INTERRUPT] = "interrupt",
1064 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1065 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1066 [GNU_AK_NESTING] = "nesting",
1067 [GNU_AK_NEAR] = "near",
1068 [GNU_AK_FAR] = "far",
1069 [GNU_AK_SIGNAL] = "signal",
1070 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1071 [GNU_AK_TINY_DATA] = "tiny_data",
1072 [GNU_AK_SAVEALL] = "saveall",
1073 [GNU_AK_FLATTEN] = "flatten",
1074 [GNU_AK_SSEREGPARM] = "sseregparm",
1075 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1076 [GNU_AK_RETURN_TWICE] = "return_twice",
1077 [GNU_AK_MAY_ALIAS] = "may_alias",
1078 [GNU_AK_MS_STRUCT] = "ms_struct",
1079 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1080 [GNU_AK_ALIGNED] = "aligned",
1081 [GNU_AK_ALIAS] = "alias",
1082 [GNU_AK_SECTION] = "section",
1083 [GNU_AK_FORMAT] = "format",
1084 [GNU_AK_FORMAT_ARG] = "format_arg",
1085 [GNU_AK_WEAKREF] = "weakref",
1086 [GNU_AK_NONNULL] = "nonnull",
1087 [GNU_AK_TLS_MODEL] = "tls_model",
1088 [GNU_AK_VISIBILITY] = "visibility",
1089 [GNU_AK_REGPARM] = "regparm",
1090 [GNU_AK_MODEL] = "model",
1091 [GNU_AK_TRAP_EXIT] = "trap_exit",
1092 [GNU_AK_SP_SWITCH] = "sp_switch",
1093 [GNU_AK_SENTINEL] = "sentinel"
1097 * compare two string, ignoring double underscores on the second.
1099 static int strcmp_underscore(const char *s1, const char *s2) {
1100 if(s2[0] == '_' && s2[1] == '_') {
1102 size_t l1 = strlen(s1);
1103 if(l1 + 2 != strlen(s2)) {
1107 return strncmp(s1, s2, l1);
1109 return strcmp(s1, s2);
1113 * parse one constant expression argument.
1115 static expression_t *parse_gnu_attribute_const_arg(void) {
1116 expression_t *expression;
1117 add_anchor_token(')');
1118 expression = parse_constant_expression();
1119 rem_anchor_token(')');
1123 return create_invalid_expression();
1127 * parse a list of constant expressions argumnets.
1129 static expression_t *parse_gnu_attribute_const_arg_list(void) {
1130 expression_t *expression;
1131 add_anchor_token(')');
1132 add_anchor_token(',');
1134 expression = parse_constant_expression();
1135 if(token.type != ',')
1139 rem_anchor_token(',');
1140 rem_anchor_token(')');
1144 return create_invalid_expression();
1148 * parse one string literal argument.
1150 static string_t parse_gnu_attribute_string_arg(void) {
1151 string_t string = { NULL, 0 };
1152 add_anchor_token('(');
1153 if(token.type != T_STRING_LITERAL) {
1154 parse_error_expected("while parsing attribute directive", T_STRING_LITERAL);
1157 string = parse_string_literals();
1158 rem_anchor_token('(');
1165 * parse one tls model.
1167 static int parse_gnu_attribute_tls_model_arg(void) {
1168 static const char *tls_models[] = {
1174 string_t string = parse_gnu_attribute_string_arg();
1175 if(string.begin != NULL) {
1176 for(int i = 0; i < 4; ++i) {
1177 if(strcmp(tls_models[i], string.begin) == 0)
1181 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1186 * parse one tls model.
1188 static int parse_gnu_attribute_visibility_arg(void) {
1189 static const char *visibilities[] = {
1195 string_t string = parse_gnu_attribute_string_arg();
1196 if(string.begin != NULL) {
1197 for(int i = 0; i < 4; ++i) {
1198 if(strcmp(visibilities[i], string.begin) == 0)
1202 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1207 * parse one (code) model.
1209 static int parse_gnu_attribute_model_arg(void) {
1210 static const char *visibilities[] = {
1215 string_t string = parse_gnu_attribute_string_arg();
1216 if(string.begin != NULL) {
1217 for(int i = 0; i < 3; ++i) {
1218 if(strcmp(visibilities[i], string.begin) == 0)
1222 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1227 * parse one interrupt argument.
1229 static int parse_gnu_attribute_interrupt_arg(void) {
1230 static const char *interrupts[] = {
1237 string_t string = parse_gnu_attribute_string_arg();
1238 if(string.begin != NULL) {
1239 for(int i = 0; i < 5; ++i) {
1240 if(strcmp(interrupts[i], string.begin) == 0)
1244 errorf(HERE, "'%s' is an interrupt", string.begin);
1249 * parse ( identifier, const expression, const expression )
1251 static void parse_gnu_attribute_format_args(void) {
1252 static const char *format_names[] = {
1260 if(token.type != T_IDENTIFIER) {
1261 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER);
1264 const char *name = token.v.symbol->string;
1265 for(i = 0; i < 4; ++i) {
1266 if(strcmp_underscore(format_names[i], name) == 0)
1270 if(warning.attribute)
1271 warningf(HERE, "'%s' is an unrecognized format function type", name);
1276 add_anchor_token(')');
1277 add_anchor_token(',');
1278 parse_constant_expression();
1279 rem_anchor_token(',');
1280 rem_anchor_token('(');
1283 add_anchor_token(')');
1284 parse_constant_expression();
1285 rem_anchor_token('(');
1293 * Parse one GNU attribute.
1295 * Note that attribute names can be specified WITH or WITHOUT
1296 * double underscores, ie const or __const__.
1298 * The following attributes are parsed without arguments
1323 * no_instrument_function
1324 * warn_unused_result
1341 * externally_visible
1347 * The following attributes are parsed with arguments
1348 * aligned( const expression )
1349 * alias( string literal )
1350 * section( string literal )
1351 * format( identifier, const expression, const expression )
1352 * format_arg( const expression )
1353 * tls_model( string literal )
1354 * visibility( string literal )
1355 * regparm( const expression )
1356 * model( string leteral )
1357 * trap_exit( const expression )
1358 * sp_switch( string literal )
1360 * The following attributes might have arguments
1361 * weak_ref( string literal )
1362 * non_null( const expression // ',' )
1363 * interrupt( string literal )
1364 * sentinel( constant expression )
1366 static void parse_gnu_attribute(void)
1368 eat(T___attribute__);
1371 if(token.type != ')') {
1372 /* non-empty attribute list */
1375 if(token.type == T_const) {
1377 } else if(token.type == T_volatile) {
1379 } else if(token.type == T_cdecl) {
1380 /* __attribute__((cdecl)), WITH ms mode */
1382 } else if(token.type != T_IDENTIFIER) {
1383 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1386 const symbol_t *sym = token.v.symbol;
1390 gnu_attribute_kind_t kind;
1391 for(kind = 0; kind < GNU_AK_LAST; ++kind) {
1392 if(strcmp_underscore(gnu_attribute_names[kind], name) == 0)
1396 if(kind == GNU_AK_LAST) {
1397 if(warning.attribute)
1398 warningf(HERE, "'%s' attribute directive ignored", name);
1400 /* skip possible arguments */
1401 if(token.type == '(') {
1402 eat_until_matching_token(')');
1405 /* check for arguments */
1406 bool have_args = false;
1407 if(token.type == '(') {
1409 if(token.type == ')') {
1410 /* empty args are allowed */
1418 case GNU_AK_VOLATILE:
1420 case GNU_AK_STDCALL:
1421 case GNU_AK_FASTCALL:
1422 case GNU_AK_DEPRECATED:
1423 case GNU_AK_NOINLINE:
1424 case GNU_AK_NORETURN:
1427 case GNU_AK_ALWAYS_INLINE:
1430 case GNU_AK_CONSTRUCTOR:
1431 case GNU_AK_DESTRUCTOR:
1432 case GNU_AK_NOTHROW:
1433 case GNU_AK_TRANSPARENT_UNION:
1435 case GNU_AK_NOCOMMON:
1438 case GNU_AK_NOTSHARED:
1441 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1442 case GNU_AK_WARN_UNUSED_RESULT:
1443 case GNU_AK_LONGCALL:
1444 case GNU_AK_SHORTCALL:
1445 case GNU_AK_LONG_CALL:
1446 case GNU_AK_SHORT_CALL:
1447 case GNU_AK_FUNCTION_VECTOR:
1448 case GNU_AK_INTERRUPT_HANDLER:
1449 case GNU_AK_NMI_HANDLER:
1450 case GNU_AK_NESTING:
1454 case GNU_AK_EIGTHBIT_DATA:
1455 case GNU_AK_TINY_DATA:
1456 case GNU_AK_SAVEALL:
1457 case GNU_AK_FLATTEN:
1458 case GNU_AK_SSEREGPARM:
1459 case GNU_AK_EXTERNALLY_VISIBLE:
1460 case GNU_AK_RETURN_TWICE:
1461 case GNU_AK_MAY_ALIAS:
1462 case GNU_AK_MS_STRUCT:
1463 case GNU_AK_GCC_STRUCT:
1465 /* should have no arguments */
1466 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1467 eat_until_matching_token('(');
1468 /* we have already consumend '(', so we stop before ')', eat it */
1473 case GNU_AK_ALIGNED:
1474 case GNU_AK_FORMAT_ARG:
1475 case GNU_AK_REGPARM:
1476 case GNU_AK_TRAP_EXIT:
1478 /* should have arguments */
1479 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1481 parse_gnu_attribute_const_arg();
1484 case GNU_AK_SECTION:
1485 case GNU_AK_SP_SWITCH:
1487 /* should have arguments */
1488 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1490 parse_gnu_attribute_string_arg();
1494 /* should have arguments */
1495 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1497 parse_gnu_attribute_format_args();
1499 case GNU_AK_WEAKREF:
1500 /* may have one string argument */
1502 parse_gnu_attribute_string_arg();
1504 case GNU_AK_NONNULL:
1506 parse_gnu_attribute_const_arg_list();
1508 case GNU_AK_TLS_MODEL:
1510 /* should have arguments */
1511 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1513 parse_gnu_attribute_tls_model_arg();
1515 case GNU_AK_VISIBILITY:
1517 /* should have arguments */
1518 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1520 parse_gnu_attribute_visibility_arg();
1524 /* should have arguments */
1525 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1527 parse_gnu_attribute_model_arg();
1528 case GNU_AK_INTERRUPT:
1529 /* may have one string argument */
1531 parse_gnu_attribute_interrupt_arg();
1533 case GNU_AK_SENTINEL:
1534 /* may have one string argument */
1536 parse_gnu_attribute_const_arg();
1539 /* already handled */
1543 if(token.type != ',')
1555 * Parse GNU attributes.
1557 static void parse_attributes(void)
1560 switch(token.type) {
1561 case T___attribute__: {
1562 parse_gnu_attribute();
1568 if(token.type != T_STRING_LITERAL) {
1569 parse_error_expected("while parsing assembler attribute",
1571 eat_until_matching_token('(');
1574 parse_string_literals();
1579 goto attributes_finished;
1584 attributes_finished:
1588 static designator_t *parse_designation(void)
1590 designator_t *result = NULL;
1591 designator_t *last = NULL;
1594 designator_t *designator;
1595 switch(token.type) {
1597 designator = allocate_ast_zero(sizeof(designator[0]));
1598 designator->source_position = token.source_position;
1600 add_anchor_token(']');
1601 designator->array_index = parse_constant_expression();
1602 rem_anchor_token(']');
1606 designator = allocate_ast_zero(sizeof(designator[0]));
1607 designator->source_position = token.source_position;
1609 if(token.type != T_IDENTIFIER) {
1610 parse_error_expected("while parsing designator",
1614 designator->symbol = token.v.symbol;
1622 assert(designator != NULL);
1624 last->next = designator;
1626 result = designator;
1634 static initializer_t *initializer_from_string(array_type_t *type,
1635 const string_t *const string)
1637 /* TODO: check len vs. size of array type */
1640 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1641 initializer->string.string = *string;
1646 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1647 wide_string_t *const string)
1649 /* TODO: check len vs. size of array type */
1652 initializer_t *const initializer =
1653 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1654 initializer->wide_string.string = *string;
1660 * Build an initializer from a given expression.
1662 static initializer_t *initializer_from_expression(type_t *orig_type,
1663 expression_t *expression)
1665 /* TODO check that expression is a constant expression */
1667 /* § 6.7.8.14/15 char array may be initialized by string literals */
1668 type_t *type = skip_typeref(orig_type);
1669 type_t *expr_type_orig = expression->base.type;
1670 type_t *expr_type = skip_typeref(expr_type_orig);
1671 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1672 array_type_t *const array_type = &type->array;
1673 type_t *const element_type = skip_typeref(array_type->element_type);
1675 if (element_type->kind == TYPE_ATOMIC) {
1676 atomic_type_kind_t akind = element_type->atomic.akind;
1677 switch (expression->kind) {
1678 case EXPR_STRING_LITERAL:
1679 if (akind == ATOMIC_TYPE_CHAR
1680 || akind == ATOMIC_TYPE_SCHAR
1681 || akind == ATOMIC_TYPE_UCHAR) {
1682 return initializer_from_string(array_type,
1683 &expression->string.value);
1686 case EXPR_WIDE_STRING_LITERAL: {
1687 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1688 if (get_unqualified_type(element_type) == bare_wchar_type) {
1689 return initializer_from_wide_string(array_type,
1690 &expression->wide_string.value);
1700 type_t *const res_type = semantic_assign(type, expression, "initializer",
1701 expression->base.source_position);
1702 if (res_type == NULL)
1705 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1706 result->value.value = create_implicit_cast(expression, res_type);
1712 * Checks if a given expression can be used as an constant initializer.
1714 static bool is_initializer_constant(const expression_t *expression)
1716 return is_constant_expression(expression)
1717 || is_address_constant(expression);
1721 * Parses an scalar initializer.
1723 * § 6.7.8.11; eat {} without warning
1725 static initializer_t *parse_scalar_initializer(type_t *type,
1726 bool must_be_constant)
1728 /* there might be extra {} hierarchies */
1730 while(token.type == '{') {
1733 warningf(HERE, "extra curly braces around scalar initializer");
1738 expression_t *expression = parse_assignment_expression();
1739 if(must_be_constant && !is_initializer_constant(expression)) {
1740 errorf(expression->base.source_position,
1741 "Initialisation expression '%E' is not constant\n",
1745 initializer_t *initializer = initializer_from_expression(type, expression);
1747 if(initializer == NULL) {
1748 errorf(expression->base.source_position,
1749 "expression '%E' (type '%T') doesn't match expected type '%T'",
1750 expression, expression->base.type, type);
1755 bool additional_warning_displayed = false;
1757 if(token.type == ',') {
1760 if(token.type != '}') {
1761 if(!additional_warning_displayed) {
1762 warningf(HERE, "additional elements in scalar initializer");
1763 additional_warning_displayed = true;
1774 * An entry in the type path.
1776 typedef struct type_path_entry_t type_path_entry_t;
1777 struct type_path_entry_t {
1778 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1780 size_t index; /**< For array types: the current index. */
1781 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1786 * A type path expression a position inside compound or array types.
1788 typedef struct type_path_t type_path_t;
1789 struct type_path_t {
1790 type_path_entry_t *path; /**< An flexible array containing the current path. */
1791 type_t *top_type; /**< type of the element the path points */
1792 size_t max_index; /**< largest index in outermost array */
1796 * Prints a type path for debugging.
1798 static __attribute__((unused)) void debug_print_type_path(
1799 const type_path_t *path)
1801 size_t len = ARR_LEN(path->path);
1803 for(size_t i = 0; i < len; ++i) {
1804 const type_path_entry_t *entry = & path->path[i];
1806 type_t *type = skip_typeref(entry->type);
1807 if(is_type_compound(type)) {
1808 /* in gcc mode structs can have no members */
1809 if(entry->v.compound_entry == NULL) {
1813 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1814 } else if(is_type_array(type)) {
1815 fprintf(stderr, "[%zd]", entry->v.index);
1817 fprintf(stderr, "-INVALID-");
1820 if(path->top_type != NULL) {
1821 fprintf(stderr, " (");
1822 print_type(path->top_type);
1823 fprintf(stderr, ")");
1828 * Return the top type path entry, ie. in a path
1829 * (type).a.b returns the b.
1831 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1833 size_t len = ARR_LEN(path->path);
1835 return &path->path[len-1];
1839 * Enlarge the type path by an (empty) element.
1841 static type_path_entry_t *append_to_type_path(type_path_t *path)
1843 size_t len = ARR_LEN(path->path);
1844 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1846 type_path_entry_t *result = & path->path[len];
1847 memset(result, 0, sizeof(result[0]));
1852 * Descending into a sub-type. Enter the scope of the current
1855 static void descend_into_subtype(type_path_t *path)
1857 type_t *orig_top_type = path->top_type;
1858 type_t *top_type = skip_typeref(orig_top_type);
1860 assert(is_type_compound(top_type) || is_type_array(top_type));
1862 type_path_entry_t *top = append_to_type_path(path);
1863 top->type = top_type;
1865 if(is_type_compound(top_type)) {
1866 declaration_t *declaration = top_type->compound.declaration;
1867 declaration_t *entry = declaration->scope.declarations;
1868 top->v.compound_entry = entry;
1871 path->top_type = entry->type;
1873 path->top_type = NULL;
1876 assert(is_type_array(top_type));
1879 path->top_type = top_type->array.element_type;
1884 * Pop an entry from the given type path, ie. returning from
1885 * (type).a.b to (type).a
1887 static void ascend_from_subtype(type_path_t *path)
1889 type_path_entry_t *top = get_type_path_top(path);
1891 path->top_type = top->type;
1893 size_t len = ARR_LEN(path->path);
1894 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1898 * Pop entries from the given type path until the given
1899 * path level is reached.
1901 static void ascend_to(type_path_t *path, size_t top_path_level)
1903 size_t len = ARR_LEN(path->path);
1905 while(len > top_path_level) {
1906 ascend_from_subtype(path);
1907 len = ARR_LEN(path->path);
1911 static bool walk_designator(type_path_t *path, const designator_t *designator,
1912 bool used_in_offsetof)
1914 for( ; designator != NULL; designator = designator->next) {
1915 type_path_entry_t *top = get_type_path_top(path);
1916 type_t *orig_type = top->type;
1918 type_t *type = skip_typeref(orig_type);
1920 if(designator->symbol != NULL) {
1921 symbol_t *symbol = designator->symbol;
1922 if(!is_type_compound(type)) {
1923 if(is_type_valid(type)) {
1924 errorf(designator->source_position,
1925 "'.%Y' designator used for non-compound type '%T'",
1931 declaration_t *declaration = type->compound.declaration;
1932 declaration_t *iter = declaration->scope.declarations;
1933 for( ; iter != NULL; iter = iter->next) {
1934 if(iter->symbol == symbol) {
1939 errorf(designator->source_position,
1940 "'%T' has no member named '%Y'", orig_type, symbol);
1943 if(used_in_offsetof) {
1944 type_t *real_type = skip_typeref(iter->type);
1945 if(real_type->kind == TYPE_BITFIELD) {
1946 errorf(designator->source_position,
1947 "offsetof designator '%Y' may not specify bitfield",
1953 top->type = orig_type;
1954 top->v.compound_entry = iter;
1955 orig_type = iter->type;
1957 expression_t *array_index = designator->array_index;
1958 assert(designator->array_index != NULL);
1960 if(!is_type_array(type)) {
1961 if(is_type_valid(type)) {
1962 errorf(designator->source_position,
1963 "[%E] designator used for non-array type '%T'",
1964 array_index, orig_type);
1968 if(!is_type_valid(array_index->base.type)) {
1972 long index = fold_constant(array_index);
1973 if(!used_in_offsetof) {
1975 errorf(designator->source_position,
1976 "array index [%E] must be positive", array_index);
1979 if(type->array.size_constant == true) {
1980 long array_size = type->array.size;
1981 if(index >= array_size) {
1982 errorf(designator->source_position,
1983 "designator [%E] (%d) exceeds array size %d",
1984 array_index, index, array_size);
1990 top->type = orig_type;
1991 top->v.index = (size_t) index;
1992 orig_type = type->array.element_type;
1994 path->top_type = orig_type;
1996 if(designator->next != NULL) {
1997 descend_into_subtype(path);
2006 static void advance_current_object(type_path_t *path, size_t top_path_level)
2008 type_path_entry_t *top = get_type_path_top(path);
2010 type_t *type = skip_typeref(top->type);
2011 if(is_type_union(type)) {
2012 /* in unions only the first element is initialized */
2013 top->v.compound_entry = NULL;
2014 } else if(is_type_struct(type)) {
2015 declaration_t *entry = top->v.compound_entry;
2017 entry = entry->next;
2018 top->v.compound_entry = entry;
2020 path->top_type = entry->type;
2024 assert(is_type_array(type));
2028 if(!type->array.size_constant || top->v.index < type->array.size) {
2033 /* we're past the last member of the current sub-aggregate, try if we
2034 * can ascend in the type hierarchy and continue with another subobject */
2035 size_t len = ARR_LEN(path->path);
2037 if(len > top_path_level) {
2038 ascend_from_subtype(path);
2039 advance_current_object(path, top_path_level);
2041 path->top_type = NULL;
2046 * skip until token is found.
2048 static void skip_until(int type) {
2049 while(token.type != type) {
2050 if(token.type == T_EOF)
2057 * skip any {...} blocks until a closing braket is reached.
2059 static void skip_initializers(void)
2061 if(token.type == '{')
2064 while(token.type != '}') {
2065 if(token.type == T_EOF)
2067 if(token.type == '{') {
2075 static initializer_t *create_empty_initializer(void)
2077 static initializer_t empty_initializer
2078 = { .list = { { INITIALIZER_LIST }, 0 } };
2079 return &empty_initializer;
2083 * Parse a part of an initialiser for a struct or union,
2085 static initializer_t *parse_sub_initializer(type_path_t *path,
2086 type_t *outer_type, size_t top_path_level,
2087 parse_initializer_env_t *env)
2089 if(token.type == '}') {
2090 /* empty initializer */
2091 return create_empty_initializer();
2094 type_t *orig_type = path->top_type;
2095 type_t *type = NULL;
2097 if (orig_type == NULL) {
2098 /* We are initializing an empty compound. */
2100 type = skip_typeref(orig_type);
2102 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2103 * initializers in this case. */
2104 if(!is_type_valid(type)) {
2105 skip_initializers();
2106 return create_empty_initializer();
2110 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2113 designator_t *designator = NULL;
2114 if(token.type == '.' || token.type == '[') {
2115 designator = parse_designation();
2117 /* reset path to toplevel, evaluate designator from there */
2118 ascend_to(path, top_path_level);
2119 if(!walk_designator(path, designator, false)) {
2120 /* can't continue after designation error */
2124 initializer_t *designator_initializer
2125 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2126 designator_initializer->designator.designator = designator;
2127 ARR_APP1(initializer_t*, initializers, designator_initializer);
2132 if(token.type == '{') {
2133 if(type != NULL && is_type_scalar(type)) {
2134 sub = parse_scalar_initializer(type, env->must_be_constant);
2138 if (env->declaration != NULL)
2139 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2140 env->declaration->symbol);
2142 errorf(HERE, "extra brace group at end of initializer");
2144 descend_into_subtype(path);
2146 add_anchor_token('}');
2147 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2149 rem_anchor_token('}');
2152 ascend_from_subtype(path);
2156 goto error_parse_next;
2160 /* must be an expression */
2161 expression_t *expression = parse_assignment_expression();
2163 if(env->must_be_constant && !is_initializer_constant(expression)) {
2164 errorf(expression->base.source_position,
2165 "Initialisation expression '%E' is not constant\n",
2170 /* we are already outside, ... */
2174 /* handle { "string" } special case */
2175 if((expression->kind == EXPR_STRING_LITERAL
2176 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2177 && outer_type != NULL) {
2178 sub = initializer_from_expression(outer_type, expression);
2180 if(token.type == ',') {
2183 if(token.type != '}') {
2184 warningf(HERE, "excessive elements in initializer for type '%T'",
2187 /* TODO: eat , ... */
2192 /* descend into subtypes until expression matches type */
2194 orig_type = path->top_type;
2195 type = skip_typeref(orig_type);
2197 sub = initializer_from_expression(orig_type, expression);
2201 if(!is_type_valid(type)) {
2204 if(is_type_scalar(type)) {
2205 errorf(expression->base.source_position,
2206 "expression '%E' doesn't match expected type '%T'",
2207 expression, orig_type);
2211 descend_into_subtype(path);
2215 /* update largest index of top array */
2216 const type_path_entry_t *first = &path->path[0];
2217 type_t *first_type = first->type;
2218 first_type = skip_typeref(first_type);
2219 if(is_type_array(first_type)) {
2220 size_t index = first->v.index;
2221 if(index > path->max_index)
2222 path->max_index = index;
2226 /* append to initializers list */
2227 ARR_APP1(initializer_t*, initializers, sub);
2230 if(env->declaration != NULL)
2231 warningf(HERE, "excess elements in struct initializer for '%Y'",
2232 env->declaration->symbol);
2234 warningf(HERE, "excess elements in struct initializer");
2238 if(token.type == '}') {
2242 if(token.type == '}') {
2247 /* advance to the next declaration if we are not at the end */
2248 advance_current_object(path, top_path_level);
2249 orig_type = path->top_type;
2250 if(orig_type != NULL)
2251 type = skip_typeref(orig_type);
2257 size_t len = ARR_LEN(initializers);
2258 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2259 initializer_t *result = allocate_ast_zero(size);
2260 result->kind = INITIALIZER_LIST;
2261 result->list.len = len;
2262 memcpy(&result->list.initializers, initializers,
2263 len * sizeof(initializers[0]));
2265 DEL_ARR_F(initializers);
2266 ascend_to(path, top_path_level);
2271 skip_initializers();
2272 DEL_ARR_F(initializers);
2273 ascend_to(path, top_path_level);
2278 * Parses an initializer. Parsers either a compound literal
2279 * (env->declaration == NULL) or an initializer of a declaration.
2281 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2283 type_t *type = skip_typeref(env->type);
2284 initializer_t *result = NULL;
2287 if(is_type_scalar(type)) {
2288 result = parse_scalar_initializer(type, env->must_be_constant);
2289 } else if(token.type == '{') {
2293 memset(&path, 0, sizeof(path));
2294 path.top_type = env->type;
2295 path.path = NEW_ARR_F(type_path_entry_t, 0);
2297 descend_into_subtype(&path);
2299 add_anchor_token('}');
2300 result = parse_sub_initializer(&path, env->type, 1, env);
2301 rem_anchor_token('}');
2303 max_index = path.max_index;
2304 DEL_ARR_F(path.path);
2308 /* parse_scalar_initializer() also works in this case: we simply
2309 * have an expression without {} around it */
2310 result = parse_scalar_initializer(type, env->must_be_constant);
2313 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2314 * the array type size */
2315 if(is_type_array(type) && type->array.size_expression == NULL
2316 && result != NULL) {
2318 switch (result->kind) {
2319 case INITIALIZER_LIST:
2320 size = max_index + 1;
2323 case INITIALIZER_STRING:
2324 size = result->string.string.size;
2327 case INITIALIZER_WIDE_STRING:
2328 size = result->wide_string.string.size;
2332 internal_errorf(HERE, "invalid initializer type");
2335 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2336 cnst->base.type = type_size_t;
2337 cnst->conste.v.int_value = size;
2339 type_t *new_type = duplicate_type(type);
2341 new_type->array.size_expression = cnst;
2342 new_type->array.size_constant = true;
2343 new_type->array.size = size;
2344 env->type = new_type;
2352 static declaration_t *append_declaration(declaration_t *declaration);
2354 static declaration_t *parse_compound_type_specifier(bool is_struct)
2362 symbol_t *symbol = NULL;
2363 declaration_t *declaration = NULL;
2365 if (token.type == T___attribute__) {
2370 if(token.type == T_IDENTIFIER) {
2371 symbol = token.v.symbol;
2375 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2377 declaration = get_declaration(symbol, NAMESPACE_UNION);
2379 } else if(token.type != '{') {
2381 parse_error_expected("while parsing struct type specifier",
2382 T_IDENTIFIER, '{', 0);
2384 parse_error_expected("while parsing union type specifier",
2385 T_IDENTIFIER, '{', 0);
2391 if(declaration == NULL) {
2392 declaration = allocate_declaration_zero();
2393 declaration->namespc =
2394 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2395 declaration->source_position = token.source_position;
2396 declaration->symbol = symbol;
2397 declaration->parent_scope = scope;
2398 if (symbol != NULL) {
2399 environment_push(declaration);
2401 append_declaration(declaration);
2404 if(token.type == '{') {
2405 if(declaration->init.is_defined) {
2406 assert(symbol != NULL);
2407 errorf(HERE, "multiple definitions of '%s %Y'",
2408 is_struct ? "struct" : "union", symbol);
2409 declaration->scope.declarations = NULL;
2411 declaration->init.is_defined = true;
2413 parse_compound_type_entries(declaration);
2420 static void parse_enum_entries(type_t *const enum_type)
2424 if(token.type == '}') {
2426 errorf(HERE, "empty enum not allowed");
2430 add_anchor_token('}');
2432 if(token.type != T_IDENTIFIER) {
2433 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2435 rem_anchor_token('}');
2439 declaration_t *const entry = allocate_declaration_zero();
2440 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2441 entry->type = enum_type;
2442 entry->symbol = token.v.symbol;
2443 entry->source_position = token.source_position;
2446 if(token.type == '=') {
2448 expression_t *value = parse_constant_expression();
2450 value = create_implicit_cast(value, enum_type);
2451 entry->init.enum_value = value;
2456 record_declaration(entry);
2458 if(token.type != ',')
2461 } while(token.type != '}');
2462 rem_anchor_token('}');
2470 static type_t *parse_enum_specifier(void)
2474 declaration_t *declaration;
2477 if(token.type == T_IDENTIFIER) {
2478 symbol = token.v.symbol;
2481 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2482 } else if(token.type != '{') {
2483 parse_error_expected("while parsing enum type specifier",
2484 T_IDENTIFIER, '{', 0);
2491 if(declaration == NULL) {
2492 declaration = allocate_declaration_zero();
2493 declaration->namespc = NAMESPACE_ENUM;
2494 declaration->source_position = token.source_position;
2495 declaration->symbol = symbol;
2496 declaration->parent_scope = scope;
2499 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2500 type->enumt.declaration = declaration;
2502 if(token.type == '{') {
2503 if(declaration->init.is_defined) {
2504 errorf(HERE, "multiple definitions of enum %Y", symbol);
2506 if (symbol != NULL) {
2507 environment_push(declaration);
2509 append_declaration(declaration);
2510 declaration->init.is_defined = 1;
2512 parse_enum_entries(type);
2520 * if a symbol is a typedef to another type, return true
2522 static bool is_typedef_symbol(symbol_t *symbol)
2524 const declaration_t *const declaration =
2525 get_declaration(symbol, NAMESPACE_NORMAL);
2527 declaration != NULL &&
2528 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2531 static type_t *parse_typeof(void)
2538 add_anchor_token(')');
2540 expression_t *expression = NULL;
2543 switch(token.type) {
2544 case T___extension__:
2545 /* this can be a prefix to a typename or an expression */
2546 /* we simply eat it now. */
2549 } while(token.type == T___extension__);
2553 if(is_typedef_symbol(token.v.symbol)) {
2554 type = parse_typename();
2556 expression = parse_expression();
2557 type = expression->base.type;
2562 type = parse_typename();
2566 expression = parse_expression();
2567 type = expression->base.type;
2571 rem_anchor_token(')');
2574 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2575 typeof_type->typeoft.expression = expression;
2576 typeof_type->typeoft.typeof_type = type;
2584 SPECIFIER_SIGNED = 1 << 0,
2585 SPECIFIER_UNSIGNED = 1 << 1,
2586 SPECIFIER_LONG = 1 << 2,
2587 SPECIFIER_INT = 1 << 3,
2588 SPECIFIER_DOUBLE = 1 << 4,
2589 SPECIFIER_CHAR = 1 << 5,
2590 SPECIFIER_SHORT = 1 << 6,
2591 SPECIFIER_LONG_LONG = 1 << 7,
2592 SPECIFIER_FLOAT = 1 << 8,
2593 SPECIFIER_BOOL = 1 << 9,
2594 SPECIFIER_VOID = 1 << 10,
2595 SPECIFIER_INT8 = 1 << 11,
2596 SPECIFIER_INT16 = 1 << 12,
2597 SPECIFIER_INT32 = 1 << 13,
2598 SPECIFIER_INT64 = 1 << 14,
2599 SPECIFIER_INT128 = 1 << 15,
2600 #ifdef PROVIDE_COMPLEX
2601 SPECIFIER_COMPLEX = 1 << 16,
2602 SPECIFIER_IMAGINARY = 1 << 17,
2606 static type_t *create_builtin_type(symbol_t *const symbol,
2607 type_t *const real_type)
2609 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2610 type->builtin.symbol = symbol;
2611 type->builtin.real_type = real_type;
2613 type_t *result = typehash_insert(type);
2614 if (type != result) {
2621 static type_t *get_typedef_type(symbol_t *symbol)
2623 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2624 if(declaration == NULL
2625 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2628 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2629 type->typedeft.declaration = declaration;
2635 * check for the allowed MS alignment values.
2637 static bool check_elignment_value(long long intvalue) {
2638 if(intvalue < 1 || intvalue > 8192) {
2639 errorf(HERE, "illegal alignment value");
2642 unsigned v = (unsigned)intvalue;
2643 for(unsigned i = 1; i <= 8192; i += i) {
2647 errorf(HERE, "alignment must be power of two");
2651 #define DET_MOD(name, tag) do { \
2652 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2653 *modifiers |= tag; \
2656 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2658 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2661 if(token.type == T_restrict) {
2663 DET_MOD(restrict, DM_RESTRICT);
2665 } else if(token.type != T_IDENTIFIER)
2667 symbol_t *symbol = token.v.symbol;
2668 if(symbol == sym_align) {
2671 if(token.type != T_INTEGER)
2673 if(check_elignment_value(token.v.intvalue)) {
2674 if(specifiers->alignment != 0)
2675 warningf(HERE, "align used more than once");
2676 specifiers->alignment = (unsigned char)token.v.intvalue;
2680 } else if(symbol == sym_allocate) {
2683 if(token.type != T_IDENTIFIER)
2685 (void)token.v.symbol;
2687 } else if(symbol == sym_dllimport) {
2689 DET_MOD(dllimport, DM_DLLIMPORT);
2690 } else if(symbol == sym_dllexport) {
2692 DET_MOD(dllexport, DM_DLLEXPORT);
2693 } else if(symbol == sym_thread) {
2695 DET_MOD(thread, DM_THREAD);
2696 } else if(symbol == sym_naked) {
2698 DET_MOD(naked, DM_NAKED);
2699 } else if(symbol == sym_noinline) {
2701 DET_MOD(noinline, DM_NOINLINE);
2702 } else if(symbol == sym_noreturn) {
2704 DET_MOD(noreturn, DM_NORETURN);
2705 } else if(symbol == sym_nothrow) {
2707 DET_MOD(nothrow, DM_NOTHROW);
2708 } else if(symbol == sym_novtable) {
2710 DET_MOD(novtable, DM_NOVTABLE);
2711 } else if(symbol == sym_property) {
2715 bool is_get = false;
2716 if(token.type != T_IDENTIFIER)
2718 if(token.v.symbol == sym_get) {
2720 } else if(token.v.symbol == sym_put) {
2722 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2727 if(token.type != T_IDENTIFIER)
2730 if(specifiers->get_property_sym != NULL) {
2731 errorf(HERE, "get property name already specified");
2733 specifiers->get_property_sym = token.v.symbol;
2736 if(specifiers->put_property_sym != NULL) {
2737 errorf(HERE, "put property name already specified");
2739 specifiers->put_property_sym = token.v.symbol;
2743 if(token.type == ',') {
2750 } else if(symbol == sym_selectany) {
2752 DET_MOD(selectany, DM_SELECTANY);
2753 } else if(symbol == sym_uuid) {
2756 if(token.type != T_STRING_LITERAL)
2760 } else if(symbol == sym_deprecated) {
2762 if(specifiers->deprecated != 0)
2763 warningf(HERE, "deprecated used more than once");
2764 specifiers->deprecated = 1;
2765 if(token.type == '(') {
2767 if(token.type == T_STRING_LITERAL) {
2768 specifiers->deprecated_string = token.v.string.begin;
2771 errorf(HERE, "string literal expected");
2775 } else if(symbol == sym_noalias) {
2777 DET_MOD(noalias, DM_NOALIAS);
2779 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2781 if(token.type == '(')
2785 if (token.type == ',')
2792 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2794 type_t *type = NULL;
2795 unsigned type_qualifiers = 0;
2796 unsigned type_specifiers = 0;
2799 specifiers->source_position = token.source_position;
2802 switch(token.type) {
2805 #define MATCH_STORAGE_CLASS(token, class) \
2807 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2808 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2810 specifiers->declared_storage_class = class; \
2814 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2815 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2816 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2817 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2818 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2823 add_anchor_token(')');
2824 parse_microsoft_extended_decl_modifier(specifiers);
2825 rem_anchor_token(')');
2830 switch (specifiers->declared_storage_class) {
2831 case STORAGE_CLASS_NONE:
2832 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2835 case STORAGE_CLASS_EXTERN:
2836 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2839 case STORAGE_CLASS_STATIC:
2840 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2844 errorf(HERE, "multiple storage classes in declaration specifiers");
2850 /* type qualifiers */
2851 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2853 type_qualifiers |= qualifier; \
2857 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2858 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2859 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2860 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2861 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2862 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2863 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2864 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2866 case T___extension__:
2871 /* type specifiers */
2872 #define MATCH_SPECIFIER(token, specifier, name) \
2875 if(type_specifiers & specifier) { \
2876 errorf(HERE, "multiple " name " type specifiers given"); \
2878 type_specifiers |= specifier; \
2882 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2883 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2884 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2885 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2886 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2887 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2888 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2889 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2890 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2891 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2892 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2893 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2894 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2895 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2896 #ifdef PROVIDE_COMPLEX
2897 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2898 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2900 case T__forceinline:
2901 /* only in microsoft mode */
2902 specifiers->decl_modifiers |= DM_FORCEINLINE;
2906 specifiers->is_inline = true;
2911 if(type_specifiers & SPECIFIER_LONG_LONG) {
2912 errorf(HERE, "multiple type specifiers given");
2913 } else if(type_specifiers & SPECIFIER_LONG) {
2914 type_specifiers |= SPECIFIER_LONG_LONG;
2916 type_specifiers |= SPECIFIER_LONG;
2921 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2923 type->compound.declaration = parse_compound_type_specifier(true);
2927 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2929 type->compound.declaration = parse_compound_type_specifier(false);
2933 type = parse_enum_specifier();
2936 type = parse_typeof();
2938 case T___builtin_va_list:
2939 type = duplicate_type(type_valist);
2943 case T___attribute__:
2947 case T_IDENTIFIER: {
2948 /* only parse identifier if we haven't found a type yet */
2949 if(type != NULL || type_specifiers != 0)
2950 goto finish_specifiers;
2952 type_t *typedef_type = get_typedef_type(token.v.symbol);
2954 if(typedef_type == NULL)
2955 goto finish_specifiers;
2958 type = typedef_type;
2962 /* function specifier */
2964 goto finish_specifiers;
2971 atomic_type_kind_t atomic_type;
2973 /* match valid basic types */
2974 switch(type_specifiers) {
2975 case SPECIFIER_VOID:
2976 atomic_type = ATOMIC_TYPE_VOID;
2978 case SPECIFIER_CHAR:
2979 atomic_type = ATOMIC_TYPE_CHAR;
2981 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2982 atomic_type = ATOMIC_TYPE_SCHAR;
2984 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2985 atomic_type = ATOMIC_TYPE_UCHAR;
2987 case SPECIFIER_SHORT:
2988 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2989 case SPECIFIER_SHORT | SPECIFIER_INT:
2990 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2991 atomic_type = ATOMIC_TYPE_SHORT;
2993 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2994 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2995 atomic_type = ATOMIC_TYPE_USHORT;
2998 case SPECIFIER_SIGNED:
2999 case SPECIFIER_SIGNED | SPECIFIER_INT:
3000 atomic_type = ATOMIC_TYPE_INT;
3002 case SPECIFIER_UNSIGNED:
3003 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3004 atomic_type = ATOMIC_TYPE_UINT;
3006 case SPECIFIER_LONG:
3007 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3008 case SPECIFIER_LONG | SPECIFIER_INT:
3009 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3010 atomic_type = ATOMIC_TYPE_LONG;
3012 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3013 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3014 atomic_type = ATOMIC_TYPE_ULONG;
3016 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3017 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3018 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3019 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3021 atomic_type = ATOMIC_TYPE_LONGLONG;
3023 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3024 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3026 atomic_type = ATOMIC_TYPE_ULONGLONG;
3029 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3030 atomic_type = unsigned_int8_type_kind;
3033 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3034 atomic_type = unsigned_int16_type_kind;
3037 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3038 atomic_type = unsigned_int32_type_kind;
3041 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3042 atomic_type = unsigned_int64_type_kind;
3045 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3046 atomic_type = unsigned_int128_type_kind;
3049 case SPECIFIER_INT8:
3050 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3051 atomic_type = int8_type_kind;
3054 case SPECIFIER_INT16:
3055 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3056 atomic_type = int16_type_kind;
3059 case SPECIFIER_INT32:
3060 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3061 atomic_type = int32_type_kind;
3064 case SPECIFIER_INT64:
3065 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3066 atomic_type = int64_type_kind;
3069 case SPECIFIER_INT128:
3070 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3071 atomic_type = int128_type_kind;
3074 case SPECIFIER_FLOAT:
3075 atomic_type = ATOMIC_TYPE_FLOAT;
3077 case SPECIFIER_DOUBLE:
3078 atomic_type = ATOMIC_TYPE_DOUBLE;
3080 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3081 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3083 case SPECIFIER_BOOL:
3084 atomic_type = ATOMIC_TYPE_BOOL;
3086 #ifdef PROVIDE_COMPLEX
3087 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3088 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
3090 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3091 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
3093 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3094 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
3096 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3097 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
3099 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3100 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
3102 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3103 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
3107 /* invalid specifier combination, give an error message */
3108 if(type_specifiers == 0) {
3109 if (! strict_mode) {
3110 if (warning.implicit_int) {
3111 warningf(HERE, "no type specifiers in declaration, using 'int'");
3113 atomic_type = ATOMIC_TYPE_INT;
3116 errorf(HERE, "no type specifiers given in declaration");
3118 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3119 (type_specifiers & SPECIFIER_UNSIGNED)) {
3120 errorf(HERE, "signed and unsigned specifiers gives");
3121 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3122 errorf(HERE, "only integer types can be signed or unsigned");
3124 errorf(HERE, "multiple datatypes in declaration");
3126 atomic_type = ATOMIC_TYPE_INVALID;
3129 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
3130 type->atomic.akind = atomic_type;
3133 if(type_specifiers != 0) {
3134 errorf(HERE, "multiple datatypes in declaration");
3138 type->base.qualifiers = type_qualifiers;
3139 /* FIXME: check type qualifiers here */
3141 type_t *result = typehash_insert(type);
3142 if(newtype && result != type) {
3146 specifiers->type = result;
3151 static type_qualifiers_t parse_type_qualifiers(void)
3153 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3156 switch(token.type) {
3157 /* type qualifiers */
3158 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3159 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3160 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3161 /* microsoft extended type modifiers */
3162 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3163 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3164 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3165 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3166 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3169 return type_qualifiers;
3174 static declaration_t *parse_identifier_list(void)
3176 declaration_t *declarations = NULL;
3177 declaration_t *last_declaration = NULL;
3179 declaration_t *const declaration = allocate_declaration_zero();
3180 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3181 declaration->source_position = token.source_position;
3182 declaration->symbol = token.v.symbol;
3185 if(last_declaration != NULL) {
3186 last_declaration->next = declaration;
3188 declarations = declaration;
3190 last_declaration = declaration;
3192 if(token.type != ',')
3195 } while(token.type == T_IDENTIFIER);
3197 return declarations;
3200 static void semantic_parameter(declaration_t *declaration)
3202 /* TODO: improve error messages */
3204 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3205 errorf(HERE, "typedef not allowed in parameter list");
3206 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3207 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3208 errorf(HERE, "parameter may only have none or register storage class");
3211 type_t *const orig_type = declaration->type;
3212 type_t * type = skip_typeref(orig_type);
3214 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3215 * into a pointer. § 6.7.5.3 (7) */
3216 if (is_type_array(type)) {
3217 type_t *const element_type = type->array.element_type;
3219 type = make_pointer_type(element_type, type->base.qualifiers);
3221 declaration->type = type;
3224 if(is_type_incomplete(type)) {
3225 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3226 orig_type, declaration->symbol);
3230 static declaration_t *parse_parameter(void)
3232 declaration_specifiers_t specifiers;
3233 memset(&specifiers, 0, sizeof(specifiers));
3235 parse_declaration_specifiers(&specifiers);
3237 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3239 semantic_parameter(declaration);
3244 static declaration_t *parse_parameters(function_type_t *type)
3246 if(token.type == T_IDENTIFIER) {
3247 symbol_t *symbol = token.v.symbol;
3248 if(!is_typedef_symbol(symbol)) {
3249 type->kr_style_parameters = true;
3250 return parse_identifier_list();
3254 if(token.type == ')') {
3255 type->unspecified_parameters = 1;
3258 if(token.type == T_void && look_ahead(1)->type == ')') {
3263 declaration_t *declarations = NULL;
3264 declaration_t *declaration;
3265 declaration_t *last_declaration = NULL;
3266 function_parameter_t *parameter;
3267 function_parameter_t *last_parameter = NULL;
3270 switch(token.type) {
3274 return declarations;
3277 case T___extension__:
3279 declaration = parse_parameter();
3281 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3282 memset(parameter, 0, sizeof(parameter[0]));
3283 parameter->type = declaration->type;
3285 if(last_parameter != NULL) {
3286 last_declaration->next = declaration;
3287 last_parameter->next = parameter;
3289 type->parameters = parameter;
3290 declarations = declaration;
3292 last_parameter = parameter;
3293 last_declaration = declaration;
3297 return declarations;
3299 if(token.type != ',')
3300 return declarations;
3310 } construct_type_kind_t;
3312 typedef struct construct_type_t construct_type_t;
3313 struct construct_type_t {
3314 construct_type_kind_t kind;
3315 construct_type_t *next;
3318 typedef struct parsed_pointer_t parsed_pointer_t;
3319 struct parsed_pointer_t {
3320 construct_type_t construct_type;
3321 type_qualifiers_t type_qualifiers;
3324 typedef struct construct_function_type_t construct_function_type_t;
3325 struct construct_function_type_t {
3326 construct_type_t construct_type;
3327 type_t *function_type;
3330 typedef struct parsed_array_t parsed_array_t;
3331 struct parsed_array_t {
3332 construct_type_t construct_type;
3333 type_qualifiers_t type_qualifiers;
3339 typedef struct construct_base_type_t construct_base_type_t;
3340 struct construct_base_type_t {
3341 construct_type_t construct_type;
3345 static construct_type_t *parse_pointer_declarator(void)
3349 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3350 memset(pointer, 0, sizeof(pointer[0]));
3351 pointer->construct_type.kind = CONSTRUCT_POINTER;
3352 pointer->type_qualifiers = parse_type_qualifiers();
3354 return (construct_type_t*) pointer;
3357 static construct_type_t *parse_array_declarator(void)
3360 add_anchor_token(']');
3362 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3363 memset(array, 0, sizeof(array[0]));
3364 array->construct_type.kind = CONSTRUCT_ARRAY;
3366 if(token.type == T_static) {
3367 array->is_static = true;
3371 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3372 if(type_qualifiers != 0) {
3373 if(token.type == T_static) {
3374 array->is_static = true;
3378 array->type_qualifiers = type_qualifiers;
3380 if(token.type == '*' && look_ahead(1)->type == ']') {
3381 array->is_variable = true;
3383 } else if(token.type != ']') {
3384 array->size = parse_assignment_expression();
3387 rem_anchor_token(']');
3390 return (construct_type_t*) array;
3395 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3398 add_anchor_token(')');
3401 if(declaration != NULL) {
3402 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
3404 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
3407 declaration_t *parameters = parse_parameters(&type->function);
3408 if(declaration != NULL) {
3409 declaration->scope.declarations = parameters;
3412 construct_function_type_t *construct_function_type =
3413 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3414 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3415 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3416 construct_function_type->function_type = type;
3418 rem_anchor_token(')');
3422 return (construct_type_t*) construct_function_type;
3425 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3426 bool may_be_abstract)
3428 /* construct a single linked list of construct_type_t's which describe
3429 * how to construct the final declarator type */
3430 construct_type_t *first = NULL;
3431 construct_type_t *last = NULL;
3434 while(token.type == '*') {
3435 construct_type_t *type = parse_pointer_declarator();
3446 /* TODO: find out if this is correct */
3449 construct_type_t *inner_types = NULL;
3451 switch(token.type) {
3453 if(declaration == NULL) {
3454 errorf(HERE, "no identifier expected in typename");
3456 declaration->symbol = token.v.symbol;
3457 declaration->source_position = token.source_position;
3463 add_anchor_token(')');
3464 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3465 rem_anchor_token(')');
3471 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3472 /* avoid a loop in the outermost scope, because eat_statement doesn't
3474 if(token.type == '}' && current_function == NULL) {
3482 construct_type_t *p = last;
3485 construct_type_t *type;
3486 switch(token.type) {
3488 type = parse_function_declarator(declaration);
3491 type = parse_array_declarator();
3494 goto declarator_finished;
3497 /* insert in the middle of the list (behind p) */
3499 type->next = p->next;
3510 declarator_finished:
3513 /* append inner_types at the end of the list, we don't to set last anymore
3514 * as it's not needed anymore */
3516 assert(first == NULL);
3517 first = inner_types;
3519 last->next = inner_types;
3527 static type_t *construct_declarator_type(construct_type_t *construct_list,
3530 construct_type_t *iter = construct_list;
3531 for( ; iter != NULL; iter = iter->next) {
3532 switch(iter->kind) {
3533 case CONSTRUCT_INVALID:
3534 internal_errorf(HERE, "invalid type construction found");
3535 case CONSTRUCT_FUNCTION: {
3536 construct_function_type_t *construct_function_type
3537 = (construct_function_type_t*) iter;
3539 type_t *function_type = construct_function_type->function_type;
3541 function_type->function.return_type = type;
3543 type_t *skipped_return_type = skip_typeref(type);
3544 if (is_type_function(skipped_return_type)) {
3545 errorf(HERE, "function returning function is not allowed");
3546 type = type_error_type;
3547 } else if (is_type_array(skipped_return_type)) {
3548 errorf(HERE, "function returning array is not allowed");
3549 type = type_error_type;
3551 type = function_type;
3556 case CONSTRUCT_POINTER: {
3557 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3558 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3559 pointer_type->pointer.points_to = type;
3560 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3562 type = pointer_type;
3566 case CONSTRUCT_ARRAY: {
3567 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3568 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3570 expression_t *size_expression = parsed_array->size;
3571 if(size_expression != NULL) {
3573 = create_implicit_cast(size_expression, type_size_t);
3576 array_type->base.qualifiers = parsed_array->type_qualifiers;
3577 array_type->array.element_type = type;
3578 array_type->array.is_static = parsed_array->is_static;
3579 array_type->array.is_variable = parsed_array->is_variable;
3580 array_type->array.size_expression = size_expression;
3582 if(size_expression != NULL) {
3583 if(is_constant_expression(size_expression)) {
3584 array_type->array.size_constant = true;
3585 array_type->array.size
3586 = fold_constant(size_expression);
3588 array_type->array.is_vla = true;
3592 type_t *skipped_type = skip_typeref(type);
3593 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3594 errorf(HERE, "array of void is not allowed");
3595 type = type_error_type;
3603 type_t *hashed_type = typehash_insert(type);
3604 if(hashed_type != type) {
3605 /* the function type was constructed earlier freeing it here will
3606 * destroy other types... */
3607 if(iter->kind != CONSTRUCT_FUNCTION) {
3617 static declaration_t *parse_declarator(
3618 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3620 declaration_t *const declaration = allocate_declaration_zero();
3621 declaration->declared_storage_class = specifiers->declared_storage_class;
3622 declaration->modifiers = specifiers->decl_modifiers;
3623 declaration->deprecated = specifiers->deprecated;
3624 declaration->deprecated_string = specifiers->deprecated_string;
3625 declaration->get_property_sym = specifiers->get_property_sym;
3626 declaration->put_property_sym = specifiers->put_property_sym;
3627 declaration->is_inline = specifiers->is_inline;
3629 declaration->storage_class = specifiers->declared_storage_class;
3630 if(declaration->storage_class == STORAGE_CLASS_NONE
3631 && scope != global_scope) {
3632 declaration->storage_class = STORAGE_CLASS_AUTO;
3635 if(specifiers->alignment != 0) {
3636 /* TODO: add checks here */
3637 declaration->alignment = specifiers->alignment;
3640 construct_type_t *construct_type
3641 = parse_inner_declarator(declaration, may_be_abstract);
3642 type_t *const type = specifiers->type;
3643 declaration->type = construct_declarator_type(construct_type, type);
3645 if(construct_type != NULL) {
3646 obstack_free(&temp_obst, construct_type);
3652 static type_t *parse_abstract_declarator(type_t *base_type)
3654 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3656 type_t *result = construct_declarator_type(construct_type, base_type);
3657 if(construct_type != NULL) {
3658 obstack_free(&temp_obst, construct_type);
3664 static declaration_t *append_declaration(declaration_t* const declaration)
3666 if (last_declaration != NULL) {
3667 last_declaration->next = declaration;
3669 scope->declarations = declaration;
3671 last_declaration = declaration;
3676 * Check if the declaration of main is suspicious. main should be a
3677 * function with external linkage, returning int, taking either zero
3678 * arguments, two, or three arguments of appropriate types, ie.
3680 * int main([ int argc, char **argv [, char **env ] ]).
3682 * @param decl the declaration to check
3683 * @param type the function type of the declaration
3685 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3687 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3688 warningf(decl->source_position, "'main' is normally a non-static function");
3690 if (skip_typeref(func_type->return_type) != type_int) {
3691 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3693 const function_parameter_t *parm = func_type->parameters;
3695 type_t *const first_type = parm->type;
3696 if (!types_compatible(skip_typeref(first_type), type_int)) {
3697 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3701 type_t *const second_type = parm->type;
3702 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3703 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3707 type_t *const third_type = parm->type;
3708 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3709 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3713 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3717 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3723 * Check if a symbol is the equal to "main".
3725 static bool is_sym_main(const symbol_t *const sym)
3727 return strcmp(sym->string, "main") == 0;
3730 static declaration_t *internal_record_declaration(
3731 declaration_t *const declaration,
3732 const bool is_function_definition)
3734 const symbol_t *const symbol = declaration->symbol;
3735 const namespace_t namespc = (namespace_t)declaration->namespc;
3737 type_t *const orig_type = declaration->type;
3738 type_t *const type = skip_typeref(orig_type);
3739 if (is_type_function(type) &&
3740 type->function.unspecified_parameters &&
3741 warning.strict_prototypes) {
3742 warningf(declaration->source_position,
3743 "function declaration '%#T' is not a prototype",
3744 orig_type, declaration->symbol);
3747 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3748 check_type_of_main(declaration, &type->function);
3751 assert(declaration->symbol != NULL);
3752 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3754 assert(declaration != previous_declaration);
3755 if (previous_declaration != NULL) {
3756 if (previous_declaration->parent_scope == scope) {
3757 /* can happen for K&R style declarations */
3758 if(previous_declaration->type == NULL) {
3759 previous_declaration->type = declaration->type;
3762 const type_t *prev_type = skip_typeref(previous_declaration->type);
3763 if (!types_compatible(type, prev_type)) {
3764 errorf(declaration->source_position,
3765 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3766 orig_type, symbol, previous_declaration->type, symbol,
3767 previous_declaration->source_position);
3769 unsigned old_storage_class = previous_declaration->storage_class;
3770 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3771 errorf(declaration->source_position, "redeclaration of enum entry '%Y' (declared %P)",
3772 symbol, previous_declaration->source_position);
3773 return previous_declaration;
3776 unsigned new_storage_class = declaration->storage_class;
3778 if(is_type_incomplete(prev_type)) {
3779 previous_declaration->type = type;
3783 /* pretend no storage class means extern for function
3784 * declarations (except if the previous declaration is neither
3785 * none nor extern) */
3786 if (is_type_function(type)) {
3787 switch (old_storage_class) {
3788 case STORAGE_CLASS_NONE:
3789 old_storage_class = STORAGE_CLASS_EXTERN;
3791 case STORAGE_CLASS_EXTERN:
3792 if (is_function_definition) {
3793 if (warning.missing_prototypes &&
3794 prev_type->function.unspecified_parameters &&
3795 !is_sym_main(symbol)) {
3796 warningf(declaration->source_position,
3797 "no previous prototype for '%#T'",
3800 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3801 new_storage_class = STORAGE_CLASS_EXTERN;
3809 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3810 new_storage_class == STORAGE_CLASS_EXTERN) {
3811 warn_redundant_declaration:
3812 if (warning.redundant_decls) {
3813 warningf(declaration->source_position,
3814 "redundant declaration for '%Y' (declared %P)",
3815 symbol, previous_declaration->source_position);
3817 } else if (current_function == NULL) {
3818 if (old_storage_class != STORAGE_CLASS_STATIC &&
3819 new_storage_class == STORAGE_CLASS_STATIC) {
3820 errorf(declaration->source_position,
3821 "static declaration of '%Y' follows non-static declaration (declared %P)",
3822 symbol, previous_declaration->source_position);
3824 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3825 goto warn_redundant_declaration;
3827 if (new_storage_class == STORAGE_CLASS_NONE) {
3828 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3829 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3833 if (old_storage_class == new_storage_class) {
3834 errorf(declaration->source_position,
3835 "redeclaration of '%Y' (declared %P)",
3836 symbol, previous_declaration->source_position);
3838 errorf(declaration->source_position,
3839 "redeclaration of '%Y' with different linkage (declared %P)",
3840 symbol, previous_declaration->source_position);
3844 return previous_declaration;
3846 } else if (is_function_definition) {
3847 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3848 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3849 warningf(declaration->source_position,
3850 "no previous prototype for '%#T'", orig_type, symbol);
3851 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3852 warningf(declaration->source_position,
3853 "no previous declaration for '%#T'", orig_type,
3857 } else if (warning.missing_declarations &&
3858 scope == global_scope &&
3859 !is_type_function(type) && (
3860 declaration->storage_class == STORAGE_CLASS_NONE ||
3861 declaration->storage_class == STORAGE_CLASS_THREAD
3863 warningf(declaration->source_position,
3864 "no previous declaration for '%#T'", orig_type, symbol);
3867 assert(declaration->parent_scope == NULL);
3868 assert(scope != NULL);
3870 declaration->parent_scope = scope;
3872 environment_push(declaration);
3873 return append_declaration(declaration);
3876 static declaration_t *record_declaration(declaration_t *declaration)
3878 return internal_record_declaration(declaration, false);
3881 static declaration_t *record_function_definition(declaration_t *declaration)
3883 return internal_record_declaration(declaration, true);
3886 static void parser_error_multiple_definition(declaration_t *declaration,
3887 const source_position_t source_position)
3889 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
3890 declaration->symbol, declaration->source_position);
3893 static bool is_declaration_specifier(const token_t *token,
3894 bool only_type_specifiers)
3896 switch(token->type) {
3900 return is_typedef_symbol(token->v.symbol);
3902 case T___extension__:
3905 return !only_type_specifiers;
3912 static void parse_init_declarator_rest(declaration_t *declaration)
3916 type_t *orig_type = declaration->type;
3917 type_t *type = skip_typeref(orig_type);
3919 if(declaration->init.initializer != NULL) {
3920 parser_error_multiple_definition(declaration, token.source_position);
3923 bool must_be_constant = false;
3924 if(declaration->storage_class == STORAGE_CLASS_STATIC
3925 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3926 || declaration->parent_scope == global_scope) {
3927 must_be_constant = true;
3930 parse_initializer_env_t env;
3931 env.type = orig_type;
3932 env.must_be_constant = must_be_constant;
3933 env.declaration = declaration;
3935 initializer_t *initializer = parse_initializer(&env);
3937 if(env.type != orig_type) {
3938 orig_type = env.type;
3939 type = skip_typeref(orig_type);
3940 declaration->type = env.type;
3943 if(is_type_function(type)) {
3944 errorf(declaration->source_position,
3945 "initializers not allowed for function types at declator '%Y' (type '%T')",
3946 declaration->symbol, orig_type);
3948 declaration->init.initializer = initializer;
3952 /* parse rest of a declaration without any declarator */
3953 static void parse_anonymous_declaration_rest(
3954 const declaration_specifiers_t *specifiers,
3955 parsed_declaration_func finished_declaration)
3959 declaration_t *const declaration = allocate_declaration_zero();
3960 declaration->type = specifiers->type;
3961 declaration->declared_storage_class = specifiers->declared_storage_class;
3962 declaration->source_position = specifiers->source_position;
3963 declaration->modifiers = specifiers->decl_modifiers;
3965 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3966 warningf(declaration->source_position, "useless storage class in empty declaration");
3968 declaration->storage_class = STORAGE_CLASS_NONE;
3970 type_t *type = declaration->type;
3971 switch (type->kind) {
3972 case TYPE_COMPOUND_STRUCT:
3973 case TYPE_COMPOUND_UNION: {
3974 if (type->compound.declaration->symbol == NULL) {
3975 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3984 warningf(declaration->source_position, "empty declaration");
3988 finished_declaration(declaration);
3991 static void parse_declaration_rest(declaration_t *ndeclaration,
3992 const declaration_specifiers_t *specifiers,
3993 parsed_declaration_func finished_declaration)
3995 add_anchor_token(';');
3996 add_anchor_token('=');
3997 add_anchor_token(',');
3999 declaration_t *declaration = finished_declaration(ndeclaration);
4001 type_t *orig_type = declaration->type;
4002 type_t *type = skip_typeref(orig_type);
4004 if (type->kind != TYPE_FUNCTION &&
4005 declaration->is_inline &&
4006 is_type_valid(type)) {
4007 warningf(declaration->source_position,
4008 "variable '%Y' declared 'inline'\n", declaration->symbol);
4011 if(token.type == '=') {
4012 parse_init_declarator_rest(declaration);
4015 if(token.type != ',')
4019 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4024 rem_anchor_token(';');
4025 rem_anchor_token('=');
4026 rem_anchor_token(',');
4029 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4031 symbol_t *symbol = declaration->symbol;
4032 if(symbol == NULL) {
4033 errorf(HERE, "anonymous declaration not valid as function parameter");
4036 namespace_t namespc = (namespace_t) declaration->namespc;
4037 if(namespc != NAMESPACE_NORMAL) {
4038 return record_declaration(declaration);
4041 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4042 if(previous_declaration == NULL ||
4043 previous_declaration->parent_scope != scope) {
4044 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4049 if(previous_declaration->type == NULL) {
4050 previous_declaration->type = declaration->type;
4051 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4052 previous_declaration->storage_class = declaration->storage_class;
4053 previous_declaration->parent_scope = scope;
4054 return previous_declaration;
4056 return record_declaration(declaration);
4060 static void parse_declaration(parsed_declaration_func finished_declaration)
4062 declaration_specifiers_t specifiers;
4063 memset(&specifiers, 0, sizeof(specifiers));
4064 parse_declaration_specifiers(&specifiers);
4066 if(token.type == ';') {
4067 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4069 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4070 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4074 static void parse_kr_declaration_list(declaration_t *declaration)
4076 type_t *type = skip_typeref(declaration->type);
4077 if(!is_type_function(type))
4080 if(!type->function.kr_style_parameters)
4083 /* push function parameters */
4084 int top = environment_top();
4085 scope_t *last_scope = scope;
4086 set_scope(&declaration->scope);
4088 declaration_t *parameter = declaration->scope.declarations;
4089 for( ; parameter != NULL; parameter = parameter->next) {
4090 assert(parameter->parent_scope == NULL);
4091 parameter->parent_scope = scope;
4092 environment_push(parameter);
4095 /* parse declaration list */
4096 while(is_declaration_specifier(&token, false)) {
4097 parse_declaration(finished_kr_declaration);
4100 /* pop function parameters */
4101 assert(scope == &declaration->scope);
4102 set_scope(last_scope);
4103 environment_pop_to(top);
4105 /* update function type */
4106 type_t *new_type = duplicate_type(type);
4107 new_type->function.kr_style_parameters = false;
4109 function_parameter_t *parameters = NULL;
4110 function_parameter_t *last_parameter = NULL;
4112 declaration_t *parameter_declaration = declaration->scope.declarations;
4113 for( ; parameter_declaration != NULL;
4114 parameter_declaration = parameter_declaration->next) {
4115 type_t *parameter_type = parameter_declaration->type;
4116 if(parameter_type == NULL) {
4118 errorf(HERE, "no type specified for function parameter '%Y'",
4119 parameter_declaration->symbol);
4121 if (warning.implicit_int) {
4122 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4123 parameter_declaration->symbol);
4125 parameter_type = type_int;
4126 parameter_declaration->type = parameter_type;
4130 semantic_parameter(parameter_declaration);
4131 parameter_type = parameter_declaration->type;
4133 function_parameter_t *function_parameter
4134 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4135 memset(function_parameter, 0, sizeof(function_parameter[0]));
4137 function_parameter->type = parameter_type;
4138 if(last_parameter != NULL) {
4139 last_parameter->next = function_parameter;
4141 parameters = function_parameter;
4143 last_parameter = function_parameter;
4145 new_type->function.parameters = parameters;
4147 type = typehash_insert(new_type);
4148 if(type != new_type) {
4149 obstack_free(type_obst, new_type);
4152 declaration->type = type;
4155 static bool first_err = true;
4158 * When called with first_err set, prints the name of the current function,
4161 static void print_in_function(void) {
4164 diagnosticf("%s: In function '%Y':\n",
4165 current_function->source_position.input_name,
4166 current_function->symbol);
4171 * Check if all labels are defined in the current function.
4172 * Check if all labels are used in the current function.
4174 static void check_labels(void)
4176 for (const goto_statement_t *goto_statement = goto_first;
4177 goto_statement != NULL;
4178 goto_statement = goto_statement->next) {
4179 declaration_t *label = goto_statement->label;
4182 if (label->source_position.input_name == NULL) {
4183 print_in_function();
4184 errorf(goto_statement->base.source_position,
4185 "label '%Y' used but not defined", label->symbol);
4188 goto_first = goto_last = NULL;
4190 if (warning.unused_label) {
4191 for (const label_statement_t *label_statement = label_first;
4192 label_statement != NULL;
4193 label_statement = label_statement->next) {
4194 const declaration_t *label = label_statement->label;
4196 if (! label->used) {
4197 print_in_function();
4198 warningf(label_statement->base.source_position,
4199 "label '%Y' defined but not used", label->symbol);
4203 label_first = label_last = NULL;
4207 * Check declarations of current_function for unused entities.
4209 static void check_declarations(void)
4211 if (warning.unused_parameter) {
4212 const scope_t *scope = ¤t_function->scope;
4214 const declaration_t *parameter = scope->declarations;
4215 for (; parameter != NULL; parameter = parameter->next) {
4216 if (! parameter->used) {
4217 print_in_function();
4218 warningf(parameter->source_position,
4219 "unused parameter '%Y'", parameter->symbol);
4223 if (warning.unused_variable) {
4227 static void parse_external_declaration(void)
4229 /* function-definitions and declarations both start with declaration
4231 declaration_specifiers_t specifiers;
4232 memset(&specifiers, 0, sizeof(specifiers));
4234 add_anchor_token(';');
4235 parse_declaration_specifiers(&specifiers);
4236 rem_anchor_token(';');
4238 /* must be a declaration */
4239 if(token.type == ';') {
4240 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4244 add_anchor_token(',');
4245 add_anchor_token('=');
4246 rem_anchor_token(';');
4248 /* declarator is common to both function-definitions and declarations */
4249 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4251 rem_anchor_token(',');
4252 rem_anchor_token('=');
4253 rem_anchor_token(';');
4255 /* must be a declaration */
4256 if(token.type == ',' || token.type == '=' || token.type == ';') {
4257 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4261 /* must be a function definition */
4262 parse_kr_declaration_list(ndeclaration);
4264 if(token.type != '{') {
4265 parse_error_expected("while parsing function definition", '{', 0);
4266 eat_until_matching_token(';');
4270 type_t *type = ndeclaration->type;
4272 /* note that we don't skip typerefs: the standard doesn't allow them here
4273 * (so we can't use is_type_function here) */
4274 if(type->kind != TYPE_FUNCTION) {
4275 if (is_type_valid(type)) {
4276 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4277 type, ndeclaration->symbol);
4283 /* § 6.7.5.3 (14) a function definition with () means no
4284 * parameters (and not unspecified parameters) */
4285 if(type->function.unspecified_parameters) {
4286 type_t *duplicate = duplicate_type(type);
4287 duplicate->function.unspecified_parameters = false;
4289 type = typehash_insert(duplicate);
4290 if(type != duplicate) {
4291 obstack_free(type_obst, duplicate);
4293 ndeclaration->type = type;
4296 declaration_t *const declaration = record_function_definition(ndeclaration);
4297 if(ndeclaration != declaration) {
4298 declaration->scope = ndeclaration->scope;
4300 type = skip_typeref(declaration->type);
4302 /* push function parameters and switch scope */
4303 int top = environment_top();
4304 scope_t *last_scope = scope;
4305 set_scope(&declaration->scope);
4307 declaration_t *parameter = declaration->scope.declarations;
4308 for( ; parameter != NULL; parameter = parameter->next) {
4309 if(parameter->parent_scope == &ndeclaration->scope) {
4310 parameter->parent_scope = scope;
4312 assert(parameter->parent_scope == NULL
4313 || parameter->parent_scope == scope);
4314 parameter->parent_scope = scope;
4315 environment_push(parameter);
4318 if(declaration->init.statement != NULL) {
4319 parser_error_multiple_definition(declaration, token.source_position);
4321 goto end_of_parse_external_declaration;
4323 /* parse function body */
4324 int label_stack_top = label_top();
4325 declaration_t *old_current_function = current_function;
4326 current_function = declaration;
4328 declaration->init.statement = parse_compound_statement();
4331 check_declarations();
4333 assert(current_function == declaration);
4334 current_function = old_current_function;
4335 label_pop_to(label_stack_top);
4338 end_of_parse_external_declaration:
4339 assert(scope == &declaration->scope);
4340 set_scope(last_scope);
4341 environment_pop_to(top);
4344 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4345 source_position_t source_position)
4347 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4348 type->bitfield.base = base;
4349 type->bitfield.size = size;
4354 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4357 declaration_t *iter = compound_declaration->scope.declarations;
4358 for( ; iter != NULL; iter = iter->next) {
4359 if(iter->namespc != NAMESPACE_NORMAL)
4362 if(iter->symbol == NULL) {
4363 type_t *type = skip_typeref(iter->type);
4364 if(is_type_compound(type)) {
4365 declaration_t *result
4366 = find_compound_entry(type->compound.declaration, symbol);
4373 if(iter->symbol == symbol) {
4381 static void parse_compound_declarators(declaration_t *struct_declaration,
4382 const declaration_specifiers_t *specifiers)
4384 declaration_t *last_declaration = struct_declaration->scope.declarations;
4385 if(last_declaration != NULL) {
4386 while(last_declaration->next != NULL) {
4387 last_declaration = last_declaration->next;
4392 declaration_t *declaration;
4394 if(token.type == ':') {
4395 source_position_t source_position = HERE;
4398 type_t *base_type = specifiers->type;
4399 expression_t *size = parse_constant_expression();
4401 if(!is_type_integer(skip_typeref(base_type))) {
4402 errorf(HERE, "bitfield base type '%T' is not an integer type",
4406 type_t *type = make_bitfield_type(base_type, size, source_position);
4408 declaration = allocate_declaration_zero();
4409 declaration->namespc = NAMESPACE_NORMAL;
4410 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4411 declaration->storage_class = STORAGE_CLASS_NONE;
4412 declaration->source_position = source_position;
4413 declaration->modifiers = specifiers->decl_modifiers;
4414 declaration->type = type;
4416 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4418 type_t *orig_type = declaration->type;
4419 type_t *type = skip_typeref(orig_type);
4421 if(token.type == ':') {
4422 source_position_t source_position = HERE;
4424 expression_t *size = parse_constant_expression();
4426 if(!is_type_integer(type)) {
4427 errorf(HERE, "bitfield base type '%T' is not an "
4428 "integer type", orig_type);
4431 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
4432 declaration->type = bitfield_type;
4434 /* TODO we ignore arrays for now... what is missing is a check
4435 * that they're at the end of the struct */
4436 if(is_type_incomplete(type) && !is_type_array(type)) {
4438 "compound member '%Y' has incomplete type '%T'",
4439 declaration->symbol, orig_type);
4440 } else if(is_type_function(type)) {
4441 errorf(HERE, "compound member '%Y' must not have function "
4442 "type '%T'", declaration->symbol, orig_type);
4447 /* make sure we don't define a symbol multiple times */
4448 symbol_t *symbol = declaration->symbol;
4449 if(symbol != NULL) {
4450 declaration_t *prev_decl
4451 = find_compound_entry(struct_declaration, symbol);
4453 if(prev_decl != NULL) {
4454 assert(prev_decl->symbol == symbol);
4455 errorf(declaration->source_position,
4456 "multiple declarations of symbol '%Y' (declared %P)",
4457 symbol, prev_decl->source_position);
4461 /* append declaration */
4462 if(last_declaration != NULL) {
4463 last_declaration->next = declaration;
4465 struct_declaration->scope.declarations = declaration;
4467 last_declaration = declaration;
4469 if(token.type != ',')
4479 static void parse_compound_type_entries(declaration_t *compound_declaration)
4482 add_anchor_token('}');
4484 while(token.type != '}' && token.type != T_EOF) {
4485 declaration_specifiers_t specifiers;
4486 memset(&specifiers, 0, sizeof(specifiers));
4487 parse_declaration_specifiers(&specifiers);
4489 parse_compound_declarators(compound_declaration, &specifiers);
4491 rem_anchor_token('}');
4493 if(token.type == T_EOF) {
4494 errorf(HERE, "EOF while parsing struct");
4499 static type_t *parse_typename(void)
4501 declaration_specifiers_t specifiers;
4502 memset(&specifiers, 0, sizeof(specifiers));
4503 parse_declaration_specifiers(&specifiers);
4504 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4505 /* TODO: improve error message, user does probably not know what a
4506 * storage class is...
4508 errorf(HERE, "typename may not have a storage class");
4511 type_t *result = parse_abstract_declarator(specifiers.type);
4519 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4520 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4521 expression_t *left);
4523 typedef struct expression_parser_function_t expression_parser_function_t;
4524 struct expression_parser_function_t {
4525 unsigned precedence;
4526 parse_expression_function parser;
4527 unsigned infix_precedence;
4528 parse_expression_infix_function infix_parser;
4531 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4534 * Prints an error message if an expression was expected but not read
4536 static expression_t *expected_expression_error(void)
4538 /* skip the error message if the error token was read */
4539 if (token.type != T_ERROR) {
4540 errorf(HERE, "expected expression, got token '%K'", &token);
4544 return create_invalid_expression();
4548 * Parse a string constant.
4550 static expression_t *parse_string_const(void)
4553 if (token.type == T_STRING_LITERAL) {
4554 string_t res = token.v.string;
4556 while (token.type == T_STRING_LITERAL) {
4557 res = concat_strings(&res, &token.v.string);
4560 if (token.type != T_WIDE_STRING_LITERAL) {
4561 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4562 /* note: that we use type_char_ptr here, which is already the
4563 * automatic converted type. revert_automatic_type_conversion
4564 * will construct the array type */
4565 cnst->base.type = type_char_ptr;
4566 cnst->string.value = res;
4570 wres = concat_string_wide_string(&res, &token.v.wide_string);
4572 wres = token.v.wide_string;
4577 switch (token.type) {
4578 case T_WIDE_STRING_LITERAL:
4579 wres = concat_wide_strings(&wres, &token.v.wide_string);
4582 case T_STRING_LITERAL:
4583 wres = concat_wide_string_string(&wres, &token.v.string);
4587 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4588 cnst->base.type = type_wchar_t_ptr;
4589 cnst->wide_string.value = wres;
4598 * Parse an integer constant.
4600 static expression_t *parse_int_const(void)
4602 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4603 cnst->base.source_position = HERE;
4604 cnst->base.type = token.datatype;
4605 cnst->conste.v.int_value = token.v.intvalue;
4613 * Parse a character constant.
4615 static expression_t *parse_character_constant(void)
4617 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4619 cnst->base.source_position = HERE;
4620 cnst->base.type = token.datatype;
4621 cnst->conste.v.character = token.v.string;
4623 if (cnst->conste.v.character.size != 1) {
4624 if (warning.multichar && (c_mode & _GNUC)) {
4626 warningf(HERE, "multi-character character constant");
4628 errorf(HERE, "more than 1 characters in character constant");
4637 * Parse a wide character constant.
4639 static expression_t *parse_wide_character_constant(void)
4641 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4643 cnst->base.source_position = HERE;
4644 cnst->base.type = token.datatype;
4645 cnst->conste.v.wide_character = token.v.wide_string;
4647 if (cnst->conste.v.wide_character.size != 1) {
4648 if (warning.multichar && (c_mode & _GNUC)) {
4650 warningf(HERE, "multi-character character constant");
4652 errorf(HERE, "more than 1 characters in character constant");
4661 * Parse a float constant.
4663 static expression_t *parse_float_const(void)
4665 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4666 cnst->base.type = token.datatype;
4667 cnst->conste.v.float_value = token.v.floatvalue;
4674 static declaration_t *create_implicit_function(symbol_t *symbol,
4675 const source_position_t source_position)
4677 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4678 ntype->function.return_type = type_int;
4679 ntype->function.unspecified_parameters = true;
4681 type_t *type = typehash_insert(ntype);
4686 declaration_t *const declaration = allocate_declaration_zero();
4687 declaration->storage_class = STORAGE_CLASS_EXTERN;
4688 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4689 declaration->type = type;
4690 declaration->symbol = symbol;
4691 declaration->source_position = source_position;
4692 declaration->parent_scope = global_scope;
4694 scope_t *old_scope = scope;
4695 set_scope(global_scope);
4697 environment_push(declaration);
4698 /* prepends the declaration to the global declarations list */
4699 declaration->next = scope->declarations;
4700 scope->declarations = declaration;
4702 assert(scope == global_scope);
4703 set_scope(old_scope);
4709 * Creates a return_type (func)(argument_type) function type if not
4712 * @param return_type the return type
4713 * @param argument_type the argument type
4715 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4717 function_parameter_t *parameter
4718 = obstack_alloc(type_obst, sizeof(parameter[0]));
4719 memset(parameter, 0, sizeof(parameter[0]));
4720 parameter->type = argument_type;
4722 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4723 type->function.return_type = return_type;
4724 type->function.parameters = parameter;
4726 type_t *result = typehash_insert(type);
4727 if(result != type) {
4735 * Creates a function type for some function like builtins.
4737 * @param symbol the symbol describing the builtin
4739 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4741 switch(symbol->ID) {
4742 case T___builtin_alloca:
4743 return make_function_1_type(type_void_ptr, type_size_t);
4744 case T___builtin_nan:
4745 return make_function_1_type(type_double, type_char_ptr);
4746 case T___builtin_nanf:
4747 return make_function_1_type(type_float, type_char_ptr);
4748 case T___builtin_nand:
4749 return make_function_1_type(type_long_double, type_char_ptr);
4750 case T___builtin_va_end:
4751 return make_function_1_type(type_void, type_valist);
4753 internal_errorf(HERE, "not implemented builtin symbol found");
4758 * Performs automatic type cast as described in § 6.3.2.1.
4760 * @param orig_type the original type
4762 static type_t *automatic_type_conversion(type_t *orig_type)
4764 type_t *type = skip_typeref(orig_type);
4765 if(is_type_array(type)) {
4766 array_type_t *array_type = &type->array;
4767 type_t *element_type = array_type->element_type;
4768 unsigned qualifiers = array_type->type.qualifiers;
4770 return make_pointer_type(element_type, qualifiers);
4773 if(is_type_function(type)) {
4774 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4781 * reverts the automatic casts of array to pointer types and function
4782 * to function-pointer types as defined § 6.3.2.1
4784 type_t *revert_automatic_type_conversion(const expression_t *expression)
4786 switch (expression->kind) {
4787 case EXPR_REFERENCE: return expression->reference.declaration->type;
4788 case EXPR_SELECT: return expression->select.compound_entry->type;
4790 case EXPR_UNARY_DEREFERENCE: {
4791 const expression_t *const value = expression->unary.value;
4792 type_t *const type = skip_typeref(value->base.type);
4793 assert(is_type_pointer(type));
4794 return type->pointer.points_to;
4797 case EXPR_BUILTIN_SYMBOL:
4798 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4800 case EXPR_ARRAY_ACCESS: {
4801 const expression_t *array_ref = expression->array_access.array_ref;
4802 type_t *type_left = skip_typeref(array_ref->base.type);
4803 if (!is_type_valid(type_left))
4805 assert(is_type_pointer(type_left));
4806 return type_left->pointer.points_to;
4809 case EXPR_STRING_LITERAL: {
4810 size_t size = expression->string.value.size;
4811 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4814 case EXPR_WIDE_STRING_LITERAL: {
4815 size_t size = expression->wide_string.value.size;
4816 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4819 case EXPR_COMPOUND_LITERAL:
4820 return expression->compound_literal.type;
4825 return expression->base.type;
4828 static expression_t *parse_reference(void)
4830 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4832 reference_expression_t *ref = &expression->reference;
4833 ref->symbol = token.v.symbol;
4835 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4837 source_position_t source_position = token.source_position;
4840 if(declaration == NULL) {
4841 if (! strict_mode && token.type == '(') {
4842 /* an implicitly defined function */
4843 if (warning.implicit_function_declaration) {
4844 warningf(HERE, "implicit declaration of function '%Y'",
4848 declaration = create_implicit_function(ref->symbol,
4851 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4852 return create_invalid_expression();
4856 type_t *type = declaration->type;
4858 /* we always do the auto-type conversions; the & and sizeof parser contains
4859 * code to revert this! */
4860 type = automatic_type_conversion(type);
4862 ref->declaration = declaration;
4863 ref->base.type = type;
4865 /* this declaration is used */
4866 declaration->used = true;
4868 /* check for deprecated functions */
4869 if(declaration->deprecated != 0) {
4870 const char *prefix = "";
4871 if (is_type_function(declaration->type))
4872 prefix = "function ";
4874 if (declaration->deprecated_string != NULL) {
4875 warningf(source_position,
4876 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4877 declaration->deprecated_string);
4879 warningf(source_position,
4880 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4887 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4891 /* TODO check if explicit cast is allowed and issue warnings/errors */
4894 static expression_t *parse_compound_literal(type_t *type)
4896 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4898 parse_initializer_env_t env;
4900 env.declaration = NULL;
4901 env.must_be_constant = false;
4902 initializer_t *initializer = parse_initializer(&env);
4905 expression->compound_literal.initializer = initializer;
4906 expression->compound_literal.type = type;
4907 expression->base.type = automatic_type_conversion(type);
4913 * Parse a cast expression.
4915 static expression_t *parse_cast(void)
4917 source_position_t source_position = token.source_position;
4919 type_t *type = parse_typename();
4921 /* matching add_anchor_token() is at call site */
4922 rem_anchor_token(')');
4925 if(token.type == '{') {
4926 return parse_compound_literal(type);
4929 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4930 cast->base.source_position = source_position;
4932 expression_t *value = parse_sub_expression(20);
4934 check_cast_allowed(value, type);
4936 cast->base.type = type;
4937 cast->unary.value = value;
4941 return create_invalid_expression();
4945 * Parse a statement expression.
4947 static expression_t *parse_statement_expression(void)
4949 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4951 statement_t *statement = parse_compound_statement();
4952 expression->statement.statement = statement;
4953 expression->base.source_position = statement->base.source_position;
4955 /* find last statement and use its type */
4956 type_t *type = type_void;
4957 const statement_t *stmt = statement->compound.statements;
4959 while (stmt->base.next != NULL)
4960 stmt = stmt->base.next;
4962 if (stmt->kind == STATEMENT_EXPRESSION) {
4963 type = stmt->expression.expression->base.type;
4966 warningf(expression->base.source_position, "empty statement expression ({})");
4968 expression->base.type = type;
4974 return create_invalid_expression();
4978 * Parse a braced expression.
4980 static expression_t *parse_brace_expression(void)
4983 add_anchor_token(')');
4985 switch(token.type) {
4987 /* gcc extension: a statement expression */
4988 return parse_statement_expression();
4992 return parse_cast();
4994 if(is_typedef_symbol(token.v.symbol)) {
4995 return parse_cast();
4999 expression_t *result = parse_expression();
5000 rem_anchor_token(')');
5005 return create_invalid_expression();
5008 static expression_t *parse_function_keyword(void)
5013 if (current_function == NULL) {
5014 errorf(HERE, "'__func__' used outside of a function");
5017 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5018 expression->base.type = type_char_ptr;
5019 expression->funcname.kind = FUNCNAME_FUNCTION;
5024 static expression_t *parse_pretty_function_keyword(void)
5026 eat(T___PRETTY_FUNCTION__);
5028 if (current_function == NULL) {
5029 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5032 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5033 expression->base.type = type_char_ptr;
5034 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5039 static expression_t *parse_funcsig_keyword(void)
5043 if (current_function == NULL) {
5044 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5047 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5048 expression->base.type = type_char_ptr;
5049 expression->funcname.kind = FUNCNAME_FUNCSIG;
5054 static expression_t *parse_funcdname_keyword(void)
5056 eat(T___FUNCDNAME__);
5058 if (current_function == NULL) {
5059 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5062 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5063 expression->base.type = type_char_ptr;
5064 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5069 static designator_t *parse_designator(void)
5071 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5072 result->source_position = HERE;
5074 if(token.type != T_IDENTIFIER) {
5075 parse_error_expected("while parsing member designator",
5079 result->symbol = token.v.symbol;
5082 designator_t *last_designator = result;
5084 if(token.type == '.') {
5086 if(token.type != T_IDENTIFIER) {
5087 parse_error_expected("while parsing member designator",
5091 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5092 designator->source_position = HERE;
5093 designator->symbol = token.v.symbol;
5096 last_designator->next = designator;
5097 last_designator = designator;
5100 if(token.type == '[') {
5102 add_anchor_token(']');
5103 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5104 designator->source_position = HERE;
5105 designator->array_index = parse_expression();
5106 rem_anchor_token(']');
5108 if(designator->array_index == NULL) {
5112 last_designator->next = designator;
5113 last_designator = designator;
5125 * Parse the __builtin_offsetof() expression.
5127 static expression_t *parse_offsetof(void)
5129 eat(T___builtin_offsetof);
5131 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5132 expression->base.type = type_size_t;
5135 add_anchor_token(',');
5136 type_t *type = parse_typename();
5137 rem_anchor_token(',');
5139 add_anchor_token(')');
5140 designator_t *designator = parse_designator();
5141 rem_anchor_token(')');
5144 expression->offsetofe.type = type;
5145 expression->offsetofe.designator = designator;
5148 memset(&path, 0, sizeof(path));
5149 path.top_type = type;
5150 path.path = NEW_ARR_F(type_path_entry_t, 0);
5152 descend_into_subtype(&path);
5154 if(!walk_designator(&path, designator, true)) {
5155 return create_invalid_expression();
5158 DEL_ARR_F(path.path);
5162 return create_invalid_expression();
5166 * Parses a _builtin_va_start() expression.
5168 static expression_t *parse_va_start(void)
5170 eat(T___builtin_va_start);
5172 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5175 add_anchor_token(',');
5176 expression->va_starte.ap = parse_assignment_expression();
5177 rem_anchor_token(',');
5179 expression_t *const expr = parse_assignment_expression();
5180 if (expr->kind == EXPR_REFERENCE) {
5181 declaration_t *const decl = expr->reference.declaration;
5183 return create_invalid_expression();
5184 if (decl->parent_scope == ¤t_function->scope &&
5185 decl->next == NULL) {
5186 expression->va_starte.parameter = decl;
5191 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
5193 return create_invalid_expression();
5197 * Parses a _builtin_va_arg() expression.
5199 static expression_t *parse_va_arg(void)
5201 eat(T___builtin_va_arg);
5203 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5206 expression->va_arge.ap = parse_assignment_expression();
5208 expression->base.type = parse_typename();
5213 return create_invalid_expression();
5216 static expression_t *parse_builtin_symbol(void)
5218 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5220 symbol_t *symbol = token.v.symbol;
5222 expression->builtin_symbol.symbol = symbol;
5225 type_t *type = get_builtin_symbol_type(symbol);
5226 type = automatic_type_conversion(type);
5228 expression->base.type = type;
5233 * Parses a __builtin_constant() expression.
5235 static expression_t *parse_builtin_constant(void)
5237 eat(T___builtin_constant_p);
5239 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5242 add_anchor_token(')');
5243 expression->builtin_constant.value = parse_assignment_expression();
5244 rem_anchor_token(')');
5246 expression->base.type = type_int;
5250 return create_invalid_expression();
5254 * Parses a __builtin_prefetch() expression.
5256 static expression_t *parse_builtin_prefetch(void)
5258 eat(T___builtin_prefetch);
5260 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5263 add_anchor_token(')');
5264 expression->builtin_prefetch.adr = parse_assignment_expression();
5265 if (token.type == ',') {
5267 expression->builtin_prefetch.rw = parse_assignment_expression();
5269 if (token.type == ',') {
5271 expression->builtin_prefetch.locality = parse_assignment_expression();
5273 rem_anchor_token(')');
5275 expression->base.type = type_void;
5279 return create_invalid_expression();
5283 * Parses a __builtin_is_*() compare expression.
5285 static expression_t *parse_compare_builtin(void)
5287 expression_t *expression;
5289 switch(token.type) {
5290 case T___builtin_isgreater:
5291 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5293 case T___builtin_isgreaterequal:
5294 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5296 case T___builtin_isless:
5297 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5299 case T___builtin_islessequal:
5300 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5302 case T___builtin_islessgreater:
5303 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5305 case T___builtin_isunordered:
5306 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5309 internal_errorf(HERE, "invalid compare builtin found");
5312 expression->base.source_position = HERE;
5316 expression->binary.left = parse_assignment_expression();
5318 expression->binary.right = parse_assignment_expression();
5321 type_t *const orig_type_left = expression->binary.left->base.type;
5322 type_t *const orig_type_right = expression->binary.right->base.type;
5324 type_t *const type_left = skip_typeref(orig_type_left);
5325 type_t *const type_right = skip_typeref(orig_type_right);
5326 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5327 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5328 type_error_incompatible("invalid operands in comparison",
5329 expression->base.source_position, orig_type_left, orig_type_right);
5332 semantic_comparison(&expression->binary);
5337 return create_invalid_expression();
5341 * Parses a __builtin_expect() expression.
5343 static expression_t *parse_builtin_expect(void)
5345 eat(T___builtin_expect);
5347 expression_t *expression
5348 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5351 expression->binary.left = parse_assignment_expression();
5353 expression->binary.right = parse_constant_expression();
5356 expression->base.type = expression->binary.left->base.type;
5360 return create_invalid_expression();
5364 * Parses a MS assume() expression.
5366 static expression_t *parse_assume(void) {
5369 expression_t *expression
5370 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5373 add_anchor_token(')');
5374 expression->unary.value = parse_assignment_expression();
5375 rem_anchor_token(')');
5378 expression->base.type = type_void;
5381 return create_invalid_expression();
5385 * Parse a microsoft __noop expression.
5387 static expression_t *parse_noop_expression(void) {
5388 source_position_t source_position = HERE;
5391 if (token.type == '(') {
5392 /* parse arguments */
5394 add_anchor_token(')');
5395 add_anchor_token(',');
5397 if(token.type != ')') {
5399 (void)parse_assignment_expression();
5400 if(token.type != ',')
5406 rem_anchor_token(',');
5407 rem_anchor_token(')');
5410 /* the result is a (int)0 */
5411 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5412 cnst->base.source_position = source_position;
5413 cnst->base.type = type_int;
5414 cnst->conste.v.int_value = 0;
5415 cnst->conste.is_ms_noop = true;
5420 return create_invalid_expression();
5424 * Parses a primary expression.
5426 static expression_t *parse_primary_expression(void)
5428 switch (token.type) {
5429 case T_INTEGER: return parse_int_const();
5430 case T_CHARACTER_CONSTANT: return parse_character_constant();
5431 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5432 case T_FLOATINGPOINT: return parse_float_const();
5433 case T_STRING_LITERAL:
5434 case T_WIDE_STRING_LITERAL: return parse_string_const();
5435 case T_IDENTIFIER: return parse_reference();
5436 case T___FUNCTION__:
5437 case T___func__: return parse_function_keyword();
5438 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5439 case T___FUNCSIG__: return parse_funcsig_keyword();
5440 case T___FUNCDNAME__: return parse_funcdname_keyword();
5441 case T___builtin_offsetof: return parse_offsetof();
5442 case T___builtin_va_start: return parse_va_start();
5443 case T___builtin_va_arg: return parse_va_arg();
5444 case T___builtin_expect: return parse_builtin_expect();
5445 case T___builtin_alloca:
5446 case T___builtin_nan:
5447 case T___builtin_nand:
5448 case T___builtin_nanf:
5449 case T___builtin_va_end: return parse_builtin_symbol();
5450 case T___builtin_isgreater:
5451 case T___builtin_isgreaterequal:
5452 case T___builtin_isless:
5453 case T___builtin_islessequal:
5454 case T___builtin_islessgreater:
5455 case T___builtin_isunordered: return parse_compare_builtin();
5456 case T___builtin_constant_p: return parse_builtin_constant();
5457 case T___builtin_prefetch: return parse_builtin_prefetch();
5458 case T__assume: return parse_assume();
5460 case '(': return parse_brace_expression();
5461 case T___noop: return parse_noop_expression();
5464 errorf(HERE, "unexpected token %K, expected an expression", &token);
5465 return create_invalid_expression();
5469 * Check if the expression has the character type and issue a warning then.
5471 static void check_for_char_index_type(const expression_t *expression) {
5472 type_t *const type = expression->base.type;
5473 const type_t *const base_type = skip_typeref(type);
5475 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5476 warning.char_subscripts) {
5477 warningf(expression->base.source_position,
5478 "array subscript has type '%T'", type);
5482 static expression_t *parse_array_expression(unsigned precedence,
5488 add_anchor_token(']');
5490 expression_t *inside = parse_expression();
5492 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5494 array_access_expression_t *array_access = &expression->array_access;
5496 type_t *const orig_type_left = left->base.type;
5497 type_t *const orig_type_inside = inside->base.type;
5499 type_t *const type_left = skip_typeref(orig_type_left);
5500 type_t *const type_inside = skip_typeref(orig_type_inside);
5502 type_t *return_type;
5503 if (is_type_pointer(type_left)) {
5504 return_type = type_left->pointer.points_to;
5505 array_access->array_ref = left;
5506 array_access->index = inside;
5507 check_for_char_index_type(inside);
5508 } else if (is_type_pointer(type_inside)) {
5509 return_type = type_inside->pointer.points_to;
5510 array_access->array_ref = inside;
5511 array_access->index = left;
5512 array_access->flipped = true;
5513 check_for_char_index_type(left);
5515 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5517 "array access on object with non-pointer types '%T', '%T'",
5518 orig_type_left, orig_type_inside);
5520 return_type = type_error_type;
5521 array_access->array_ref = create_invalid_expression();
5524 rem_anchor_token(']');
5525 if(token.type != ']') {
5526 parse_error_expected("Problem while parsing array access", ']', 0);
5531 return_type = automatic_type_conversion(return_type);
5532 expression->base.type = return_type;
5537 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5539 expression_t *tp_expression = allocate_expression_zero(kind);
5540 tp_expression->base.type = type_size_t;
5542 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5544 add_anchor_token(')');
5545 tp_expression->typeprop.type = parse_typename();
5546 rem_anchor_token(')');
5549 expression_t *expression = parse_sub_expression(precedence);
5550 expression->base.type = revert_automatic_type_conversion(expression);
5552 tp_expression->typeprop.type = expression->base.type;
5553 tp_expression->typeprop.tp_expression = expression;
5556 return tp_expression;
5558 return create_invalid_expression();
5561 static expression_t *parse_sizeof(unsigned precedence)
5564 return parse_typeprop(EXPR_SIZEOF, precedence);
5567 static expression_t *parse_alignof(unsigned precedence)
5570 return parse_typeprop(EXPR_SIZEOF, precedence);
5573 static expression_t *parse_select_expression(unsigned precedence,
5574 expression_t *compound)
5577 assert(token.type == '.' || token.type == T_MINUSGREATER);
5579 bool is_pointer = (token.type == T_MINUSGREATER);
5582 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5583 select->select.compound = compound;
5585 if(token.type != T_IDENTIFIER) {
5586 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5589 symbol_t *symbol = token.v.symbol;
5590 select->select.symbol = symbol;
5593 type_t *const orig_type = compound->base.type;
5594 type_t *const type = skip_typeref(orig_type);
5596 type_t *type_left = type;
5598 if (!is_type_pointer(type)) {
5599 if (is_type_valid(type)) {
5600 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5602 return create_invalid_expression();
5604 type_left = type->pointer.points_to;
5606 type_left = skip_typeref(type_left);
5608 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5609 type_left->kind != TYPE_COMPOUND_UNION) {
5610 if (is_type_valid(type_left)) {
5611 errorf(HERE, "request for member '%Y' in something not a struct or "
5612 "union, but '%T'", symbol, type_left);
5614 return create_invalid_expression();
5617 declaration_t *const declaration = type_left->compound.declaration;
5619 if(!declaration->init.is_defined) {
5620 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5622 return create_invalid_expression();
5625 declaration_t *iter = find_compound_entry(declaration, symbol);
5627 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5628 return create_invalid_expression();
5631 /* we always do the auto-type conversions; the & and sizeof parser contains
5632 * code to revert this! */
5633 type_t *expression_type = automatic_type_conversion(iter->type);
5635 select->select.compound_entry = iter;
5636 select->base.type = expression_type;
5638 if(expression_type->kind == TYPE_BITFIELD) {
5639 expression_t *extract
5640 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5641 extract->unary.value = select;
5642 extract->base.type = expression_type->bitfield.base;
5651 * Parse a call expression, ie. expression '( ... )'.
5653 * @param expression the function address
5655 static expression_t *parse_call_expression(unsigned precedence,
5656 expression_t *expression)
5659 expression_t *result = allocate_expression_zero(EXPR_CALL);
5660 result->base.source_position = expression->base.source_position;
5662 call_expression_t *call = &result->call;
5663 call->function = expression;
5665 type_t *const orig_type = expression->base.type;
5666 type_t *const type = skip_typeref(orig_type);
5668 function_type_t *function_type = NULL;
5669 if (is_type_pointer(type)) {
5670 type_t *const to_type = skip_typeref(type->pointer.points_to);
5672 if (is_type_function(to_type)) {
5673 function_type = &to_type->function;
5674 call->base.type = function_type->return_type;
5678 if (function_type == NULL && is_type_valid(type)) {
5679 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5682 /* parse arguments */
5684 add_anchor_token(')');
5685 add_anchor_token(',');
5687 if(token.type != ')') {
5688 call_argument_t *last_argument = NULL;
5691 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5693 argument->expression = parse_assignment_expression();
5694 if(last_argument == NULL) {
5695 call->arguments = argument;
5697 last_argument->next = argument;
5699 last_argument = argument;
5701 if(token.type != ',')
5706 rem_anchor_token(',');
5707 rem_anchor_token(')');
5710 if(function_type != NULL) {
5711 function_parameter_t *parameter = function_type->parameters;
5712 call_argument_t *argument = call->arguments;
5713 for( ; parameter != NULL && argument != NULL;
5714 parameter = parameter->next, argument = argument->next) {
5715 type_t *expected_type = parameter->type;
5716 /* TODO report scope in error messages */
5717 expression_t *const arg_expr = argument->expression;
5718 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call", arg_expr->base.source_position);
5719 if (res_type == NULL) {
5720 /* TODO improve error message */
5721 errorf(arg_expr->base.source_position,
5722 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5723 arg_expr, arg_expr->base.type, expected_type);
5725 argument->expression = create_implicit_cast(argument->expression, expected_type);
5728 /* too few parameters */
5729 if(parameter != NULL) {
5730 errorf(HERE, "too few arguments to function '%E'", expression);
5731 } else if(argument != NULL) {
5732 /* too many parameters */
5733 if(!function_type->variadic
5734 && !function_type->unspecified_parameters) {
5735 errorf(HERE, "too many arguments to function '%E'", expression);
5737 /* do default promotion */
5738 for( ; argument != NULL; argument = argument->next) {
5739 type_t *type = argument->expression->base.type;
5741 type = skip_typeref(type);
5742 if(is_type_integer(type)) {
5743 type = promote_integer(type);
5744 } else if(type == type_float) {
5748 argument->expression
5749 = create_implicit_cast(argument->expression, type);
5752 check_format(&result->call);
5755 check_format(&result->call);
5761 return create_invalid_expression();
5764 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5766 static bool same_compound_type(const type_t *type1, const type_t *type2)
5769 is_type_compound(type1) &&
5770 type1->kind == type2->kind &&
5771 type1->compound.declaration == type2->compound.declaration;
5775 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5777 * @param expression the conditional expression
5779 static expression_t *parse_conditional_expression(unsigned precedence,
5780 expression_t *expression)
5783 add_anchor_token(':');
5785 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5787 conditional_expression_t *conditional = &result->conditional;
5788 conditional->condition = expression;
5791 type_t *const condition_type_orig = expression->base.type;
5792 type_t *const condition_type = skip_typeref(condition_type_orig);
5793 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5794 type_error("expected a scalar type in conditional condition",
5795 expression->base.source_position, condition_type_orig);
5798 expression_t *true_expression = parse_expression();
5799 rem_anchor_token(':');
5801 expression_t *false_expression = parse_sub_expression(precedence);
5803 type_t *const orig_true_type = true_expression->base.type;
5804 type_t *const orig_false_type = false_expression->base.type;
5805 type_t *const true_type = skip_typeref(orig_true_type);
5806 type_t *const false_type = skip_typeref(orig_false_type);
5809 type_t *result_type;
5810 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5811 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5812 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5813 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5814 warningf(expression->base.source_position,
5815 "ISO C forbids conditional expression with only one void side");
5817 result_type = type_void;
5818 } else if (is_type_arithmetic(true_type)
5819 && is_type_arithmetic(false_type)) {
5820 result_type = semantic_arithmetic(true_type, false_type);
5822 true_expression = create_implicit_cast(true_expression, result_type);
5823 false_expression = create_implicit_cast(false_expression, result_type);
5825 conditional->true_expression = true_expression;
5826 conditional->false_expression = false_expression;
5827 conditional->base.type = result_type;
5828 } else if (same_compound_type(true_type, false_type)) {
5829 /* just take 1 of the 2 types */
5830 result_type = true_type;
5831 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5832 type_t *pointer_type;
5834 expression_t *other_expression;
5835 if (is_type_pointer(true_type)) {
5836 pointer_type = true_type;
5837 other_type = false_type;
5838 other_expression = false_expression;
5840 pointer_type = false_type;
5841 other_type = true_type;
5842 other_expression = true_expression;
5845 if(is_type_pointer(other_type)) {
5846 if(!pointers_compatible(true_type, false_type)) {
5847 warningf(expression->base.source_position,
5848 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5850 result_type = true_type;
5851 } else if(is_null_pointer_constant(other_expression)) {
5852 result_type = pointer_type;
5853 } else if(is_type_integer(other_type)) {
5854 warningf(expression->base.source_position,
5855 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5856 result_type = pointer_type;
5858 type_error_incompatible("while parsing conditional",
5859 expression->base.source_position, true_type, false_type);
5860 result_type = type_error_type;
5863 /* TODO: one pointer to void*, other some pointer */
5865 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5866 type_error_incompatible("while parsing conditional",
5867 expression->base.source_position, true_type,
5870 result_type = type_error_type;
5873 conditional->true_expression
5874 = create_implicit_cast(true_expression, result_type);
5875 conditional->false_expression
5876 = create_implicit_cast(false_expression, result_type);
5877 conditional->base.type = result_type;
5880 return create_invalid_expression();
5884 * Parse an extension expression.
5886 static expression_t *parse_extension(unsigned precedence)
5888 eat(T___extension__);
5890 /* TODO enable extensions */
5891 expression_t *expression = parse_sub_expression(precedence);
5892 /* TODO disable extensions */
5897 * Parse a __builtin_classify_type() expression.
5899 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5901 eat(T___builtin_classify_type);
5903 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5904 result->base.type = type_int;
5907 add_anchor_token(')');
5908 expression_t *expression = parse_sub_expression(precedence);
5909 rem_anchor_token(')');
5911 result->classify_type.type_expression = expression;
5915 return create_invalid_expression();
5918 static void semantic_incdec(unary_expression_t *expression)
5920 type_t *const orig_type = expression->value->base.type;
5921 type_t *const type = skip_typeref(orig_type);
5922 /* TODO !is_type_real && !is_type_pointer */
5923 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5924 if (is_type_valid(type)) {
5925 /* TODO: improve error message */
5926 errorf(HERE, "operation needs an arithmetic or pointer type");
5931 expression->base.type = orig_type;
5934 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5936 type_t *const orig_type = expression->value->base.type;
5937 type_t *const type = skip_typeref(orig_type);
5938 if(!is_type_arithmetic(type)) {
5939 if (is_type_valid(type)) {
5940 /* TODO: improve error message */
5941 errorf(HERE, "operation needs an arithmetic type");
5946 expression->base.type = orig_type;
5949 static void semantic_unexpr_scalar(unary_expression_t *expression)
5951 type_t *const orig_type = expression->value->base.type;
5952 type_t *const type = skip_typeref(orig_type);
5953 if (!is_type_scalar(type)) {
5954 if (is_type_valid(type)) {
5955 errorf(HERE, "operand of ! must be of scalar type");
5960 expression->base.type = orig_type;
5963 static void semantic_unexpr_integer(unary_expression_t *expression)
5965 type_t *const orig_type = expression->value->base.type;
5966 type_t *const type = skip_typeref(orig_type);
5967 if (!is_type_integer(type)) {
5968 if (is_type_valid(type)) {
5969 errorf(HERE, "operand of ~ must be of integer type");
5974 expression->base.type = orig_type;
5977 static void semantic_dereference(unary_expression_t *expression)
5979 type_t *const orig_type = expression->value->base.type;
5980 type_t *const type = skip_typeref(orig_type);
5981 if(!is_type_pointer(type)) {
5982 if (is_type_valid(type)) {
5983 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5988 type_t *result_type = type->pointer.points_to;
5989 result_type = automatic_type_conversion(result_type);
5990 expression->base.type = result_type;
5994 * Check the semantic of the address taken expression.
5996 static void semantic_take_addr(unary_expression_t *expression)
5998 expression_t *value = expression->value;
5999 value->base.type = revert_automatic_type_conversion(value);
6001 type_t *orig_type = value->base.type;
6002 if(!is_type_valid(orig_type))
6005 if(value->kind == EXPR_REFERENCE) {
6006 declaration_t *const declaration = value->reference.declaration;
6007 if(declaration != NULL) {
6008 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6009 errorf(expression->base.source_position,
6010 "address of register variable '%Y' requested",
6011 declaration->symbol);
6013 declaration->address_taken = 1;
6017 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6020 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6021 static expression_t *parse_##unexpression_type(unsigned precedence) \
6025 expression_t *unary_expression \
6026 = allocate_expression_zero(unexpression_type); \
6027 unary_expression->base.source_position = HERE; \
6028 unary_expression->unary.value = parse_sub_expression(precedence); \
6030 sfunc(&unary_expression->unary); \
6032 return unary_expression; \
6035 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6036 semantic_unexpr_arithmetic)
6037 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6038 semantic_unexpr_arithmetic)
6039 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6040 semantic_unexpr_scalar)
6041 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6042 semantic_dereference)
6043 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6045 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6046 semantic_unexpr_integer)
6047 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6049 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6052 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6054 static expression_t *parse_##unexpression_type(unsigned precedence, \
6055 expression_t *left) \
6057 (void) precedence; \
6060 expression_t *unary_expression \
6061 = allocate_expression_zero(unexpression_type); \
6062 unary_expression->unary.value = left; \
6064 sfunc(&unary_expression->unary); \
6066 return unary_expression; \
6069 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6070 EXPR_UNARY_POSTFIX_INCREMENT,
6072 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6073 EXPR_UNARY_POSTFIX_DECREMENT,
6076 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6078 /* TODO: handle complex + imaginary types */
6080 /* § 6.3.1.8 Usual arithmetic conversions */
6081 if(type_left == type_long_double || type_right == type_long_double) {
6082 return type_long_double;
6083 } else if(type_left == type_double || type_right == type_double) {
6085 } else if(type_left == type_float || type_right == type_float) {
6089 type_right = promote_integer(type_right);
6090 type_left = promote_integer(type_left);
6092 if(type_left == type_right)
6095 bool signed_left = is_type_signed(type_left);
6096 bool signed_right = is_type_signed(type_right);
6097 int rank_left = get_rank(type_left);
6098 int rank_right = get_rank(type_right);
6099 if(rank_left < rank_right) {
6100 if(signed_left == signed_right || !signed_right) {
6106 if(signed_left == signed_right || !signed_left) {
6115 * Check the semantic restrictions for a binary expression.
6117 static void semantic_binexpr_arithmetic(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);
6126 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6127 /* TODO: improve error message */
6128 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6129 errorf(HERE, "operation needs arithmetic types");
6134 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6135 expression->left = create_implicit_cast(left, arithmetic_type);
6136 expression->right = create_implicit_cast(right, arithmetic_type);
6137 expression->base.type = arithmetic_type;
6140 static void semantic_shift_op(binary_expression_t *expression)
6142 expression_t *const left = expression->left;
6143 expression_t *const right = expression->right;
6144 type_t *const orig_type_left = left->base.type;
6145 type_t *const orig_type_right = right->base.type;
6146 type_t * type_left = skip_typeref(orig_type_left);
6147 type_t * type_right = skip_typeref(orig_type_right);
6149 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6150 /* TODO: improve error message */
6151 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6152 errorf(HERE, "operation needs integer types");
6157 type_left = promote_integer(type_left);
6158 type_right = promote_integer(type_right);
6160 expression->left = create_implicit_cast(left, type_left);
6161 expression->right = create_implicit_cast(right, type_right);
6162 expression->base.type = type_left;
6165 static void semantic_add(binary_expression_t *expression)
6167 expression_t *const left = expression->left;
6168 expression_t *const right = expression->right;
6169 type_t *const orig_type_left = left->base.type;
6170 type_t *const orig_type_right = right->base.type;
6171 type_t *const type_left = skip_typeref(orig_type_left);
6172 type_t *const type_right = skip_typeref(orig_type_right);
6175 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6176 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6177 expression->left = create_implicit_cast(left, arithmetic_type);
6178 expression->right = create_implicit_cast(right, arithmetic_type);
6179 expression->base.type = arithmetic_type;
6181 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6182 expression->base.type = type_left;
6183 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
6184 expression->base.type = type_right;
6185 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6186 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
6190 static void semantic_sub(binary_expression_t *expression)
6192 expression_t *const left = expression->left;
6193 expression_t *const right = expression->right;
6194 type_t *const orig_type_left = left->base.type;
6195 type_t *const orig_type_right = right->base.type;
6196 type_t *const type_left = skip_typeref(orig_type_left);
6197 type_t *const type_right = skip_typeref(orig_type_right);
6200 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6201 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6202 expression->left = create_implicit_cast(left, arithmetic_type);
6203 expression->right = create_implicit_cast(right, arithmetic_type);
6204 expression->base.type = arithmetic_type;
6206 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6207 expression->base.type = type_left;
6208 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6209 if(!pointers_compatible(type_left, type_right)) {
6211 "pointers to incompatible objects to binary '-' ('%T', '%T')",
6212 orig_type_left, orig_type_right);
6214 expression->base.type = type_ptrdiff_t;
6216 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6217 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6218 orig_type_left, orig_type_right);
6223 * Check the semantics of comparison expressions.
6225 * @param expression The expression to check.
6227 static void semantic_comparison(binary_expression_t *expression)
6229 expression_t *left = expression->left;
6230 expression_t *right = expression->right;
6231 type_t *orig_type_left = left->base.type;
6232 type_t *orig_type_right = right->base.type;
6234 type_t *type_left = skip_typeref(orig_type_left);
6235 type_t *type_right = skip_typeref(orig_type_right);
6237 /* TODO non-arithmetic types */
6238 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6239 if (warning.sign_compare &&
6240 (expression->base.kind != EXPR_BINARY_EQUAL &&
6241 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6242 (is_type_signed(type_left) != is_type_signed(type_right))) {
6243 warningf(expression->base.source_position,
6244 "comparison between signed and unsigned");
6246 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6247 expression->left = create_implicit_cast(left, arithmetic_type);
6248 expression->right = create_implicit_cast(right, arithmetic_type);
6249 expression->base.type = arithmetic_type;
6250 if (warning.float_equal &&
6251 (expression->base.kind == EXPR_BINARY_EQUAL ||
6252 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6253 is_type_float(arithmetic_type)) {
6254 warningf(expression->base.source_position,
6255 "comparing floating point with == or != is unsafe");
6257 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6258 /* TODO check compatibility */
6259 } else if (is_type_pointer(type_left)) {
6260 expression->right = create_implicit_cast(right, type_left);
6261 } else if (is_type_pointer(type_right)) {
6262 expression->left = create_implicit_cast(left, type_right);
6263 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6264 type_error_incompatible("invalid operands in comparison",
6265 expression->base.source_position,
6266 type_left, type_right);
6268 expression->base.type = type_int;
6271 static void semantic_arithmetic_assign(binary_expression_t *expression)
6273 expression_t *left = expression->left;
6274 expression_t *right = expression->right;
6275 type_t *orig_type_left = left->base.type;
6276 type_t *orig_type_right = right->base.type;
6278 type_t *type_left = skip_typeref(orig_type_left);
6279 type_t *type_right = skip_typeref(orig_type_right);
6281 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6282 /* TODO: improve error message */
6283 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6284 errorf(HERE, "operation needs arithmetic types");
6289 /* combined instructions are tricky. We can't create an implicit cast on
6290 * the left side, because we need the uncasted form for the store.
6291 * The ast2firm pass has to know that left_type must be right_type
6292 * for the arithmetic operation and create a cast by itself */
6293 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6294 expression->right = create_implicit_cast(right, arithmetic_type);
6295 expression->base.type = type_left;
6298 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6300 expression_t *const left = expression->left;
6301 expression_t *const right = expression->right;
6302 type_t *const orig_type_left = left->base.type;
6303 type_t *const orig_type_right = right->base.type;
6304 type_t *const type_left = skip_typeref(orig_type_left);
6305 type_t *const type_right = skip_typeref(orig_type_right);
6307 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6308 /* combined instructions are tricky. We can't create an implicit cast on
6309 * the left side, because we need the uncasted form for the store.
6310 * The ast2firm pass has to know that left_type must be right_type
6311 * for the arithmetic operation and create a cast by itself */
6312 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6313 expression->right = create_implicit_cast(right, arithmetic_type);
6314 expression->base.type = type_left;
6315 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6316 expression->base.type = type_left;
6317 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6318 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6323 * Check the semantic restrictions of a logical expression.
6325 static void semantic_logical_op(binary_expression_t *expression)
6327 expression_t *const left = expression->left;
6328 expression_t *const right = expression->right;
6329 type_t *const orig_type_left = left->base.type;
6330 type_t *const orig_type_right = right->base.type;
6331 type_t *const type_left = skip_typeref(orig_type_left);
6332 type_t *const type_right = skip_typeref(orig_type_right);
6334 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6335 /* TODO: improve error message */
6336 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6337 errorf(HERE, "operation needs scalar types");
6342 expression->base.type = type_int;
6346 * Checks if a compound type has constant fields.
6348 static bool has_const_fields(const compound_type_t *type)
6350 const scope_t *scope = &type->declaration->scope;
6351 const declaration_t *declaration = scope->declarations;
6353 for (; declaration != NULL; declaration = declaration->next) {
6354 if (declaration->namespc != NAMESPACE_NORMAL)
6357 const type_t *decl_type = skip_typeref(declaration->type);
6358 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6366 * Check the semantic restrictions of a binary assign expression.
6368 static void semantic_binexpr_assign(binary_expression_t *expression)
6370 expression_t *left = expression->left;
6371 type_t *orig_type_left = left->base.type;
6373 type_t *type_left = revert_automatic_type_conversion(left);
6374 type_left = skip_typeref(orig_type_left);
6376 /* must be a modifiable lvalue */
6377 if (is_type_array(type_left)) {
6378 errorf(HERE, "cannot assign to arrays ('%E')", left);
6381 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6382 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6386 if(is_type_incomplete(type_left)) {
6388 "left-hand side of assignment '%E' has incomplete type '%T'",
6389 left, orig_type_left);
6392 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6393 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6394 left, orig_type_left);
6398 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6399 "assignment", left->base.source_position);
6400 if (res_type == NULL) {
6401 errorf(expression->base.source_position,
6402 "cannot assign to '%T' from '%T'",
6403 orig_type_left, expression->right->base.type);
6405 expression->right = create_implicit_cast(expression->right, res_type);
6408 expression->base.type = orig_type_left;
6412 * Determine if the outermost operation (or parts thereof) of the given
6413 * expression has no effect in order to generate a warning about this fact.
6414 * Therefore in some cases this only examines some of the operands of the
6415 * expression (see comments in the function and examples below).
6417 * f() + 23; // warning, because + has no effect
6418 * x || f(); // no warning, because x controls execution of f()
6419 * x ? y : f(); // warning, because y has no effect
6420 * (void)x; // no warning to be able to suppress the warning
6421 * This function can NOT be used for an "expression has definitely no effect"-
6423 static bool expression_has_effect(const expression_t *const expr)
6425 switch (expr->kind) {
6426 case EXPR_UNKNOWN: break;
6427 case EXPR_INVALID: return true; /* do NOT warn */
6428 case EXPR_REFERENCE: return false;
6429 /* suppress the warning for microsoft __noop operations */
6430 case EXPR_CONST: return expr->conste.is_ms_noop;
6431 case EXPR_CHARACTER_CONSTANT: return false;
6432 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6433 case EXPR_STRING_LITERAL: return false;
6434 case EXPR_WIDE_STRING_LITERAL: return false;
6437 const call_expression_t *const call = &expr->call;
6438 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6441 switch (call->function->builtin_symbol.symbol->ID) {
6442 case T___builtin_va_end: return true;
6443 default: return false;
6447 /* Generate the warning if either the left or right hand side of a
6448 * conditional expression has no effect */
6449 case EXPR_CONDITIONAL: {
6450 const conditional_expression_t *const cond = &expr->conditional;
6452 expression_has_effect(cond->true_expression) &&
6453 expression_has_effect(cond->false_expression);
6456 case EXPR_SELECT: return false;
6457 case EXPR_ARRAY_ACCESS: return false;
6458 case EXPR_SIZEOF: return false;
6459 case EXPR_CLASSIFY_TYPE: return false;
6460 case EXPR_ALIGNOF: return false;
6462 case EXPR_FUNCNAME: return false;
6463 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6464 case EXPR_BUILTIN_CONSTANT_P: return false;
6465 case EXPR_BUILTIN_PREFETCH: return true;
6466 case EXPR_OFFSETOF: return false;
6467 case EXPR_VA_START: return true;
6468 case EXPR_VA_ARG: return true;
6469 case EXPR_STATEMENT: return true; // TODO
6470 case EXPR_COMPOUND_LITERAL: return false;
6472 case EXPR_UNARY_NEGATE: return false;
6473 case EXPR_UNARY_PLUS: return false;
6474 case EXPR_UNARY_BITWISE_NEGATE: return false;
6475 case EXPR_UNARY_NOT: return false;
6476 case EXPR_UNARY_DEREFERENCE: return false;
6477 case EXPR_UNARY_TAKE_ADDRESS: return false;
6478 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6479 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6480 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6481 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6483 /* Treat void casts as if they have an effect in order to being able to
6484 * suppress the warning */
6485 case EXPR_UNARY_CAST: {
6486 type_t *const type = skip_typeref(expr->base.type);
6487 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6490 case EXPR_UNARY_CAST_IMPLICIT: return true;
6491 case EXPR_UNARY_ASSUME: return true;
6492 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6494 case EXPR_BINARY_ADD: return false;
6495 case EXPR_BINARY_SUB: return false;
6496 case EXPR_BINARY_MUL: return false;
6497 case EXPR_BINARY_DIV: return false;
6498 case EXPR_BINARY_MOD: return false;
6499 case EXPR_BINARY_EQUAL: return false;
6500 case EXPR_BINARY_NOTEQUAL: return false;
6501 case EXPR_BINARY_LESS: return false;
6502 case EXPR_BINARY_LESSEQUAL: return false;
6503 case EXPR_BINARY_GREATER: return false;
6504 case EXPR_BINARY_GREATEREQUAL: return false;
6505 case EXPR_BINARY_BITWISE_AND: return false;
6506 case EXPR_BINARY_BITWISE_OR: return false;
6507 case EXPR_BINARY_BITWISE_XOR: return false;
6508 case EXPR_BINARY_SHIFTLEFT: return false;
6509 case EXPR_BINARY_SHIFTRIGHT: return false;
6510 case EXPR_BINARY_ASSIGN: return true;
6511 case EXPR_BINARY_MUL_ASSIGN: return true;
6512 case EXPR_BINARY_DIV_ASSIGN: return true;
6513 case EXPR_BINARY_MOD_ASSIGN: return true;
6514 case EXPR_BINARY_ADD_ASSIGN: return true;
6515 case EXPR_BINARY_SUB_ASSIGN: return true;
6516 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6517 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6518 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6519 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6520 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6522 /* Only examine the right hand side of && and ||, because the left hand
6523 * side already has the effect of controlling the execution of the right
6525 case EXPR_BINARY_LOGICAL_AND:
6526 case EXPR_BINARY_LOGICAL_OR:
6527 /* Only examine the right hand side of a comma expression, because the left
6528 * hand side has a separate warning */
6529 case EXPR_BINARY_COMMA:
6530 return expression_has_effect(expr->binary.right);
6532 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6533 case EXPR_BINARY_ISGREATER: return false;
6534 case EXPR_BINARY_ISGREATEREQUAL: return false;
6535 case EXPR_BINARY_ISLESS: return false;
6536 case EXPR_BINARY_ISLESSEQUAL: return false;
6537 case EXPR_BINARY_ISLESSGREATER: return false;
6538 case EXPR_BINARY_ISUNORDERED: return false;
6541 internal_errorf(HERE, "unexpected expression");
6544 static void semantic_comma(binary_expression_t *expression)
6546 if (warning.unused_value) {
6547 const expression_t *const left = expression->left;
6548 if (!expression_has_effect(left)) {
6549 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6552 expression->base.type = expression->right->base.type;
6555 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6556 static expression_t *parse_##binexpression_type(unsigned precedence, \
6557 expression_t *left) \
6560 source_position_t pos = HERE; \
6562 expression_t *right = parse_sub_expression(precedence + lr); \
6564 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6565 binexpr->base.source_position = pos; \
6566 binexpr->binary.left = left; \
6567 binexpr->binary.right = right; \
6568 sfunc(&binexpr->binary); \
6573 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6574 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6575 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6576 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6577 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6578 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6579 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6580 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6581 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6583 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6584 semantic_comparison, 1)
6585 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6586 semantic_comparison, 1)
6587 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6588 semantic_comparison, 1)
6589 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6590 semantic_comparison, 1)
6592 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6593 semantic_binexpr_arithmetic, 1)
6594 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6595 semantic_binexpr_arithmetic, 1)
6596 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6597 semantic_binexpr_arithmetic, 1)
6598 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6599 semantic_logical_op, 1)
6600 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6601 semantic_logical_op, 1)
6602 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6603 semantic_shift_op, 1)
6604 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6605 semantic_shift_op, 1)
6606 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6607 semantic_arithmetic_addsubb_assign, 0)
6608 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6609 semantic_arithmetic_addsubb_assign, 0)
6610 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6611 semantic_arithmetic_assign, 0)
6612 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6613 semantic_arithmetic_assign, 0)
6614 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6615 semantic_arithmetic_assign, 0)
6616 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6617 semantic_arithmetic_assign, 0)
6618 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6619 semantic_arithmetic_assign, 0)
6620 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6621 semantic_arithmetic_assign, 0)
6622 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6623 semantic_arithmetic_assign, 0)
6624 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6625 semantic_arithmetic_assign, 0)
6627 static expression_t *parse_sub_expression(unsigned precedence)
6629 if(token.type < 0) {
6630 return expected_expression_error();
6633 expression_parser_function_t *parser
6634 = &expression_parsers[token.type];
6635 source_position_t source_position = token.source_position;
6638 if(parser->parser != NULL) {
6639 left = parser->parser(parser->precedence);
6641 left = parse_primary_expression();
6643 assert(left != NULL);
6644 left->base.source_position = source_position;
6647 if(token.type < 0) {
6648 return expected_expression_error();
6651 parser = &expression_parsers[token.type];
6652 if(parser->infix_parser == NULL)
6654 if(parser->infix_precedence < precedence)
6657 left = parser->infix_parser(parser->infix_precedence, left);
6659 assert(left != NULL);
6660 assert(left->kind != EXPR_UNKNOWN);
6661 left->base.source_position = source_position;
6668 * Parse an expression.
6670 static expression_t *parse_expression(void)
6672 return parse_sub_expression(1);
6676 * Register a parser for a prefix-like operator with given precedence.
6678 * @param parser the parser function
6679 * @param token_type the token type of the prefix token
6680 * @param precedence the precedence of the operator
6682 static void register_expression_parser(parse_expression_function parser,
6683 int token_type, unsigned precedence)
6685 expression_parser_function_t *entry = &expression_parsers[token_type];
6687 if(entry->parser != NULL) {
6688 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6689 panic("trying to register multiple expression parsers for a token");
6691 entry->parser = parser;
6692 entry->precedence = precedence;
6696 * Register a parser for an infix operator with given precedence.
6698 * @param parser the parser function
6699 * @param token_type the token type of the infix operator
6700 * @param precedence the precedence of the operator
6702 static void register_infix_parser(parse_expression_infix_function parser,
6703 int token_type, unsigned precedence)
6705 expression_parser_function_t *entry = &expression_parsers[token_type];
6707 if(entry->infix_parser != NULL) {
6708 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6709 panic("trying to register multiple infix expression parsers for a "
6712 entry->infix_parser = parser;
6713 entry->infix_precedence = precedence;
6717 * Initialize the expression parsers.
6719 static void init_expression_parsers(void)
6721 memset(&expression_parsers, 0, sizeof(expression_parsers));
6723 register_infix_parser(parse_array_expression, '[', 30);
6724 register_infix_parser(parse_call_expression, '(', 30);
6725 register_infix_parser(parse_select_expression, '.', 30);
6726 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6727 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6729 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6732 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6733 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6734 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6735 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6736 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6737 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6738 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6739 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6740 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6741 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6742 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6743 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6744 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6745 T_EXCLAMATIONMARKEQUAL, 13);
6746 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6747 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6748 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6749 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6750 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6751 register_infix_parser(parse_conditional_expression, '?', 7);
6752 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6753 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6754 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6755 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6756 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6757 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6758 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6759 T_LESSLESSEQUAL, 2);
6760 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6761 T_GREATERGREATEREQUAL, 2);
6762 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6764 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6766 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6769 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6771 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6772 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6773 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6774 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6775 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6776 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6777 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6779 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6781 register_expression_parser(parse_sizeof, T_sizeof, 25);
6782 register_expression_parser(parse_alignof, T___alignof__, 25);
6783 register_expression_parser(parse_extension, T___extension__, 25);
6784 register_expression_parser(parse_builtin_classify_type,
6785 T___builtin_classify_type, 25);
6789 * Parse a asm statement constraints specification.
6791 static asm_constraint_t *parse_asm_constraints(void)
6793 asm_constraint_t *result = NULL;
6794 asm_constraint_t *last = NULL;
6796 while(token.type == T_STRING_LITERAL || token.type == '[') {
6797 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6798 memset(constraint, 0, sizeof(constraint[0]));
6800 if(token.type == '[') {
6802 if(token.type != T_IDENTIFIER) {
6803 parse_error_expected("while parsing asm constraint",
6807 constraint->symbol = token.v.symbol;
6812 constraint->constraints = parse_string_literals();
6814 constraint->expression = parse_expression();
6818 last->next = constraint;
6820 result = constraint;
6824 if(token.type != ',')
6835 * Parse a asm statement clobber specification.
6837 static asm_clobber_t *parse_asm_clobbers(void)
6839 asm_clobber_t *result = NULL;
6840 asm_clobber_t *last = NULL;
6842 while(token.type == T_STRING_LITERAL) {
6843 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6844 clobber->clobber = parse_string_literals();
6847 last->next = clobber;
6853 if(token.type != ',')
6862 * Parse an asm statement.
6864 static statement_t *parse_asm_statement(void)
6868 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6869 statement->base.source_position = token.source_position;
6871 asm_statement_t *asm_statement = &statement->asms;
6873 if(token.type == T_volatile) {
6875 asm_statement->is_volatile = true;
6879 add_anchor_token(')');
6880 add_anchor_token(':');
6881 asm_statement->asm_text = parse_string_literals();
6883 if(token.type != ':') {
6884 rem_anchor_token(':');
6889 asm_statement->inputs = parse_asm_constraints();
6890 if(token.type != ':') {
6891 rem_anchor_token(':');
6896 asm_statement->outputs = parse_asm_constraints();
6897 if(token.type != ':') {
6898 rem_anchor_token(':');
6901 rem_anchor_token(':');
6904 asm_statement->clobbers = parse_asm_clobbers();
6907 rem_anchor_token(')');
6912 return create_invalid_statement();
6916 * Parse a case statement.
6918 static statement_t *parse_case_statement(void)
6922 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6924 statement->base.source_position = token.source_position;
6925 statement->case_label.expression = parse_expression();
6927 if (c_mode & _GNUC) {
6928 if (token.type == T_DOTDOTDOT) {
6930 statement->case_label.end_range = parse_expression();
6936 if (! is_constant_expression(statement->case_label.expression)) {
6937 errorf(statement->base.source_position,
6938 "case label does not reduce to an integer constant");
6940 /* TODO: check if the case label is already known */
6941 if (current_switch != NULL) {
6942 /* link all cases into the switch statement */
6943 if (current_switch->last_case == NULL) {
6944 current_switch->first_case =
6945 current_switch->last_case = &statement->case_label;
6947 current_switch->last_case->next = &statement->case_label;
6950 errorf(statement->base.source_position,
6951 "case label not within a switch statement");
6954 statement->case_label.statement = parse_statement();
6958 return create_invalid_statement();
6962 * Finds an existing default label of a switch statement.
6964 static case_label_statement_t *
6965 find_default_label(const switch_statement_t *statement)
6967 case_label_statement_t *label = statement->first_case;
6968 for ( ; label != NULL; label = label->next) {
6969 if (label->expression == NULL)
6976 * Parse a default statement.
6978 static statement_t *parse_default_statement(void)
6982 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6984 statement->base.source_position = token.source_position;
6987 if (current_switch != NULL) {
6988 const case_label_statement_t *def_label = find_default_label(current_switch);
6989 if (def_label != NULL) {
6990 errorf(HERE, "multiple default labels in one switch");
6991 errorf(def_label->base.source_position,
6992 "this is the first default label");
6994 /* link all cases into the switch statement */
6995 if (current_switch->last_case == NULL) {
6996 current_switch->first_case =
6997 current_switch->last_case = &statement->case_label;
6999 current_switch->last_case->next = &statement->case_label;
7003 errorf(statement->base.source_position,
7004 "'default' label not within a switch statement");
7006 statement->case_label.statement = parse_statement();
7010 return create_invalid_statement();
7014 * Return the declaration for a given label symbol or create a new one.
7016 static declaration_t *get_label(symbol_t *symbol)
7018 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7019 assert(current_function != NULL);
7020 /* if we found a label in the same function, then we already created the
7022 if(candidate != NULL
7023 && candidate->parent_scope == ¤t_function->scope) {
7027 /* otherwise we need to create a new one */
7028 declaration_t *const declaration = allocate_declaration_zero();
7029 declaration->namespc = NAMESPACE_LABEL;
7030 declaration->symbol = symbol;
7032 label_push(declaration);
7038 * Parse a label statement.
7040 static statement_t *parse_label_statement(void)
7042 assert(token.type == T_IDENTIFIER);
7043 symbol_t *symbol = token.v.symbol;
7046 declaration_t *label = get_label(symbol);
7048 /* if source position is already set then the label is defined twice,
7049 * otherwise it was just mentioned in a goto so far */
7050 if(label->source_position.input_name != NULL) {
7051 errorf(HERE, "duplicate label '%Y' (declared %P)",
7052 symbol, label->source_position);
7054 label->source_position = token.source_position;
7057 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7059 statement->base.source_position = token.source_position;
7060 statement->label.label = label;
7064 if(token.type == '}') {
7065 /* TODO only warn? */
7067 warningf(HERE, "label at end of compound statement");
7068 statement->label.statement = create_empty_statement();
7070 errorf(HERE, "label at end of compound statement");
7071 statement->label.statement = create_invalid_statement();
7075 if (token.type == ';') {
7076 /* eat an empty statement here, to avoid the warning about an empty
7077 * after a label. label:; is commonly used to have a label before
7079 statement->label.statement = create_empty_statement();
7082 statement->label.statement = parse_statement();
7086 /* remember the labels's in a list for later checking */
7087 if (label_last == NULL) {
7088 label_first = &statement->label;
7090 label_last->next = &statement->label;
7092 label_last = &statement->label;
7098 * Parse an if statement.
7100 static statement_t *parse_if(void)
7104 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7105 statement->base.source_position = token.source_position;
7108 add_anchor_token(')');
7109 statement->ifs.condition = parse_expression();
7110 rem_anchor_token(')');
7113 add_anchor_token(T_else);
7114 statement->ifs.true_statement = parse_statement();
7115 rem_anchor_token(T_else);
7117 if(token.type == T_else) {
7119 statement->ifs.false_statement = parse_statement();
7124 return create_invalid_statement();
7128 * Parse a switch statement.
7130 static statement_t *parse_switch(void)
7134 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7135 statement->base.source_position = token.source_position;
7138 expression_t *const expr = parse_expression();
7139 type_t * type = skip_typeref(expr->base.type);
7140 if (is_type_integer(type)) {
7141 type = promote_integer(type);
7142 } else if (is_type_valid(type)) {
7143 errorf(expr->base.source_position,
7144 "switch quantity is not an integer, but '%T'", type);
7145 type = type_error_type;
7147 statement->switchs.expression = create_implicit_cast(expr, type);
7150 switch_statement_t *rem = current_switch;
7151 current_switch = &statement->switchs;
7152 statement->switchs.body = parse_statement();
7153 current_switch = rem;
7155 if (warning.switch_default
7156 && find_default_label(&statement->switchs) == NULL) {
7157 warningf(statement->base.source_position, "switch has no default case");
7162 return create_invalid_statement();
7165 static statement_t *parse_loop_body(statement_t *const loop)
7167 statement_t *const rem = current_loop;
7168 current_loop = loop;
7170 statement_t *const body = parse_statement();
7177 * Parse a while statement.
7179 static statement_t *parse_while(void)
7183 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7184 statement->base.source_position = token.source_position;
7187 add_anchor_token(')');
7188 statement->whiles.condition = parse_expression();
7189 rem_anchor_token(')');
7192 statement->whiles.body = parse_loop_body(statement);
7196 return create_invalid_statement();
7200 * Parse a do statement.
7202 static statement_t *parse_do(void)
7206 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7208 statement->base.source_position = token.source_position;
7210 add_anchor_token(T_while);
7211 statement->do_while.body = parse_loop_body(statement);
7212 rem_anchor_token(T_while);
7216 add_anchor_token(')');
7217 statement->do_while.condition = parse_expression();
7218 rem_anchor_token(')');
7224 return create_invalid_statement();
7228 * Parse a for statement.
7230 static statement_t *parse_for(void)
7234 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7235 statement->base.source_position = token.source_position;
7237 int top = environment_top();
7238 scope_t *last_scope = scope;
7239 set_scope(&statement->fors.scope);
7242 add_anchor_token(')');
7244 if(token.type != ';') {
7245 if(is_declaration_specifier(&token, false)) {
7246 parse_declaration(record_declaration);
7248 expression_t *const init = parse_expression();
7249 statement->fors.initialisation = init;
7250 if (warning.unused_value && !expression_has_effect(init)) {
7251 warningf(init->base.source_position,
7252 "initialisation of 'for'-statement has no effect");
7260 if(token.type != ';') {
7261 statement->fors.condition = parse_expression();
7264 if(token.type != ')') {
7265 expression_t *const step = parse_expression();
7266 statement->fors.step = step;
7267 if (warning.unused_value && !expression_has_effect(step)) {
7268 warningf(step->base.source_position,
7269 "step of 'for'-statement has no effect");
7272 rem_anchor_token(')');
7274 statement->fors.body = parse_loop_body(statement);
7276 assert(scope == &statement->fors.scope);
7277 set_scope(last_scope);
7278 environment_pop_to(top);
7283 rem_anchor_token(')');
7284 assert(scope == &statement->fors.scope);
7285 set_scope(last_scope);
7286 environment_pop_to(top);
7288 return create_invalid_statement();
7292 * Parse a goto statement.
7294 static statement_t *parse_goto(void)
7298 if(token.type != T_IDENTIFIER) {
7299 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
7303 symbol_t *symbol = token.v.symbol;
7306 declaration_t *label = get_label(symbol);
7308 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7309 statement->base.source_position = token.source_position;
7311 statement->gotos.label = label;
7313 /* remember the goto's in a list for later checking */
7314 if (goto_last == NULL) {
7315 goto_first = &statement->gotos;
7317 goto_last->next = &statement->gotos;
7319 goto_last = &statement->gotos;
7325 return create_invalid_statement();
7329 * Parse a continue statement.
7331 static statement_t *parse_continue(void)
7333 statement_t *statement;
7334 if (current_loop == NULL) {
7335 errorf(HERE, "continue statement not within loop");
7338 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7340 statement->base.source_position = token.source_position;
7348 return create_invalid_statement();
7352 * Parse a break statement.
7354 static statement_t *parse_break(void)
7356 statement_t *statement;
7357 if (current_switch == NULL && current_loop == NULL) {
7358 errorf(HERE, "break statement not within loop or switch");
7361 statement = allocate_statement_zero(STATEMENT_BREAK);
7363 statement->base.source_position = token.source_position;
7371 return create_invalid_statement();
7375 * Check if a given declaration represents a local variable.
7377 static bool is_local_var_declaration(const declaration_t *declaration) {
7378 switch ((storage_class_tag_t) declaration->storage_class) {
7379 case STORAGE_CLASS_AUTO:
7380 case STORAGE_CLASS_REGISTER: {
7381 const type_t *type = skip_typeref(declaration->type);
7382 if(is_type_function(type)) {
7394 * Check if a given declaration represents a variable.
7396 static bool is_var_declaration(const declaration_t *declaration) {
7397 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7400 const type_t *type = skip_typeref(declaration->type);
7401 return !is_type_function(type);
7405 * Check if a given expression represents a local variable.
7407 static bool is_local_variable(const expression_t *expression)
7409 if (expression->base.kind != EXPR_REFERENCE) {
7412 const declaration_t *declaration = expression->reference.declaration;
7413 return is_local_var_declaration(declaration);
7417 * Check if a given expression represents a local variable and
7418 * return its declaration then, else return NULL.
7420 declaration_t *expr_is_variable(const expression_t *expression)
7422 if (expression->base.kind != EXPR_REFERENCE) {
7425 declaration_t *declaration = expression->reference.declaration;
7426 if (is_var_declaration(declaration))
7432 * Parse a return statement.
7434 static statement_t *parse_return(void)
7436 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7437 statement->base.source_position = token.source_position;
7441 expression_t *return_value = NULL;
7442 if(token.type != ';') {
7443 return_value = parse_expression();
7447 const type_t *const func_type = current_function->type;
7448 assert(is_type_function(func_type));
7449 type_t *const return_type = skip_typeref(func_type->function.return_type);
7451 if(return_value != NULL) {
7452 type_t *return_value_type = skip_typeref(return_value->base.type);
7454 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7455 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7456 warningf(statement->base.source_position,
7457 "'return' with a value, in function returning void");
7458 return_value = NULL;
7460 type_t *const res_type = semantic_assign(return_type,
7461 return_value, "'return'", statement->base.source_position);
7462 if (res_type == NULL) {
7463 errorf(statement->base.source_position,
7464 "cannot return something of type '%T' in function returning '%T'",
7465 return_value->base.type, return_type);
7467 return_value = create_implicit_cast(return_value, res_type);
7470 /* check for returning address of a local var */
7471 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7472 const expression_t *expression = return_value->unary.value;
7473 if (is_local_variable(expression)) {
7474 warningf(statement->base.source_position,
7475 "function returns address of local variable");
7479 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7480 warningf(statement->base.source_position,
7481 "'return' without value, in function returning non-void");
7484 statement->returns.value = return_value;
7488 return create_invalid_statement();
7492 * Parse a declaration statement.
7494 static statement_t *parse_declaration_statement(void)
7496 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7498 statement->base.source_position = token.source_position;
7500 declaration_t *before = last_declaration;
7501 parse_declaration(record_declaration);
7503 if(before == NULL) {
7504 statement->declaration.declarations_begin = scope->declarations;
7506 statement->declaration.declarations_begin = before->next;
7508 statement->declaration.declarations_end = last_declaration;
7514 * Parse an expression statement, ie. expr ';'.
7516 static statement_t *parse_expression_statement(void)
7518 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7520 statement->base.source_position = token.source_position;
7521 expression_t *const expr = parse_expression();
7522 statement->expression.expression = expr;
7524 if (warning.unused_value && !expression_has_effect(expr)) {
7525 warningf(expr->base.source_position, "statement has no effect");
7532 return create_invalid_statement();
7536 * Parse a statement.
7538 static statement_t *parse_statement(void)
7540 statement_t *statement = NULL;
7542 /* declaration or statement */
7543 add_anchor_token(';');
7544 switch(token.type) {
7546 statement = parse_asm_statement();
7550 statement = parse_case_statement();
7554 statement = parse_default_statement();
7558 statement = parse_compound_statement();
7562 statement = parse_if();
7566 statement = parse_switch();
7570 statement = parse_while();
7574 statement = parse_do();
7578 statement = parse_for();
7582 statement = parse_goto();
7586 statement = parse_continue();
7590 statement = parse_break();
7594 statement = parse_return();
7598 if(warning.empty_statement) {
7599 warningf(HERE, "statement is empty");
7601 statement = create_empty_statement();
7606 if(look_ahead(1)->type == ':') {
7607 statement = parse_label_statement();
7611 if(is_typedef_symbol(token.v.symbol)) {
7612 statement = parse_declaration_statement();
7616 statement = parse_expression_statement();
7619 case T___extension__:
7620 /* this can be a prefix to a declaration or an expression statement */
7621 /* we simply eat it now and parse the rest with tail recursion */
7624 } while(token.type == T___extension__);
7625 statement = parse_statement();
7629 statement = parse_declaration_statement();
7633 statement = parse_expression_statement();
7636 rem_anchor_token(';');
7638 assert(statement != NULL
7639 && statement->base.source_position.input_name != NULL);
7645 * Parse a compound statement.
7647 static statement_t *parse_compound_statement(void)
7649 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7651 statement->base.source_position = token.source_position;
7654 add_anchor_token('}');
7656 int top = environment_top();
7657 scope_t *last_scope = scope;
7658 set_scope(&statement->compound.scope);
7660 statement_t *last_statement = NULL;
7662 while(token.type != '}' && token.type != T_EOF) {
7663 statement_t *sub_statement = parse_statement();
7664 if(is_invalid_statement(sub_statement)) {
7665 /* an error occurred. if we are at an anchor, return */
7671 if(last_statement != NULL) {
7672 last_statement->base.next = sub_statement;
7674 statement->compound.statements = sub_statement;
7677 while(sub_statement->base.next != NULL)
7678 sub_statement = sub_statement->base.next;
7680 last_statement = sub_statement;
7683 if(token.type == '}') {
7686 errorf(statement->base.source_position,
7687 "end of file while looking for closing '}'");
7691 rem_anchor_token('}');
7692 assert(scope == &statement->compound.scope);
7693 set_scope(last_scope);
7694 environment_pop_to(top);
7700 * Initialize builtin types.
7702 static void initialize_builtin_types(void)
7704 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7705 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7706 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7707 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7708 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7709 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7710 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7711 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7713 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7714 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7715 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7716 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7720 * Check for unused global static functions and variables
7722 static void check_unused_globals(void)
7724 if (!warning.unused_function && !warning.unused_variable)
7727 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7728 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7731 type_t *const type = decl->type;
7733 if (is_type_function(skip_typeref(type))) {
7734 if (!warning.unused_function || decl->is_inline)
7737 s = (decl->init.statement != NULL ? "defined" : "declared");
7739 if (!warning.unused_variable)
7745 warningf(decl->source_position, "'%#T' %s but not used",
7746 type, decl->symbol, s);
7751 * Parse a translation unit.
7753 static translation_unit_t *parse_translation_unit(void)
7755 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7757 assert(global_scope == NULL);
7758 global_scope = &unit->scope;
7760 assert(scope == NULL);
7761 set_scope(&unit->scope);
7763 initialize_builtin_types();
7765 while(token.type != T_EOF) {
7766 if (token.type == ';') {
7767 /* TODO error in strict mode */
7768 warningf(HERE, "stray ';' outside of function");
7771 parse_external_declaration();
7775 assert(scope == &unit->scope);
7777 last_declaration = NULL;
7779 assert(global_scope == &unit->scope);
7780 check_unused_globals();
7781 global_scope = NULL;
7789 * @return the translation unit or NULL if errors occurred.
7791 translation_unit_t *parse(void)
7793 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7794 label_stack = NEW_ARR_F(stack_entry_t, 0);
7795 diagnostic_count = 0;
7799 type_set_output(stderr);
7800 ast_set_output(stderr);
7802 lookahead_bufpos = 0;
7803 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7806 translation_unit_t *unit = parse_translation_unit();
7808 DEL_ARR_F(environment_stack);
7809 DEL_ARR_F(label_stack);
7815 * Initialize the parser.
7817 void init_parser(void)
7820 /* add predefined symbols for extended-decl-modifier */
7821 sym_align = symbol_table_insert("align");
7822 sym_allocate = symbol_table_insert("allocate");
7823 sym_dllimport = symbol_table_insert("dllimport");
7824 sym_dllexport = symbol_table_insert("dllexport");
7825 sym_naked = symbol_table_insert("naked");
7826 sym_noinline = symbol_table_insert("noinline");
7827 sym_noreturn = symbol_table_insert("noreturn");
7828 sym_nothrow = symbol_table_insert("nothrow");
7829 sym_novtable = symbol_table_insert("novtable");
7830 sym_property = symbol_table_insert("property");
7831 sym_get = symbol_table_insert("get");
7832 sym_put = symbol_table_insert("put");
7833 sym_selectany = symbol_table_insert("selectany");
7834 sym_thread = symbol_table_insert("thread");
7835 sym_uuid = symbol_table_insert("uuid");
7836 sym_deprecated = symbol_table_insert("deprecated");
7837 sym_restrict = symbol_table_insert("restrict");
7838 sym_noalias = symbol_table_insert("noalias");
7840 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7842 init_expression_parsers();
7843 obstack_init(&temp_obst);
7845 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7846 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7850 * Terminate the parser.
7852 void exit_parser(void)
7854 obstack_free(&temp_obst, NULL);