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;
1391 for(i = 0; i < GNU_AK_LAST; ++i) {
1392 if(strcmp_underscore(gnu_attribute_names[i], name) == 0)
1395 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1397 if(kind == GNU_AK_LAST) {
1398 if(warning.attribute)
1399 warningf(HERE, "'%s' attribute directive ignored", name);
1401 /* skip possible arguments */
1402 if(token.type == '(') {
1403 eat_until_matching_token(')');
1406 /* check for arguments */
1407 bool have_args = false;
1408 if(token.type == '(') {
1410 if(token.type == ')') {
1411 /* empty args are allowed */
1419 case GNU_AK_VOLATILE:
1421 case GNU_AK_STDCALL:
1422 case GNU_AK_FASTCALL:
1423 case GNU_AK_DEPRECATED:
1424 case GNU_AK_NOINLINE:
1425 case GNU_AK_NORETURN:
1428 case GNU_AK_ALWAYS_INLINE:
1431 case GNU_AK_CONSTRUCTOR:
1432 case GNU_AK_DESTRUCTOR:
1433 case GNU_AK_NOTHROW:
1434 case GNU_AK_TRANSPARENT_UNION:
1436 case GNU_AK_NOCOMMON:
1439 case GNU_AK_NOTSHARED:
1442 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1443 case GNU_AK_WARN_UNUSED_RESULT:
1444 case GNU_AK_LONGCALL:
1445 case GNU_AK_SHORTCALL:
1446 case GNU_AK_LONG_CALL:
1447 case GNU_AK_SHORT_CALL:
1448 case GNU_AK_FUNCTION_VECTOR:
1449 case GNU_AK_INTERRUPT_HANDLER:
1450 case GNU_AK_NMI_HANDLER:
1451 case GNU_AK_NESTING:
1455 case GNU_AK_EIGTHBIT_DATA:
1456 case GNU_AK_TINY_DATA:
1457 case GNU_AK_SAVEALL:
1458 case GNU_AK_FLATTEN:
1459 case GNU_AK_SSEREGPARM:
1460 case GNU_AK_EXTERNALLY_VISIBLE:
1461 case GNU_AK_RETURN_TWICE:
1462 case GNU_AK_MAY_ALIAS:
1463 case GNU_AK_MS_STRUCT:
1464 case GNU_AK_GCC_STRUCT:
1466 /* should have no arguments */
1467 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1468 eat_until_matching_token('(');
1469 /* we have already consumend '(', so we stop before ')', eat it */
1474 case GNU_AK_ALIGNED:
1475 case GNU_AK_FORMAT_ARG:
1476 case GNU_AK_REGPARM:
1477 case GNU_AK_TRAP_EXIT:
1479 /* should have arguments */
1480 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1482 parse_gnu_attribute_const_arg();
1485 case GNU_AK_SECTION:
1486 case GNU_AK_SP_SWITCH:
1488 /* should have arguments */
1489 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1491 parse_gnu_attribute_string_arg();
1495 /* should have arguments */
1496 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1498 parse_gnu_attribute_format_args();
1500 case GNU_AK_WEAKREF:
1501 /* may have one string argument */
1503 parse_gnu_attribute_string_arg();
1505 case GNU_AK_NONNULL:
1507 parse_gnu_attribute_const_arg_list();
1509 case GNU_AK_TLS_MODEL:
1511 /* should have arguments */
1512 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1514 parse_gnu_attribute_tls_model_arg();
1516 case GNU_AK_VISIBILITY:
1518 /* should have arguments */
1519 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1521 parse_gnu_attribute_visibility_arg();
1525 /* should have arguments */
1526 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1528 parse_gnu_attribute_model_arg();
1529 case GNU_AK_INTERRUPT:
1530 /* may have one string argument */
1532 parse_gnu_attribute_interrupt_arg();
1534 case GNU_AK_SENTINEL:
1535 /* may have one string argument */
1537 parse_gnu_attribute_const_arg();
1540 /* already handled */
1544 if(token.type != ',')
1556 * Parse GNU attributes.
1558 static void parse_attributes(void)
1561 switch(token.type) {
1562 case T___attribute__: {
1563 parse_gnu_attribute();
1569 if(token.type != T_STRING_LITERAL) {
1570 parse_error_expected("while parsing assembler attribute",
1572 eat_until_matching_token('(');
1575 parse_string_literals();
1580 goto attributes_finished;
1585 attributes_finished:
1589 static designator_t *parse_designation(void)
1591 designator_t *result = NULL;
1592 designator_t *last = NULL;
1595 designator_t *designator;
1596 switch(token.type) {
1598 designator = allocate_ast_zero(sizeof(designator[0]));
1599 designator->source_position = token.source_position;
1601 add_anchor_token(']');
1602 designator->array_index = parse_constant_expression();
1603 rem_anchor_token(']');
1607 designator = allocate_ast_zero(sizeof(designator[0]));
1608 designator->source_position = token.source_position;
1610 if(token.type != T_IDENTIFIER) {
1611 parse_error_expected("while parsing designator",
1615 designator->symbol = token.v.symbol;
1623 assert(designator != NULL);
1625 last->next = designator;
1627 result = designator;
1635 static initializer_t *initializer_from_string(array_type_t *type,
1636 const string_t *const string)
1638 /* TODO: check len vs. size of array type */
1641 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1642 initializer->string.string = *string;
1647 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1648 wide_string_t *const string)
1650 /* TODO: check len vs. size of array type */
1653 initializer_t *const initializer =
1654 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1655 initializer->wide_string.string = *string;
1661 * Build an initializer from a given expression.
1663 static initializer_t *initializer_from_expression(type_t *orig_type,
1664 expression_t *expression)
1666 /* TODO check that expression is a constant expression */
1668 /* § 6.7.8.14/15 char array may be initialized by string literals */
1669 type_t *type = skip_typeref(orig_type);
1670 type_t *expr_type_orig = expression->base.type;
1671 type_t *expr_type = skip_typeref(expr_type_orig);
1672 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1673 array_type_t *const array_type = &type->array;
1674 type_t *const element_type = skip_typeref(array_type->element_type);
1676 if (element_type->kind == TYPE_ATOMIC) {
1677 atomic_type_kind_t akind = element_type->atomic.akind;
1678 switch (expression->kind) {
1679 case EXPR_STRING_LITERAL:
1680 if (akind == ATOMIC_TYPE_CHAR
1681 || akind == ATOMIC_TYPE_SCHAR
1682 || akind == ATOMIC_TYPE_UCHAR) {
1683 return initializer_from_string(array_type,
1684 &expression->string.value);
1687 case EXPR_WIDE_STRING_LITERAL: {
1688 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1689 if (get_unqualified_type(element_type) == bare_wchar_type) {
1690 return initializer_from_wide_string(array_type,
1691 &expression->wide_string.value);
1701 type_t *const res_type = semantic_assign(type, expression, "initializer",
1702 expression->base.source_position);
1703 if (res_type == NULL)
1706 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1707 result->value.value = create_implicit_cast(expression, res_type);
1713 * Checks if a given expression can be used as an constant initializer.
1715 static bool is_initializer_constant(const expression_t *expression)
1717 return is_constant_expression(expression)
1718 || is_address_constant(expression);
1722 * Parses an scalar initializer.
1724 * § 6.7.8.11; eat {} without warning
1726 static initializer_t *parse_scalar_initializer(type_t *type,
1727 bool must_be_constant)
1729 /* there might be extra {} hierarchies */
1731 while(token.type == '{') {
1734 warningf(HERE, "extra curly braces around scalar initializer");
1739 expression_t *expression = parse_assignment_expression();
1740 if(must_be_constant && !is_initializer_constant(expression)) {
1741 errorf(expression->base.source_position,
1742 "Initialisation expression '%E' is not constant\n",
1746 initializer_t *initializer = initializer_from_expression(type, expression);
1748 if(initializer == NULL) {
1749 errorf(expression->base.source_position,
1750 "expression '%E' (type '%T') doesn't match expected type '%T'",
1751 expression, expression->base.type, type);
1756 bool additional_warning_displayed = false;
1758 if(token.type == ',') {
1761 if(token.type != '}') {
1762 if(!additional_warning_displayed) {
1763 warningf(HERE, "additional elements in scalar initializer");
1764 additional_warning_displayed = true;
1775 * An entry in the type path.
1777 typedef struct type_path_entry_t type_path_entry_t;
1778 struct type_path_entry_t {
1779 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1781 size_t index; /**< For array types: the current index. */
1782 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1787 * A type path expression a position inside compound or array types.
1789 typedef struct type_path_t type_path_t;
1790 struct type_path_t {
1791 type_path_entry_t *path; /**< An flexible array containing the current path. */
1792 type_t *top_type; /**< type of the element the path points */
1793 size_t max_index; /**< largest index in outermost array */
1797 * Prints a type path for debugging.
1799 static __attribute__((unused)) void debug_print_type_path(
1800 const type_path_t *path)
1802 size_t len = ARR_LEN(path->path);
1804 for(size_t i = 0; i < len; ++i) {
1805 const type_path_entry_t *entry = & path->path[i];
1807 type_t *type = skip_typeref(entry->type);
1808 if(is_type_compound(type)) {
1809 /* in gcc mode structs can have no members */
1810 if(entry->v.compound_entry == NULL) {
1814 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1815 } else if(is_type_array(type)) {
1816 fprintf(stderr, "[%zd]", entry->v.index);
1818 fprintf(stderr, "-INVALID-");
1821 if(path->top_type != NULL) {
1822 fprintf(stderr, " (");
1823 print_type(path->top_type);
1824 fprintf(stderr, ")");
1829 * Return the top type path entry, ie. in a path
1830 * (type).a.b returns the b.
1832 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1834 size_t len = ARR_LEN(path->path);
1836 return &path->path[len-1];
1840 * Enlarge the type path by an (empty) element.
1842 static type_path_entry_t *append_to_type_path(type_path_t *path)
1844 size_t len = ARR_LEN(path->path);
1845 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1847 type_path_entry_t *result = & path->path[len];
1848 memset(result, 0, sizeof(result[0]));
1853 * Descending into a sub-type. Enter the scope of the current
1856 static void descend_into_subtype(type_path_t *path)
1858 type_t *orig_top_type = path->top_type;
1859 type_t *top_type = skip_typeref(orig_top_type);
1861 assert(is_type_compound(top_type) || is_type_array(top_type));
1863 type_path_entry_t *top = append_to_type_path(path);
1864 top->type = top_type;
1866 if(is_type_compound(top_type)) {
1867 declaration_t *declaration = top_type->compound.declaration;
1868 declaration_t *entry = declaration->scope.declarations;
1869 top->v.compound_entry = entry;
1872 path->top_type = entry->type;
1874 path->top_type = NULL;
1877 assert(is_type_array(top_type));
1880 path->top_type = top_type->array.element_type;
1885 * Pop an entry from the given type path, ie. returning from
1886 * (type).a.b to (type).a
1888 static void ascend_from_subtype(type_path_t *path)
1890 type_path_entry_t *top = get_type_path_top(path);
1892 path->top_type = top->type;
1894 size_t len = ARR_LEN(path->path);
1895 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1899 * Pop entries from the given type path until the given
1900 * path level is reached.
1902 static void ascend_to(type_path_t *path, size_t top_path_level)
1904 size_t len = ARR_LEN(path->path);
1906 while(len > top_path_level) {
1907 ascend_from_subtype(path);
1908 len = ARR_LEN(path->path);
1912 static bool walk_designator(type_path_t *path, const designator_t *designator,
1913 bool used_in_offsetof)
1915 for( ; designator != NULL; designator = designator->next) {
1916 type_path_entry_t *top = get_type_path_top(path);
1917 type_t *orig_type = top->type;
1919 type_t *type = skip_typeref(orig_type);
1921 if(designator->symbol != NULL) {
1922 symbol_t *symbol = designator->symbol;
1923 if(!is_type_compound(type)) {
1924 if(is_type_valid(type)) {
1925 errorf(designator->source_position,
1926 "'.%Y' designator used for non-compound type '%T'",
1932 declaration_t *declaration = type->compound.declaration;
1933 declaration_t *iter = declaration->scope.declarations;
1934 for( ; iter != NULL; iter = iter->next) {
1935 if(iter->symbol == symbol) {
1940 errorf(designator->source_position,
1941 "'%T' has no member named '%Y'", orig_type, symbol);
1944 if(used_in_offsetof) {
1945 type_t *real_type = skip_typeref(iter->type);
1946 if(real_type->kind == TYPE_BITFIELD) {
1947 errorf(designator->source_position,
1948 "offsetof designator '%Y' may not specify bitfield",
1954 top->type = orig_type;
1955 top->v.compound_entry = iter;
1956 orig_type = iter->type;
1958 expression_t *array_index = designator->array_index;
1959 assert(designator->array_index != NULL);
1961 if(!is_type_array(type)) {
1962 if(is_type_valid(type)) {
1963 errorf(designator->source_position,
1964 "[%E] designator used for non-array type '%T'",
1965 array_index, orig_type);
1969 if(!is_type_valid(array_index->base.type)) {
1973 long index = fold_constant(array_index);
1974 if(!used_in_offsetof) {
1976 errorf(designator->source_position,
1977 "array index [%E] must be positive", array_index);
1980 if(type->array.size_constant == true) {
1981 long array_size = type->array.size;
1982 if(index >= array_size) {
1983 errorf(designator->source_position,
1984 "designator [%E] (%d) exceeds array size %d",
1985 array_index, index, array_size);
1991 top->type = orig_type;
1992 top->v.index = (size_t) index;
1993 orig_type = type->array.element_type;
1995 path->top_type = orig_type;
1997 if(designator->next != NULL) {
1998 descend_into_subtype(path);
2007 static void advance_current_object(type_path_t *path, size_t top_path_level)
2009 type_path_entry_t *top = get_type_path_top(path);
2011 type_t *type = skip_typeref(top->type);
2012 if(is_type_union(type)) {
2013 /* in unions only the first element is initialized */
2014 top->v.compound_entry = NULL;
2015 } else if(is_type_struct(type)) {
2016 declaration_t *entry = top->v.compound_entry;
2018 entry = entry->next;
2019 top->v.compound_entry = entry;
2021 path->top_type = entry->type;
2025 assert(is_type_array(type));
2029 if(!type->array.size_constant || top->v.index < type->array.size) {
2034 /* we're past the last member of the current sub-aggregate, try if we
2035 * can ascend in the type hierarchy and continue with another subobject */
2036 size_t len = ARR_LEN(path->path);
2038 if(len > top_path_level) {
2039 ascend_from_subtype(path);
2040 advance_current_object(path, top_path_level);
2042 path->top_type = NULL;
2047 * skip until token is found.
2049 static void skip_until(int type) {
2050 while(token.type != type) {
2051 if(token.type == T_EOF)
2058 * skip any {...} blocks until a closing braket is reached.
2060 static void skip_initializers(void)
2062 if(token.type == '{')
2065 while(token.type != '}') {
2066 if(token.type == T_EOF)
2068 if(token.type == '{') {
2076 static initializer_t *create_empty_initializer(void)
2078 static initializer_t empty_initializer
2079 = { .list = { { INITIALIZER_LIST }, 0 } };
2080 return &empty_initializer;
2084 * Parse a part of an initialiser for a struct or union,
2086 static initializer_t *parse_sub_initializer(type_path_t *path,
2087 type_t *outer_type, size_t top_path_level,
2088 parse_initializer_env_t *env)
2090 if(token.type == '}') {
2091 /* empty initializer */
2092 return create_empty_initializer();
2095 type_t *orig_type = path->top_type;
2096 type_t *type = NULL;
2098 if (orig_type == NULL) {
2099 /* We are initializing an empty compound. */
2101 type = skip_typeref(orig_type);
2103 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2104 * initializers in this case. */
2105 if(!is_type_valid(type)) {
2106 skip_initializers();
2107 return create_empty_initializer();
2111 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2114 designator_t *designator = NULL;
2115 if(token.type == '.' || token.type == '[') {
2116 designator = parse_designation();
2118 /* reset path to toplevel, evaluate designator from there */
2119 ascend_to(path, top_path_level);
2120 if(!walk_designator(path, designator, false)) {
2121 /* can't continue after designation error */
2125 initializer_t *designator_initializer
2126 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2127 designator_initializer->designator.designator = designator;
2128 ARR_APP1(initializer_t*, initializers, designator_initializer);
2133 if(token.type == '{') {
2134 if(type != NULL && is_type_scalar(type)) {
2135 sub = parse_scalar_initializer(type, env->must_be_constant);
2139 if (env->declaration != NULL)
2140 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2141 env->declaration->symbol);
2143 errorf(HERE, "extra brace group at end of initializer");
2145 descend_into_subtype(path);
2147 add_anchor_token('}');
2148 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2150 rem_anchor_token('}');
2153 ascend_from_subtype(path);
2157 goto error_parse_next;
2161 /* must be an expression */
2162 expression_t *expression = parse_assignment_expression();
2164 if(env->must_be_constant && !is_initializer_constant(expression)) {
2165 errorf(expression->base.source_position,
2166 "Initialisation expression '%E' is not constant\n",
2171 /* we are already outside, ... */
2175 /* handle { "string" } special case */
2176 if((expression->kind == EXPR_STRING_LITERAL
2177 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2178 && outer_type != NULL) {
2179 sub = initializer_from_expression(outer_type, expression);
2181 if(token.type == ',') {
2184 if(token.type != '}') {
2185 warningf(HERE, "excessive elements in initializer for type '%T'",
2188 /* TODO: eat , ... */
2193 /* descend into subtypes until expression matches type */
2195 orig_type = path->top_type;
2196 type = skip_typeref(orig_type);
2198 sub = initializer_from_expression(orig_type, expression);
2202 if(!is_type_valid(type)) {
2205 if(is_type_scalar(type)) {
2206 errorf(expression->base.source_position,
2207 "expression '%E' doesn't match expected type '%T'",
2208 expression, orig_type);
2212 descend_into_subtype(path);
2216 /* update largest index of top array */
2217 const type_path_entry_t *first = &path->path[0];
2218 type_t *first_type = first->type;
2219 first_type = skip_typeref(first_type);
2220 if(is_type_array(first_type)) {
2221 size_t index = first->v.index;
2222 if(index > path->max_index)
2223 path->max_index = index;
2227 /* append to initializers list */
2228 ARR_APP1(initializer_t*, initializers, sub);
2231 if(env->declaration != NULL)
2232 warningf(HERE, "excess elements in struct initializer for '%Y'",
2233 env->declaration->symbol);
2235 warningf(HERE, "excess elements in struct initializer");
2239 if(token.type == '}') {
2243 if(token.type == '}') {
2248 /* advance to the next declaration if we are not at the end */
2249 advance_current_object(path, top_path_level);
2250 orig_type = path->top_type;
2251 if(orig_type != NULL)
2252 type = skip_typeref(orig_type);
2258 size_t len = ARR_LEN(initializers);
2259 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2260 initializer_t *result = allocate_ast_zero(size);
2261 result->kind = INITIALIZER_LIST;
2262 result->list.len = len;
2263 memcpy(&result->list.initializers, initializers,
2264 len * sizeof(initializers[0]));
2266 DEL_ARR_F(initializers);
2267 ascend_to(path, top_path_level);
2272 skip_initializers();
2273 DEL_ARR_F(initializers);
2274 ascend_to(path, top_path_level);
2279 * Parses an initializer. Parsers either a compound literal
2280 * (env->declaration == NULL) or an initializer of a declaration.
2282 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2284 type_t *type = skip_typeref(env->type);
2285 initializer_t *result = NULL;
2288 if(is_type_scalar(type)) {
2289 result = parse_scalar_initializer(type, env->must_be_constant);
2290 } else if(token.type == '{') {
2294 memset(&path, 0, sizeof(path));
2295 path.top_type = env->type;
2296 path.path = NEW_ARR_F(type_path_entry_t, 0);
2298 descend_into_subtype(&path);
2300 add_anchor_token('}');
2301 result = parse_sub_initializer(&path, env->type, 1, env);
2302 rem_anchor_token('}');
2304 max_index = path.max_index;
2305 DEL_ARR_F(path.path);
2309 /* parse_scalar_initializer() also works in this case: we simply
2310 * have an expression without {} around it */
2311 result = parse_scalar_initializer(type, env->must_be_constant);
2314 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2315 * the array type size */
2316 if(is_type_array(type) && type->array.size_expression == NULL
2317 && result != NULL) {
2319 switch (result->kind) {
2320 case INITIALIZER_LIST:
2321 size = max_index + 1;
2324 case INITIALIZER_STRING:
2325 size = result->string.string.size;
2328 case INITIALIZER_WIDE_STRING:
2329 size = result->wide_string.string.size;
2333 internal_errorf(HERE, "invalid initializer type");
2336 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2337 cnst->base.type = type_size_t;
2338 cnst->conste.v.int_value = size;
2340 type_t *new_type = duplicate_type(type);
2342 new_type->array.size_expression = cnst;
2343 new_type->array.size_constant = true;
2344 new_type->array.size = size;
2345 env->type = new_type;
2353 static declaration_t *append_declaration(declaration_t *declaration);
2355 static declaration_t *parse_compound_type_specifier(bool is_struct)
2363 symbol_t *symbol = NULL;
2364 declaration_t *declaration = NULL;
2366 if (token.type == T___attribute__) {
2371 if(token.type == T_IDENTIFIER) {
2372 symbol = token.v.symbol;
2376 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
2378 declaration = get_declaration(symbol, NAMESPACE_UNION);
2380 } else if(token.type != '{') {
2382 parse_error_expected("while parsing struct type specifier",
2383 T_IDENTIFIER, '{', 0);
2385 parse_error_expected("while parsing union type specifier",
2386 T_IDENTIFIER, '{', 0);
2392 if(declaration == NULL) {
2393 declaration = allocate_declaration_zero();
2394 declaration->namespc =
2395 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2396 declaration->source_position = token.source_position;
2397 declaration->symbol = symbol;
2398 declaration->parent_scope = scope;
2399 if (symbol != NULL) {
2400 environment_push(declaration);
2402 append_declaration(declaration);
2405 if(token.type == '{') {
2406 if(declaration->init.is_defined) {
2407 assert(symbol != NULL);
2408 errorf(HERE, "multiple definitions of '%s %Y'",
2409 is_struct ? "struct" : "union", symbol);
2410 declaration->scope.declarations = NULL;
2412 declaration->init.is_defined = true;
2414 parse_compound_type_entries(declaration);
2421 static void parse_enum_entries(type_t *const enum_type)
2425 if(token.type == '}') {
2427 errorf(HERE, "empty enum not allowed");
2431 add_anchor_token('}');
2433 if(token.type != T_IDENTIFIER) {
2434 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
2436 rem_anchor_token('}');
2440 declaration_t *const entry = allocate_declaration_zero();
2441 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2442 entry->type = enum_type;
2443 entry->symbol = token.v.symbol;
2444 entry->source_position = token.source_position;
2447 if(token.type == '=') {
2449 expression_t *value = parse_constant_expression();
2451 value = create_implicit_cast(value, enum_type);
2452 entry->init.enum_value = value;
2457 record_declaration(entry);
2459 if(token.type != ',')
2462 } while(token.type != '}');
2463 rem_anchor_token('}');
2471 static type_t *parse_enum_specifier(void)
2475 declaration_t *declaration;
2478 if(token.type == T_IDENTIFIER) {
2479 symbol = token.v.symbol;
2482 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2483 } else if(token.type != '{') {
2484 parse_error_expected("while parsing enum type specifier",
2485 T_IDENTIFIER, '{', 0);
2492 if(declaration == NULL) {
2493 declaration = allocate_declaration_zero();
2494 declaration->namespc = NAMESPACE_ENUM;
2495 declaration->source_position = token.source_position;
2496 declaration->symbol = symbol;
2497 declaration->parent_scope = scope;
2500 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2501 type->enumt.declaration = declaration;
2503 if(token.type == '{') {
2504 if(declaration->init.is_defined) {
2505 errorf(HERE, "multiple definitions of enum %Y", symbol);
2507 if (symbol != NULL) {
2508 environment_push(declaration);
2510 append_declaration(declaration);
2511 declaration->init.is_defined = 1;
2513 parse_enum_entries(type);
2521 * if a symbol is a typedef to another type, return true
2523 static bool is_typedef_symbol(symbol_t *symbol)
2525 const declaration_t *const declaration =
2526 get_declaration(symbol, NAMESPACE_NORMAL);
2528 declaration != NULL &&
2529 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2532 static type_t *parse_typeof(void)
2539 add_anchor_token(')');
2541 expression_t *expression = NULL;
2544 switch(token.type) {
2545 case T___extension__:
2546 /* this can be a prefix to a typename or an expression */
2547 /* we simply eat it now. */
2550 } while(token.type == T___extension__);
2554 if(is_typedef_symbol(token.v.symbol)) {
2555 type = parse_typename();
2557 expression = parse_expression();
2558 type = expression->base.type;
2563 type = parse_typename();
2567 expression = parse_expression();
2568 type = expression->base.type;
2572 rem_anchor_token(')');
2575 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2576 typeof_type->typeoft.expression = expression;
2577 typeof_type->typeoft.typeof_type = type;
2585 SPECIFIER_SIGNED = 1 << 0,
2586 SPECIFIER_UNSIGNED = 1 << 1,
2587 SPECIFIER_LONG = 1 << 2,
2588 SPECIFIER_INT = 1 << 3,
2589 SPECIFIER_DOUBLE = 1 << 4,
2590 SPECIFIER_CHAR = 1 << 5,
2591 SPECIFIER_SHORT = 1 << 6,
2592 SPECIFIER_LONG_LONG = 1 << 7,
2593 SPECIFIER_FLOAT = 1 << 8,
2594 SPECIFIER_BOOL = 1 << 9,
2595 SPECIFIER_VOID = 1 << 10,
2596 SPECIFIER_INT8 = 1 << 11,
2597 SPECIFIER_INT16 = 1 << 12,
2598 SPECIFIER_INT32 = 1 << 13,
2599 SPECIFIER_INT64 = 1 << 14,
2600 SPECIFIER_INT128 = 1 << 15,
2601 #ifdef PROVIDE_COMPLEX
2602 SPECIFIER_COMPLEX = 1 << 16,
2603 SPECIFIER_IMAGINARY = 1 << 17,
2607 static type_t *create_builtin_type(symbol_t *const symbol,
2608 type_t *const real_type)
2610 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2611 type->builtin.symbol = symbol;
2612 type->builtin.real_type = real_type;
2614 type_t *result = typehash_insert(type);
2615 if (type != result) {
2622 static type_t *get_typedef_type(symbol_t *symbol)
2624 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2625 if(declaration == NULL
2626 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2629 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2630 type->typedeft.declaration = declaration;
2636 * check for the allowed MS alignment values.
2638 static bool check_elignment_value(long long intvalue) {
2639 if(intvalue < 1 || intvalue > 8192) {
2640 errorf(HERE, "illegal alignment value");
2643 unsigned v = (unsigned)intvalue;
2644 for(unsigned i = 1; i <= 8192; i += i) {
2648 errorf(HERE, "alignment must be power of two");
2652 #define DET_MOD(name, tag) do { \
2653 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2654 *modifiers |= tag; \
2657 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2659 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2662 if(token.type == T_restrict) {
2664 DET_MOD(restrict, DM_RESTRICT);
2666 } else if(token.type != T_IDENTIFIER)
2668 symbol_t *symbol = token.v.symbol;
2669 if(symbol == sym_align) {
2672 if(token.type != T_INTEGER)
2674 if(check_elignment_value(token.v.intvalue)) {
2675 if(specifiers->alignment != 0)
2676 warningf(HERE, "align used more than once");
2677 specifiers->alignment = (unsigned char)token.v.intvalue;
2681 } else if(symbol == sym_allocate) {
2684 if(token.type != T_IDENTIFIER)
2686 (void)token.v.symbol;
2688 } else if(symbol == sym_dllimport) {
2690 DET_MOD(dllimport, DM_DLLIMPORT);
2691 } else if(symbol == sym_dllexport) {
2693 DET_MOD(dllexport, DM_DLLEXPORT);
2694 } else if(symbol == sym_thread) {
2696 DET_MOD(thread, DM_THREAD);
2697 } else if(symbol == sym_naked) {
2699 DET_MOD(naked, DM_NAKED);
2700 } else if(symbol == sym_noinline) {
2702 DET_MOD(noinline, DM_NOINLINE);
2703 } else if(symbol == sym_noreturn) {
2705 DET_MOD(noreturn, DM_NORETURN);
2706 } else if(symbol == sym_nothrow) {
2708 DET_MOD(nothrow, DM_NOTHROW);
2709 } else if(symbol == sym_novtable) {
2711 DET_MOD(novtable, DM_NOVTABLE);
2712 } else if(symbol == sym_property) {
2716 bool is_get = false;
2717 if(token.type != T_IDENTIFIER)
2719 if(token.v.symbol == sym_get) {
2721 } else if(token.v.symbol == sym_put) {
2723 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2728 if(token.type != T_IDENTIFIER)
2731 if(specifiers->get_property_sym != NULL) {
2732 errorf(HERE, "get property name already specified");
2734 specifiers->get_property_sym = token.v.symbol;
2737 if(specifiers->put_property_sym != NULL) {
2738 errorf(HERE, "put property name already specified");
2740 specifiers->put_property_sym = token.v.symbol;
2744 if(token.type == ',') {
2751 } else if(symbol == sym_selectany) {
2753 DET_MOD(selectany, DM_SELECTANY);
2754 } else if(symbol == sym_uuid) {
2757 if(token.type != T_STRING_LITERAL)
2761 } else if(symbol == sym_deprecated) {
2763 if(specifiers->deprecated != 0)
2764 warningf(HERE, "deprecated used more than once");
2765 specifiers->deprecated = 1;
2766 if(token.type == '(') {
2768 if(token.type == T_STRING_LITERAL) {
2769 specifiers->deprecated_string = token.v.string.begin;
2772 errorf(HERE, "string literal expected");
2776 } else if(symbol == sym_noalias) {
2778 DET_MOD(noalias, DM_NOALIAS);
2780 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2782 if(token.type == '(')
2786 if (token.type == ',')
2793 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2795 type_t *type = NULL;
2796 unsigned type_qualifiers = 0;
2797 unsigned type_specifiers = 0;
2800 specifiers->source_position = token.source_position;
2803 switch(token.type) {
2806 #define MATCH_STORAGE_CLASS(token, class) \
2808 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2809 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2811 specifiers->declared_storage_class = class; \
2815 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2816 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2817 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2818 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2819 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2824 add_anchor_token(')');
2825 parse_microsoft_extended_decl_modifier(specifiers);
2826 rem_anchor_token(')');
2831 switch (specifiers->declared_storage_class) {
2832 case STORAGE_CLASS_NONE:
2833 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2836 case STORAGE_CLASS_EXTERN:
2837 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2840 case STORAGE_CLASS_STATIC:
2841 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2845 errorf(HERE, "multiple storage classes in declaration specifiers");
2851 /* type qualifiers */
2852 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2854 type_qualifiers |= qualifier; \
2858 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2859 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2860 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2861 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2862 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2863 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2864 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2865 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2867 case T___extension__:
2872 /* type specifiers */
2873 #define MATCH_SPECIFIER(token, specifier, name) \
2876 if(type_specifiers & specifier) { \
2877 errorf(HERE, "multiple " name " type specifiers given"); \
2879 type_specifiers |= specifier; \
2883 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2884 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2885 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2886 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2887 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2888 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2889 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2890 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2891 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2892 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2893 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2894 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2895 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2896 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2897 #ifdef PROVIDE_COMPLEX
2898 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2899 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2901 case T__forceinline:
2902 /* only in microsoft mode */
2903 specifiers->decl_modifiers |= DM_FORCEINLINE;
2907 specifiers->is_inline = true;
2912 if(type_specifiers & SPECIFIER_LONG_LONG) {
2913 errorf(HERE, "multiple type specifiers given");
2914 } else if(type_specifiers & SPECIFIER_LONG) {
2915 type_specifiers |= SPECIFIER_LONG_LONG;
2917 type_specifiers |= SPECIFIER_LONG;
2922 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2924 type->compound.declaration = parse_compound_type_specifier(true);
2928 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2930 type->compound.declaration = parse_compound_type_specifier(false);
2934 type = parse_enum_specifier();
2937 type = parse_typeof();
2939 case T___builtin_va_list:
2940 type = duplicate_type(type_valist);
2944 case T___attribute__:
2948 case T_IDENTIFIER: {
2949 /* only parse identifier if we haven't found a type yet */
2950 if(type != NULL || type_specifiers != 0)
2951 goto finish_specifiers;
2953 type_t *typedef_type = get_typedef_type(token.v.symbol);
2955 if(typedef_type == NULL)
2956 goto finish_specifiers;
2959 type = typedef_type;
2963 /* function specifier */
2965 goto finish_specifiers;
2972 atomic_type_kind_t atomic_type;
2974 /* match valid basic types */
2975 switch(type_specifiers) {
2976 case SPECIFIER_VOID:
2977 atomic_type = ATOMIC_TYPE_VOID;
2979 case SPECIFIER_CHAR:
2980 atomic_type = ATOMIC_TYPE_CHAR;
2982 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2983 atomic_type = ATOMIC_TYPE_SCHAR;
2985 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2986 atomic_type = ATOMIC_TYPE_UCHAR;
2988 case SPECIFIER_SHORT:
2989 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2990 case SPECIFIER_SHORT | SPECIFIER_INT:
2991 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2992 atomic_type = ATOMIC_TYPE_SHORT;
2994 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2995 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2996 atomic_type = ATOMIC_TYPE_USHORT;
2999 case SPECIFIER_SIGNED:
3000 case SPECIFIER_SIGNED | SPECIFIER_INT:
3001 atomic_type = ATOMIC_TYPE_INT;
3003 case SPECIFIER_UNSIGNED:
3004 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3005 atomic_type = ATOMIC_TYPE_UINT;
3007 case SPECIFIER_LONG:
3008 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3009 case SPECIFIER_LONG | SPECIFIER_INT:
3010 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3011 atomic_type = ATOMIC_TYPE_LONG;
3013 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3014 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3015 atomic_type = ATOMIC_TYPE_ULONG;
3017 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3018 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3019 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3020 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3022 atomic_type = ATOMIC_TYPE_LONGLONG;
3024 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3025 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3027 atomic_type = ATOMIC_TYPE_ULONGLONG;
3030 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3031 atomic_type = unsigned_int8_type_kind;
3034 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3035 atomic_type = unsigned_int16_type_kind;
3038 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3039 atomic_type = unsigned_int32_type_kind;
3042 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3043 atomic_type = unsigned_int64_type_kind;
3046 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3047 atomic_type = unsigned_int128_type_kind;
3050 case SPECIFIER_INT8:
3051 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3052 atomic_type = int8_type_kind;
3055 case SPECIFIER_INT16:
3056 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3057 atomic_type = int16_type_kind;
3060 case SPECIFIER_INT32:
3061 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3062 atomic_type = int32_type_kind;
3065 case SPECIFIER_INT64:
3066 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3067 atomic_type = int64_type_kind;
3070 case SPECIFIER_INT128:
3071 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3072 atomic_type = int128_type_kind;
3075 case SPECIFIER_FLOAT:
3076 atomic_type = ATOMIC_TYPE_FLOAT;
3078 case SPECIFIER_DOUBLE:
3079 atomic_type = ATOMIC_TYPE_DOUBLE;
3081 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3082 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3084 case SPECIFIER_BOOL:
3085 atomic_type = ATOMIC_TYPE_BOOL;
3087 #ifdef PROVIDE_COMPLEX
3088 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3089 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
3091 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3092 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
3094 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3095 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
3097 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3098 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
3100 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3101 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
3103 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3104 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
3108 /* invalid specifier combination, give an error message */
3109 if(type_specifiers == 0) {
3110 if (! strict_mode) {
3111 if (warning.implicit_int) {
3112 warningf(HERE, "no type specifiers in declaration, using 'int'");
3114 atomic_type = ATOMIC_TYPE_INT;
3117 errorf(HERE, "no type specifiers given in declaration");
3119 } else if((type_specifiers & SPECIFIER_SIGNED) &&
3120 (type_specifiers & SPECIFIER_UNSIGNED)) {
3121 errorf(HERE, "signed and unsigned specifiers gives");
3122 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3123 errorf(HERE, "only integer types can be signed or unsigned");
3125 errorf(HERE, "multiple datatypes in declaration");
3127 atomic_type = ATOMIC_TYPE_INVALID;
3130 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
3131 type->atomic.akind = atomic_type;
3134 if(type_specifiers != 0) {
3135 errorf(HERE, "multiple datatypes in declaration");
3139 type->base.qualifiers = type_qualifiers;
3140 /* FIXME: check type qualifiers here */
3142 type_t *result = typehash_insert(type);
3143 if(newtype && result != type) {
3147 specifiers->type = result;
3152 static type_qualifiers_t parse_type_qualifiers(void)
3154 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
3157 switch(token.type) {
3158 /* type qualifiers */
3159 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3160 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3161 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3162 /* microsoft extended type modifiers */
3163 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3164 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3165 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3166 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3167 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3170 return type_qualifiers;
3175 static declaration_t *parse_identifier_list(void)
3177 declaration_t *declarations = NULL;
3178 declaration_t *last_declaration = NULL;
3180 declaration_t *const declaration = allocate_declaration_zero();
3181 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3182 declaration->source_position = token.source_position;
3183 declaration->symbol = token.v.symbol;
3186 if(last_declaration != NULL) {
3187 last_declaration->next = declaration;
3189 declarations = declaration;
3191 last_declaration = declaration;
3193 if(token.type != ',')
3196 } while(token.type == T_IDENTIFIER);
3198 return declarations;
3201 static void semantic_parameter(declaration_t *declaration)
3203 /* TODO: improve error messages */
3205 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3206 errorf(HERE, "typedef not allowed in parameter list");
3207 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
3208 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3209 errorf(HERE, "parameter may only have none or register storage class");
3212 type_t *const orig_type = declaration->type;
3213 type_t * type = skip_typeref(orig_type);
3215 /* Array as last part of a parameter type is just syntactic sugar. Turn it
3216 * into a pointer. § 6.7.5.3 (7) */
3217 if (is_type_array(type)) {
3218 type_t *const element_type = type->array.element_type;
3220 type = make_pointer_type(element_type, type->base.qualifiers);
3222 declaration->type = type;
3225 if(is_type_incomplete(type)) {
3226 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3227 orig_type, declaration->symbol);
3231 static declaration_t *parse_parameter(void)
3233 declaration_specifiers_t specifiers;
3234 memset(&specifiers, 0, sizeof(specifiers));
3236 parse_declaration_specifiers(&specifiers);
3238 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3240 semantic_parameter(declaration);
3245 static declaration_t *parse_parameters(function_type_t *type)
3247 if(token.type == T_IDENTIFIER) {
3248 symbol_t *symbol = token.v.symbol;
3249 if(!is_typedef_symbol(symbol)) {
3250 type->kr_style_parameters = true;
3251 return parse_identifier_list();
3255 if(token.type == ')') {
3256 type->unspecified_parameters = 1;
3259 if(token.type == T_void && look_ahead(1)->type == ')') {
3264 declaration_t *declarations = NULL;
3265 declaration_t *declaration;
3266 declaration_t *last_declaration = NULL;
3267 function_parameter_t *parameter;
3268 function_parameter_t *last_parameter = NULL;
3271 switch(token.type) {
3275 return declarations;
3278 case T___extension__:
3280 declaration = parse_parameter();
3282 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3283 memset(parameter, 0, sizeof(parameter[0]));
3284 parameter->type = declaration->type;
3286 if(last_parameter != NULL) {
3287 last_declaration->next = declaration;
3288 last_parameter->next = parameter;
3290 type->parameters = parameter;
3291 declarations = declaration;
3293 last_parameter = parameter;
3294 last_declaration = declaration;
3298 return declarations;
3300 if(token.type != ',')
3301 return declarations;
3311 } construct_type_kind_t;
3313 typedef struct construct_type_t construct_type_t;
3314 struct construct_type_t {
3315 construct_type_kind_t kind;
3316 construct_type_t *next;
3319 typedef struct parsed_pointer_t parsed_pointer_t;
3320 struct parsed_pointer_t {
3321 construct_type_t construct_type;
3322 type_qualifiers_t type_qualifiers;
3325 typedef struct construct_function_type_t construct_function_type_t;
3326 struct construct_function_type_t {
3327 construct_type_t construct_type;
3328 type_t *function_type;
3331 typedef struct parsed_array_t parsed_array_t;
3332 struct parsed_array_t {
3333 construct_type_t construct_type;
3334 type_qualifiers_t type_qualifiers;
3340 typedef struct construct_base_type_t construct_base_type_t;
3341 struct construct_base_type_t {
3342 construct_type_t construct_type;
3346 static construct_type_t *parse_pointer_declarator(void)
3350 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3351 memset(pointer, 0, sizeof(pointer[0]));
3352 pointer->construct_type.kind = CONSTRUCT_POINTER;
3353 pointer->type_qualifiers = parse_type_qualifiers();
3355 return (construct_type_t*) pointer;
3358 static construct_type_t *parse_array_declarator(void)
3361 add_anchor_token(']');
3363 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3364 memset(array, 0, sizeof(array[0]));
3365 array->construct_type.kind = CONSTRUCT_ARRAY;
3367 if(token.type == T_static) {
3368 array->is_static = true;
3372 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3373 if(type_qualifiers != 0) {
3374 if(token.type == T_static) {
3375 array->is_static = true;
3379 array->type_qualifiers = type_qualifiers;
3381 if(token.type == '*' && look_ahead(1)->type == ']') {
3382 array->is_variable = true;
3384 } else if(token.type != ']') {
3385 array->size = parse_assignment_expression();
3388 rem_anchor_token(']');
3391 return (construct_type_t*) array;
3396 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3399 add_anchor_token(')');
3402 if(declaration != NULL) {
3403 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
3405 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
3408 declaration_t *parameters = parse_parameters(&type->function);
3409 if(declaration != NULL) {
3410 declaration->scope.declarations = parameters;
3413 construct_function_type_t *construct_function_type =
3414 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3415 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3416 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3417 construct_function_type->function_type = type;
3419 rem_anchor_token(')');
3423 return (construct_type_t*) construct_function_type;
3426 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3427 bool may_be_abstract)
3429 /* construct a single linked list of construct_type_t's which describe
3430 * how to construct the final declarator type */
3431 construct_type_t *first = NULL;
3432 construct_type_t *last = NULL;
3435 while(token.type == '*') {
3436 construct_type_t *type = parse_pointer_declarator();
3447 /* TODO: find out if this is correct */
3450 construct_type_t *inner_types = NULL;
3452 switch(token.type) {
3454 if(declaration == NULL) {
3455 errorf(HERE, "no identifier expected in typename");
3457 declaration->symbol = token.v.symbol;
3458 declaration->source_position = token.source_position;
3464 add_anchor_token(')');
3465 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3466 rem_anchor_token(')');
3472 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3473 /* avoid a loop in the outermost scope, because eat_statement doesn't
3475 if(token.type == '}' && current_function == NULL) {
3483 construct_type_t *p = last;
3486 construct_type_t *type;
3487 switch(token.type) {
3489 type = parse_function_declarator(declaration);
3492 type = parse_array_declarator();
3495 goto declarator_finished;
3498 /* insert in the middle of the list (behind p) */
3500 type->next = p->next;
3511 declarator_finished:
3514 /* append inner_types at the end of the list, we don't to set last anymore
3515 * as it's not needed anymore */
3517 assert(first == NULL);
3518 first = inner_types;
3520 last->next = inner_types;
3528 static type_t *construct_declarator_type(construct_type_t *construct_list,
3531 construct_type_t *iter = construct_list;
3532 for( ; iter != NULL; iter = iter->next) {
3533 switch(iter->kind) {
3534 case CONSTRUCT_INVALID:
3535 internal_errorf(HERE, "invalid type construction found");
3536 case CONSTRUCT_FUNCTION: {
3537 construct_function_type_t *construct_function_type
3538 = (construct_function_type_t*) iter;
3540 type_t *function_type = construct_function_type->function_type;
3542 function_type->function.return_type = type;
3544 type_t *skipped_return_type = skip_typeref(type);
3545 if (is_type_function(skipped_return_type)) {
3546 errorf(HERE, "function returning function is not allowed");
3547 type = type_error_type;
3548 } else if (is_type_array(skipped_return_type)) {
3549 errorf(HERE, "function returning array is not allowed");
3550 type = type_error_type;
3552 type = function_type;
3557 case CONSTRUCT_POINTER: {
3558 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3559 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3560 pointer_type->pointer.points_to = type;
3561 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3563 type = pointer_type;
3567 case CONSTRUCT_ARRAY: {
3568 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3569 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3571 expression_t *size_expression = parsed_array->size;
3572 if(size_expression != NULL) {
3574 = create_implicit_cast(size_expression, type_size_t);
3577 array_type->base.qualifiers = parsed_array->type_qualifiers;
3578 array_type->array.element_type = type;
3579 array_type->array.is_static = parsed_array->is_static;
3580 array_type->array.is_variable = parsed_array->is_variable;
3581 array_type->array.size_expression = size_expression;
3583 if(size_expression != NULL) {
3584 if(is_constant_expression(size_expression)) {
3585 array_type->array.size_constant = true;
3586 array_type->array.size
3587 = fold_constant(size_expression);
3589 array_type->array.is_vla = true;
3593 type_t *skipped_type = skip_typeref(type);
3594 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3595 errorf(HERE, "array of void is not allowed");
3596 type = type_error_type;
3604 type_t *hashed_type = typehash_insert(type);
3605 if(hashed_type != type) {
3606 /* the function type was constructed earlier freeing it here will
3607 * destroy other types... */
3608 if(iter->kind != CONSTRUCT_FUNCTION) {
3618 static declaration_t *parse_declarator(
3619 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3621 declaration_t *const declaration = allocate_declaration_zero();
3622 declaration->declared_storage_class = specifiers->declared_storage_class;
3623 declaration->modifiers = specifiers->decl_modifiers;
3624 declaration->deprecated = specifiers->deprecated;
3625 declaration->deprecated_string = specifiers->deprecated_string;
3626 declaration->get_property_sym = specifiers->get_property_sym;
3627 declaration->put_property_sym = specifiers->put_property_sym;
3628 declaration->is_inline = specifiers->is_inline;
3630 declaration->storage_class = specifiers->declared_storage_class;
3631 if(declaration->storage_class == STORAGE_CLASS_NONE
3632 && scope != global_scope) {
3633 declaration->storage_class = STORAGE_CLASS_AUTO;
3636 if(specifiers->alignment != 0) {
3637 /* TODO: add checks here */
3638 declaration->alignment = specifiers->alignment;
3641 construct_type_t *construct_type
3642 = parse_inner_declarator(declaration, may_be_abstract);
3643 type_t *const type = specifiers->type;
3644 declaration->type = construct_declarator_type(construct_type, type);
3646 if(construct_type != NULL) {
3647 obstack_free(&temp_obst, construct_type);
3653 static type_t *parse_abstract_declarator(type_t *base_type)
3655 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3657 type_t *result = construct_declarator_type(construct_type, base_type);
3658 if(construct_type != NULL) {
3659 obstack_free(&temp_obst, construct_type);
3665 static declaration_t *append_declaration(declaration_t* const declaration)
3667 if (last_declaration != NULL) {
3668 last_declaration->next = declaration;
3670 scope->declarations = declaration;
3672 last_declaration = declaration;
3677 * Check if the declaration of main is suspicious. main should be a
3678 * function with external linkage, returning int, taking either zero
3679 * arguments, two, or three arguments of appropriate types, ie.
3681 * int main([ int argc, char **argv [, char **env ] ]).
3683 * @param decl the declaration to check
3684 * @param type the function type of the declaration
3686 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3688 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3689 warningf(decl->source_position, "'main' is normally a non-static function");
3691 if (skip_typeref(func_type->return_type) != type_int) {
3692 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3694 const function_parameter_t *parm = func_type->parameters;
3696 type_t *const first_type = parm->type;
3697 if (!types_compatible(skip_typeref(first_type), type_int)) {
3698 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3702 type_t *const second_type = parm->type;
3703 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3704 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3708 type_t *const third_type = parm->type;
3709 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3710 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3714 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3718 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3724 * Check if a symbol is the equal to "main".
3726 static bool is_sym_main(const symbol_t *const sym)
3728 return strcmp(sym->string, "main") == 0;
3731 static declaration_t *internal_record_declaration(
3732 declaration_t *const declaration,
3733 const bool is_function_definition)
3735 const symbol_t *const symbol = declaration->symbol;
3736 const namespace_t namespc = (namespace_t)declaration->namespc;
3738 type_t *const orig_type = declaration->type;
3739 type_t *const type = skip_typeref(orig_type);
3740 if (is_type_function(type) &&
3741 type->function.unspecified_parameters &&
3742 warning.strict_prototypes) {
3743 warningf(declaration->source_position,
3744 "function declaration '%#T' is not a prototype",
3745 orig_type, declaration->symbol);
3748 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3749 check_type_of_main(declaration, &type->function);
3752 assert(declaration->symbol != NULL);
3753 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3755 assert(declaration != previous_declaration);
3756 if (previous_declaration != NULL) {
3757 if (previous_declaration->parent_scope == scope) {
3758 /* can happen for K&R style declarations */
3759 if(previous_declaration->type == NULL) {
3760 previous_declaration->type = declaration->type;
3763 const type_t *prev_type = skip_typeref(previous_declaration->type);
3764 if (!types_compatible(type, prev_type)) {
3765 errorf(declaration->source_position,
3766 "declaration '%#T' is incompatible with '%#T' (declared %P)",
3767 orig_type, symbol, previous_declaration->type, symbol,
3768 previous_declaration->source_position);
3770 unsigned old_storage_class = previous_declaration->storage_class;
3771 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3772 errorf(declaration->source_position, "redeclaration of enum entry '%Y' (declared %P)",
3773 symbol, previous_declaration->source_position);
3774 return previous_declaration;
3777 unsigned new_storage_class = declaration->storage_class;
3779 if(is_type_incomplete(prev_type)) {
3780 previous_declaration->type = type;
3784 /* pretend no storage class means extern for function
3785 * declarations (except if the previous declaration is neither
3786 * none nor extern) */
3787 if (is_type_function(type)) {
3788 switch (old_storage_class) {
3789 case STORAGE_CLASS_NONE:
3790 old_storage_class = STORAGE_CLASS_EXTERN;
3792 case STORAGE_CLASS_EXTERN:
3793 if (is_function_definition) {
3794 if (warning.missing_prototypes &&
3795 prev_type->function.unspecified_parameters &&
3796 !is_sym_main(symbol)) {
3797 warningf(declaration->source_position,
3798 "no previous prototype for '%#T'",
3801 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3802 new_storage_class = STORAGE_CLASS_EXTERN;
3810 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3811 new_storage_class == STORAGE_CLASS_EXTERN) {
3812 warn_redundant_declaration:
3813 if (warning.redundant_decls) {
3814 warningf(declaration->source_position,
3815 "redundant declaration for '%Y' (declared %P)",
3816 symbol, previous_declaration->source_position);
3818 } else if (current_function == NULL) {
3819 if (old_storage_class != STORAGE_CLASS_STATIC &&
3820 new_storage_class == STORAGE_CLASS_STATIC) {
3821 errorf(declaration->source_position,
3822 "static declaration of '%Y' follows non-static declaration (declared %P)",
3823 symbol, previous_declaration->source_position);
3825 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3826 goto warn_redundant_declaration;
3828 if (new_storage_class == STORAGE_CLASS_NONE) {
3829 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3830 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3834 if (old_storage_class == new_storage_class) {
3835 errorf(declaration->source_position,
3836 "redeclaration of '%Y' (declared %P)",
3837 symbol, previous_declaration->source_position);
3839 errorf(declaration->source_position,
3840 "redeclaration of '%Y' with different linkage (declared %P)",
3841 symbol, previous_declaration->source_position);
3845 return previous_declaration;
3847 } else if (is_function_definition) {
3848 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3849 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3850 warningf(declaration->source_position,
3851 "no previous prototype for '%#T'", orig_type, symbol);
3852 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3853 warningf(declaration->source_position,
3854 "no previous declaration for '%#T'", orig_type,
3858 } else if (warning.missing_declarations &&
3859 scope == global_scope &&
3860 !is_type_function(type) && (
3861 declaration->storage_class == STORAGE_CLASS_NONE ||
3862 declaration->storage_class == STORAGE_CLASS_THREAD
3864 warningf(declaration->source_position,
3865 "no previous declaration for '%#T'", orig_type, symbol);
3868 assert(declaration->parent_scope == NULL);
3869 assert(scope != NULL);
3871 declaration->parent_scope = scope;
3873 environment_push(declaration);
3874 return append_declaration(declaration);
3877 static declaration_t *record_declaration(declaration_t *declaration)
3879 return internal_record_declaration(declaration, false);
3882 static declaration_t *record_function_definition(declaration_t *declaration)
3884 return internal_record_declaration(declaration, true);
3887 static void parser_error_multiple_definition(declaration_t *declaration,
3888 const source_position_t source_position)
3890 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
3891 declaration->symbol, declaration->source_position);
3894 static bool is_declaration_specifier(const token_t *token,
3895 bool only_type_specifiers)
3897 switch(token->type) {
3901 return is_typedef_symbol(token->v.symbol);
3903 case T___extension__:
3906 return !only_type_specifiers;
3913 static void parse_init_declarator_rest(declaration_t *declaration)
3917 type_t *orig_type = declaration->type;
3918 type_t *type = skip_typeref(orig_type);
3920 if(declaration->init.initializer != NULL) {
3921 parser_error_multiple_definition(declaration, token.source_position);
3924 bool must_be_constant = false;
3925 if(declaration->storage_class == STORAGE_CLASS_STATIC
3926 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3927 || declaration->parent_scope == global_scope) {
3928 must_be_constant = true;
3931 parse_initializer_env_t env;
3932 env.type = orig_type;
3933 env.must_be_constant = must_be_constant;
3934 env.declaration = declaration;
3936 initializer_t *initializer = parse_initializer(&env);
3938 if(env.type != orig_type) {
3939 orig_type = env.type;
3940 type = skip_typeref(orig_type);
3941 declaration->type = env.type;
3944 if(is_type_function(type)) {
3945 errorf(declaration->source_position,
3946 "initializers not allowed for function types at declator '%Y' (type '%T')",
3947 declaration->symbol, orig_type);
3949 declaration->init.initializer = initializer;
3953 /* parse rest of a declaration without any declarator */
3954 static void parse_anonymous_declaration_rest(
3955 const declaration_specifiers_t *specifiers,
3956 parsed_declaration_func finished_declaration)
3960 declaration_t *const declaration = allocate_declaration_zero();
3961 declaration->type = specifiers->type;
3962 declaration->declared_storage_class = specifiers->declared_storage_class;
3963 declaration->source_position = specifiers->source_position;
3964 declaration->modifiers = specifiers->decl_modifiers;
3966 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3967 warningf(declaration->source_position, "useless storage class in empty declaration");
3969 declaration->storage_class = STORAGE_CLASS_NONE;
3971 type_t *type = declaration->type;
3972 switch (type->kind) {
3973 case TYPE_COMPOUND_STRUCT:
3974 case TYPE_COMPOUND_UNION: {
3975 if (type->compound.declaration->symbol == NULL) {
3976 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3985 warningf(declaration->source_position, "empty declaration");
3989 finished_declaration(declaration);
3992 static void parse_declaration_rest(declaration_t *ndeclaration,
3993 const declaration_specifiers_t *specifiers,
3994 parsed_declaration_func finished_declaration)
3996 add_anchor_token(';');
3997 add_anchor_token('=');
3998 add_anchor_token(',');
4000 declaration_t *declaration = finished_declaration(ndeclaration);
4002 type_t *orig_type = declaration->type;
4003 type_t *type = skip_typeref(orig_type);
4005 if (type->kind != TYPE_FUNCTION &&
4006 declaration->is_inline &&
4007 is_type_valid(type)) {
4008 warningf(declaration->source_position,
4009 "variable '%Y' declared 'inline'\n", declaration->symbol);
4012 if(token.type == '=') {
4013 parse_init_declarator_rest(declaration);
4016 if(token.type != ',')
4020 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4025 rem_anchor_token(';');
4026 rem_anchor_token('=');
4027 rem_anchor_token(',');
4030 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4032 symbol_t *symbol = declaration->symbol;
4033 if(symbol == NULL) {
4034 errorf(HERE, "anonymous declaration not valid as function parameter");
4037 namespace_t namespc = (namespace_t) declaration->namespc;
4038 if(namespc != NAMESPACE_NORMAL) {
4039 return record_declaration(declaration);
4042 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4043 if(previous_declaration == NULL ||
4044 previous_declaration->parent_scope != scope) {
4045 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4050 if(previous_declaration->type == NULL) {
4051 previous_declaration->type = declaration->type;
4052 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4053 previous_declaration->storage_class = declaration->storage_class;
4054 previous_declaration->parent_scope = scope;
4055 return previous_declaration;
4057 return record_declaration(declaration);
4061 static void parse_declaration(parsed_declaration_func finished_declaration)
4063 declaration_specifiers_t specifiers;
4064 memset(&specifiers, 0, sizeof(specifiers));
4065 parse_declaration_specifiers(&specifiers);
4067 if(token.type == ';') {
4068 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4070 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4071 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4075 static void parse_kr_declaration_list(declaration_t *declaration)
4077 type_t *type = skip_typeref(declaration->type);
4078 if(!is_type_function(type))
4081 if(!type->function.kr_style_parameters)
4084 /* push function parameters */
4085 int top = environment_top();
4086 scope_t *last_scope = scope;
4087 set_scope(&declaration->scope);
4089 declaration_t *parameter = declaration->scope.declarations;
4090 for( ; parameter != NULL; parameter = parameter->next) {
4091 assert(parameter->parent_scope == NULL);
4092 parameter->parent_scope = scope;
4093 environment_push(parameter);
4096 /* parse declaration list */
4097 while(is_declaration_specifier(&token, false)) {
4098 parse_declaration(finished_kr_declaration);
4101 /* pop function parameters */
4102 assert(scope == &declaration->scope);
4103 set_scope(last_scope);
4104 environment_pop_to(top);
4106 /* update function type */
4107 type_t *new_type = duplicate_type(type);
4108 new_type->function.kr_style_parameters = false;
4110 function_parameter_t *parameters = NULL;
4111 function_parameter_t *last_parameter = NULL;
4113 declaration_t *parameter_declaration = declaration->scope.declarations;
4114 for( ; parameter_declaration != NULL;
4115 parameter_declaration = parameter_declaration->next) {
4116 type_t *parameter_type = parameter_declaration->type;
4117 if(parameter_type == NULL) {
4119 errorf(HERE, "no type specified for function parameter '%Y'",
4120 parameter_declaration->symbol);
4122 if (warning.implicit_int) {
4123 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4124 parameter_declaration->symbol);
4126 parameter_type = type_int;
4127 parameter_declaration->type = parameter_type;
4131 semantic_parameter(parameter_declaration);
4132 parameter_type = parameter_declaration->type;
4134 function_parameter_t *function_parameter
4135 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4136 memset(function_parameter, 0, sizeof(function_parameter[0]));
4138 function_parameter->type = parameter_type;
4139 if(last_parameter != NULL) {
4140 last_parameter->next = function_parameter;
4142 parameters = function_parameter;
4144 last_parameter = function_parameter;
4146 new_type->function.parameters = parameters;
4148 type = typehash_insert(new_type);
4149 if(type != new_type) {
4150 obstack_free(type_obst, new_type);
4153 declaration->type = type;
4156 static bool first_err = true;
4159 * When called with first_err set, prints the name of the current function,
4162 static void print_in_function(void) {
4165 diagnosticf("%s: In function '%Y':\n",
4166 current_function->source_position.input_name,
4167 current_function->symbol);
4172 * Check if all labels are defined in the current function.
4173 * Check if all labels are used in the current function.
4175 static void check_labels(void)
4177 for (const goto_statement_t *goto_statement = goto_first;
4178 goto_statement != NULL;
4179 goto_statement = goto_statement->next) {
4180 declaration_t *label = goto_statement->label;
4183 if (label->source_position.input_name == NULL) {
4184 print_in_function();
4185 errorf(goto_statement->base.source_position,
4186 "label '%Y' used but not defined", label->symbol);
4189 goto_first = goto_last = NULL;
4191 if (warning.unused_label) {
4192 for (const label_statement_t *label_statement = label_first;
4193 label_statement != NULL;
4194 label_statement = label_statement->next) {
4195 const declaration_t *label = label_statement->label;
4197 if (! label->used) {
4198 print_in_function();
4199 warningf(label_statement->base.source_position,
4200 "label '%Y' defined but not used", label->symbol);
4204 label_first = label_last = NULL;
4208 * Check declarations of current_function for unused entities.
4210 static void check_declarations(void)
4212 if (warning.unused_parameter) {
4213 const scope_t *scope = ¤t_function->scope;
4215 const declaration_t *parameter = scope->declarations;
4216 for (; parameter != NULL; parameter = parameter->next) {
4217 if (! parameter->used) {
4218 print_in_function();
4219 warningf(parameter->source_position,
4220 "unused parameter '%Y'", parameter->symbol);
4224 if (warning.unused_variable) {
4228 static void parse_external_declaration(void)
4230 /* function-definitions and declarations both start with declaration
4232 declaration_specifiers_t specifiers;
4233 memset(&specifiers, 0, sizeof(specifiers));
4235 add_anchor_token(';');
4236 parse_declaration_specifiers(&specifiers);
4237 rem_anchor_token(';');
4239 /* must be a declaration */
4240 if(token.type == ';') {
4241 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4245 add_anchor_token(',');
4246 add_anchor_token('=');
4247 rem_anchor_token(';');
4249 /* declarator is common to both function-definitions and declarations */
4250 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4252 rem_anchor_token(',');
4253 rem_anchor_token('=');
4254 rem_anchor_token(';');
4256 /* must be a declaration */
4257 if(token.type == ',' || token.type == '=' || token.type == ';') {
4258 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4262 /* must be a function definition */
4263 parse_kr_declaration_list(ndeclaration);
4265 if(token.type != '{') {
4266 parse_error_expected("while parsing function definition", '{', 0);
4267 eat_until_matching_token(';');
4271 type_t *type = ndeclaration->type;
4273 /* note that we don't skip typerefs: the standard doesn't allow them here
4274 * (so we can't use is_type_function here) */
4275 if(type->kind != TYPE_FUNCTION) {
4276 if (is_type_valid(type)) {
4277 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4278 type, ndeclaration->symbol);
4284 /* § 6.7.5.3 (14) a function definition with () means no
4285 * parameters (and not unspecified parameters) */
4286 if(type->function.unspecified_parameters) {
4287 type_t *duplicate = duplicate_type(type);
4288 duplicate->function.unspecified_parameters = false;
4290 type = typehash_insert(duplicate);
4291 if(type != duplicate) {
4292 obstack_free(type_obst, duplicate);
4294 ndeclaration->type = type;
4297 declaration_t *const declaration = record_function_definition(ndeclaration);
4298 if(ndeclaration != declaration) {
4299 declaration->scope = ndeclaration->scope;
4301 type = skip_typeref(declaration->type);
4303 /* push function parameters and switch scope */
4304 int top = environment_top();
4305 scope_t *last_scope = scope;
4306 set_scope(&declaration->scope);
4308 declaration_t *parameter = declaration->scope.declarations;
4309 for( ; parameter != NULL; parameter = parameter->next) {
4310 if(parameter->parent_scope == &ndeclaration->scope) {
4311 parameter->parent_scope = scope;
4313 assert(parameter->parent_scope == NULL
4314 || parameter->parent_scope == scope);
4315 parameter->parent_scope = scope;
4316 environment_push(parameter);
4319 if(declaration->init.statement != NULL) {
4320 parser_error_multiple_definition(declaration, token.source_position);
4322 goto end_of_parse_external_declaration;
4324 /* parse function body */
4325 int label_stack_top = label_top();
4326 declaration_t *old_current_function = current_function;
4327 current_function = declaration;
4329 declaration->init.statement = parse_compound_statement();
4332 check_declarations();
4334 assert(current_function == declaration);
4335 current_function = old_current_function;
4336 label_pop_to(label_stack_top);
4339 end_of_parse_external_declaration:
4340 assert(scope == &declaration->scope);
4341 set_scope(last_scope);
4342 environment_pop_to(top);
4345 static type_t *make_bitfield_type(type_t *base, expression_t *size,
4346 source_position_t source_position)
4348 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4349 type->bitfield.base = base;
4350 type->bitfield.size = size;
4355 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4358 declaration_t *iter = compound_declaration->scope.declarations;
4359 for( ; iter != NULL; iter = iter->next) {
4360 if(iter->namespc != NAMESPACE_NORMAL)
4363 if(iter->symbol == NULL) {
4364 type_t *type = skip_typeref(iter->type);
4365 if(is_type_compound(type)) {
4366 declaration_t *result
4367 = find_compound_entry(type->compound.declaration, symbol);
4374 if(iter->symbol == symbol) {
4382 static void parse_compound_declarators(declaration_t *struct_declaration,
4383 const declaration_specifiers_t *specifiers)
4385 declaration_t *last_declaration = struct_declaration->scope.declarations;
4386 if(last_declaration != NULL) {
4387 while(last_declaration->next != NULL) {
4388 last_declaration = last_declaration->next;
4393 declaration_t *declaration;
4395 if(token.type == ':') {
4396 source_position_t source_position = HERE;
4399 type_t *base_type = specifiers->type;
4400 expression_t *size = parse_constant_expression();
4402 if(!is_type_integer(skip_typeref(base_type))) {
4403 errorf(HERE, "bitfield base type '%T' is not an integer type",
4407 type_t *type = make_bitfield_type(base_type, size, source_position);
4409 declaration = allocate_declaration_zero();
4410 declaration->namespc = NAMESPACE_NORMAL;
4411 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4412 declaration->storage_class = STORAGE_CLASS_NONE;
4413 declaration->source_position = source_position;
4414 declaration->modifiers = specifiers->decl_modifiers;
4415 declaration->type = type;
4417 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4419 type_t *orig_type = declaration->type;
4420 type_t *type = skip_typeref(orig_type);
4422 if(token.type == ':') {
4423 source_position_t source_position = HERE;
4425 expression_t *size = parse_constant_expression();
4427 if(!is_type_integer(type)) {
4428 errorf(HERE, "bitfield base type '%T' is not an "
4429 "integer type", orig_type);
4432 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
4433 declaration->type = bitfield_type;
4435 /* TODO we ignore arrays for now... what is missing is a check
4436 * that they're at the end of the struct */
4437 if(is_type_incomplete(type) && !is_type_array(type)) {
4439 "compound member '%Y' has incomplete type '%T'",
4440 declaration->symbol, orig_type);
4441 } else if(is_type_function(type)) {
4442 errorf(HERE, "compound member '%Y' must not have function "
4443 "type '%T'", declaration->symbol, orig_type);
4448 /* make sure we don't define a symbol multiple times */
4449 symbol_t *symbol = declaration->symbol;
4450 if(symbol != NULL) {
4451 declaration_t *prev_decl
4452 = find_compound_entry(struct_declaration, symbol);
4454 if(prev_decl != NULL) {
4455 assert(prev_decl->symbol == symbol);
4456 errorf(declaration->source_position,
4457 "multiple declarations of symbol '%Y' (declared %P)",
4458 symbol, prev_decl->source_position);
4462 /* append declaration */
4463 if(last_declaration != NULL) {
4464 last_declaration->next = declaration;
4466 struct_declaration->scope.declarations = declaration;
4468 last_declaration = declaration;
4470 if(token.type != ',')
4480 static void parse_compound_type_entries(declaration_t *compound_declaration)
4483 add_anchor_token('}');
4485 while(token.type != '}' && token.type != T_EOF) {
4486 declaration_specifiers_t specifiers;
4487 memset(&specifiers, 0, sizeof(specifiers));
4488 parse_declaration_specifiers(&specifiers);
4490 parse_compound_declarators(compound_declaration, &specifiers);
4492 rem_anchor_token('}');
4494 if(token.type == T_EOF) {
4495 errorf(HERE, "EOF while parsing struct");
4500 static type_t *parse_typename(void)
4502 declaration_specifiers_t specifiers;
4503 memset(&specifiers, 0, sizeof(specifiers));
4504 parse_declaration_specifiers(&specifiers);
4505 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4506 /* TODO: improve error message, user does probably not know what a
4507 * storage class is...
4509 errorf(HERE, "typename may not have a storage class");
4512 type_t *result = parse_abstract_declarator(specifiers.type);
4520 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4521 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4522 expression_t *left);
4524 typedef struct expression_parser_function_t expression_parser_function_t;
4525 struct expression_parser_function_t {
4526 unsigned precedence;
4527 parse_expression_function parser;
4528 unsigned infix_precedence;
4529 parse_expression_infix_function infix_parser;
4532 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4535 * Prints an error message if an expression was expected but not read
4537 static expression_t *expected_expression_error(void)
4539 /* skip the error message if the error token was read */
4540 if (token.type != T_ERROR) {
4541 errorf(HERE, "expected expression, got token '%K'", &token);
4545 return create_invalid_expression();
4549 * Parse a string constant.
4551 static expression_t *parse_string_const(void)
4554 if (token.type == T_STRING_LITERAL) {
4555 string_t res = token.v.string;
4557 while (token.type == T_STRING_LITERAL) {
4558 res = concat_strings(&res, &token.v.string);
4561 if (token.type != T_WIDE_STRING_LITERAL) {
4562 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4563 /* note: that we use type_char_ptr here, which is already the
4564 * automatic converted type. revert_automatic_type_conversion
4565 * will construct the array type */
4566 cnst->base.type = type_char_ptr;
4567 cnst->string.value = res;
4571 wres = concat_string_wide_string(&res, &token.v.wide_string);
4573 wres = token.v.wide_string;
4578 switch (token.type) {
4579 case T_WIDE_STRING_LITERAL:
4580 wres = concat_wide_strings(&wres, &token.v.wide_string);
4583 case T_STRING_LITERAL:
4584 wres = concat_wide_string_string(&wres, &token.v.string);
4588 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4589 cnst->base.type = type_wchar_t_ptr;
4590 cnst->wide_string.value = wres;
4599 * Parse an integer constant.
4601 static expression_t *parse_int_const(void)
4603 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4604 cnst->base.source_position = HERE;
4605 cnst->base.type = token.datatype;
4606 cnst->conste.v.int_value = token.v.intvalue;
4614 * Parse a character constant.
4616 static expression_t *parse_character_constant(void)
4618 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4620 cnst->base.source_position = HERE;
4621 cnst->base.type = token.datatype;
4622 cnst->conste.v.character = token.v.string;
4624 if (cnst->conste.v.character.size != 1) {
4625 if (warning.multichar && (c_mode & _GNUC)) {
4627 warningf(HERE, "multi-character character constant");
4629 errorf(HERE, "more than 1 characters in character constant");
4638 * Parse a wide character constant.
4640 static expression_t *parse_wide_character_constant(void)
4642 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4644 cnst->base.source_position = HERE;
4645 cnst->base.type = token.datatype;
4646 cnst->conste.v.wide_character = token.v.wide_string;
4648 if (cnst->conste.v.wide_character.size != 1) {
4649 if (warning.multichar && (c_mode & _GNUC)) {
4651 warningf(HERE, "multi-character character constant");
4653 errorf(HERE, "more than 1 characters in character constant");
4662 * Parse a float constant.
4664 static expression_t *parse_float_const(void)
4666 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4667 cnst->base.type = token.datatype;
4668 cnst->conste.v.float_value = token.v.floatvalue;
4675 static declaration_t *create_implicit_function(symbol_t *symbol,
4676 const source_position_t source_position)
4678 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4679 ntype->function.return_type = type_int;
4680 ntype->function.unspecified_parameters = true;
4682 type_t *type = typehash_insert(ntype);
4687 declaration_t *const declaration = allocate_declaration_zero();
4688 declaration->storage_class = STORAGE_CLASS_EXTERN;
4689 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4690 declaration->type = type;
4691 declaration->symbol = symbol;
4692 declaration->source_position = source_position;
4693 declaration->parent_scope = global_scope;
4695 scope_t *old_scope = scope;
4696 set_scope(global_scope);
4698 environment_push(declaration);
4699 /* prepends the declaration to the global declarations list */
4700 declaration->next = scope->declarations;
4701 scope->declarations = declaration;
4703 assert(scope == global_scope);
4704 set_scope(old_scope);
4710 * Creates a return_type (func)(argument_type) function type if not
4713 * @param return_type the return type
4714 * @param argument_type the argument type
4716 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4718 function_parameter_t *parameter
4719 = obstack_alloc(type_obst, sizeof(parameter[0]));
4720 memset(parameter, 0, sizeof(parameter[0]));
4721 parameter->type = argument_type;
4723 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4724 type->function.return_type = return_type;
4725 type->function.parameters = parameter;
4727 type_t *result = typehash_insert(type);
4728 if(result != type) {
4736 * Creates a function type for some function like builtins.
4738 * @param symbol the symbol describing the builtin
4740 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4742 switch(symbol->ID) {
4743 case T___builtin_alloca:
4744 return make_function_1_type(type_void_ptr, type_size_t);
4745 case T___builtin_nan:
4746 return make_function_1_type(type_double, type_char_ptr);
4747 case T___builtin_nanf:
4748 return make_function_1_type(type_float, type_char_ptr);
4749 case T___builtin_nand:
4750 return make_function_1_type(type_long_double, type_char_ptr);
4751 case T___builtin_va_end:
4752 return make_function_1_type(type_void, type_valist);
4754 internal_errorf(HERE, "not implemented builtin symbol found");
4759 * Performs automatic type cast as described in § 6.3.2.1.
4761 * @param orig_type the original type
4763 static type_t *automatic_type_conversion(type_t *orig_type)
4765 type_t *type = skip_typeref(orig_type);
4766 if(is_type_array(type)) {
4767 array_type_t *array_type = &type->array;
4768 type_t *element_type = array_type->element_type;
4769 unsigned qualifiers = array_type->type.qualifiers;
4771 return make_pointer_type(element_type, qualifiers);
4774 if(is_type_function(type)) {
4775 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4782 * reverts the automatic casts of array to pointer types and function
4783 * to function-pointer types as defined § 6.3.2.1
4785 type_t *revert_automatic_type_conversion(const expression_t *expression)
4787 switch (expression->kind) {
4788 case EXPR_REFERENCE: return expression->reference.declaration->type;
4789 case EXPR_SELECT: return expression->select.compound_entry->type;
4791 case EXPR_UNARY_DEREFERENCE: {
4792 const expression_t *const value = expression->unary.value;
4793 type_t *const type = skip_typeref(value->base.type);
4794 assert(is_type_pointer(type));
4795 return type->pointer.points_to;
4798 case EXPR_BUILTIN_SYMBOL:
4799 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4801 case EXPR_ARRAY_ACCESS: {
4802 const expression_t *array_ref = expression->array_access.array_ref;
4803 type_t *type_left = skip_typeref(array_ref->base.type);
4804 if (!is_type_valid(type_left))
4806 assert(is_type_pointer(type_left));
4807 return type_left->pointer.points_to;
4810 case EXPR_STRING_LITERAL: {
4811 size_t size = expression->string.value.size;
4812 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4815 case EXPR_WIDE_STRING_LITERAL: {
4816 size_t size = expression->wide_string.value.size;
4817 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4820 case EXPR_COMPOUND_LITERAL:
4821 return expression->compound_literal.type;
4826 return expression->base.type;
4829 static expression_t *parse_reference(void)
4831 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4833 reference_expression_t *ref = &expression->reference;
4834 ref->symbol = token.v.symbol;
4836 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4838 source_position_t source_position = token.source_position;
4841 if(declaration == NULL) {
4842 if (! strict_mode && token.type == '(') {
4843 /* an implicitly defined function */
4844 if (warning.implicit_function_declaration) {
4845 warningf(HERE, "implicit declaration of function '%Y'",
4849 declaration = create_implicit_function(ref->symbol,
4852 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4853 return create_invalid_expression();
4857 type_t *type = declaration->type;
4859 /* we always do the auto-type conversions; the & and sizeof parser contains
4860 * code to revert this! */
4861 type = automatic_type_conversion(type);
4863 ref->declaration = declaration;
4864 ref->base.type = type;
4866 /* this declaration is used */
4867 declaration->used = true;
4869 /* check for deprecated functions */
4870 if(declaration->deprecated != 0) {
4871 const char *prefix = "";
4872 if (is_type_function(declaration->type))
4873 prefix = "function ";
4875 if (declaration->deprecated_string != NULL) {
4876 warningf(source_position,
4877 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4878 declaration->deprecated_string);
4880 warningf(source_position,
4881 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4888 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4892 /* TODO check if explicit cast is allowed and issue warnings/errors */
4895 static expression_t *parse_compound_literal(type_t *type)
4897 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4899 parse_initializer_env_t env;
4901 env.declaration = NULL;
4902 env.must_be_constant = false;
4903 initializer_t *initializer = parse_initializer(&env);
4906 expression->compound_literal.initializer = initializer;
4907 expression->compound_literal.type = type;
4908 expression->base.type = automatic_type_conversion(type);
4914 * Parse a cast expression.
4916 static expression_t *parse_cast(void)
4918 source_position_t source_position = token.source_position;
4920 type_t *type = parse_typename();
4922 /* matching add_anchor_token() is at call site */
4923 rem_anchor_token(')');
4926 if(token.type == '{') {
4927 return parse_compound_literal(type);
4930 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4931 cast->base.source_position = source_position;
4933 expression_t *value = parse_sub_expression(20);
4935 check_cast_allowed(value, type);
4937 cast->base.type = type;
4938 cast->unary.value = value;
4942 return create_invalid_expression();
4946 * Parse a statement expression.
4948 static expression_t *parse_statement_expression(void)
4950 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4952 statement_t *statement = parse_compound_statement();
4953 expression->statement.statement = statement;
4954 expression->base.source_position = statement->base.source_position;
4956 /* find last statement and use its type */
4957 type_t *type = type_void;
4958 const statement_t *stmt = statement->compound.statements;
4960 while (stmt->base.next != NULL)
4961 stmt = stmt->base.next;
4963 if (stmt->kind == STATEMENT_EXPRESSION) {
4964 type = stmt->expression.expression->base.type;
4967 warningf(expression->base.source_position, "empty statement expression ({})");
4969 expression->base.type = type;
4975 return create_invalid_expression();
4979 * Parse a braced expression.
4981 static expression_t *parse_brace_expression(void)
4984 add_anchor_token(')');
4986 switch(token.type) {
4988 /* gcc extension: a statement expression */
4989 return parse_statement_expression();
4993 return parse_cast();
4995 if(is_typedef_symbol(token.v.symbol)) {
4996 return parse_cast();
5000 expression_t *result = parse_expression();
5001 rem_anchor_token(')');
5006 return create_invalid_expression();
5009 static expression_t *parse_function_keyword(void)
5014 if (current_function == NULL) {
5015 errorf(HERE, "'__func__' used outside of a function");
5018 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5019 expression->base.type = type_char_ptr;
5020 expression->funcname.kind = FUNCNAME_FUNCTION;
5025 static expression_t *parse_pretty_function_keyword(void)
5027 eat(T___PRETTY_FUNCTION__);
5029 if (current_function == NULL) {
5030 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5033 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5034 expression->base.type = type_char_ptr;
5035 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5040 static expression_t *parse_funcsig_keyword(void)
5044 if (current_function == NULL) {
5045 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5048 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5049 expression->base.type = type_char_ptr;
5050 expression->funcname.kind = FUNCNAME_FUNCSIG;
5055 static expression_t *parse_funcdname_keyword(void)
5057 eat(T___FUNCDNAME__);
5059 if (current_function == NULL) {
5060 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5063 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5064 expression->base.type = type_char_ptr;
5065 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5070 static designator_t *parse_designator(void)
5072 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5073 result->source_position = HERE;
5075 if(token.type != T_IDENTIFIER) {
5076 parse_error_expected("while parsing member designator",
5080 result->symbol = token.v.symbol;
5083 designator_t *last_designator = result;
5085 if(token.type == '.') {
5087 if(token.type != T_IDENTIFIER) {
5088 parse_error_expected("while parsing member designator",
5092 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5093 designator->source_position = HERE;
5094 designator->symbol = token.v.symbol;
5097 last_designator->next = designator;
5098 last_designator = designator;
5101 if(token.type == '[') {
5103 add_anchor_token(']');
5104 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5105 designator->source_position = HERE;
5106 designator->array_index = parse_expression();
5107 rem_anchor_token(']');
5109 if(designator->array_index == NULL) {
5113 last_designator->next = designator;
5114 last_designator = designator;
5126 * Parse the __builtin_offsetof() expression.
5128 static expression_t *parse_offsetof(void)
5130 eat(T___builtin_offsetof);
5132 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5133 expression->base.type = type_size_t;
5136 add_anchor_token(',');
5137 type_t *type = parse_typename();
5138 rem_anchor_token(',');
5140 add_anchor_token(')');
5141 designator_t *designator = parse_designator();
5142 rem_anchor_token(')');
5145 expression->offsetofe.type = type;
5146 expression->offsetofe.designator = designator;
5149 memset(&path, 0, sizeof(path));
5150 path.top_type = type;
5151 path.path = NEW_ARR_F(type_path_entry_t, 0);
5153 descend_into_subtype(&path);
5155 if(!walk_designator(&path, designator, true)) {
5156 return create_invalid_expression();
5159 DEL_ARR_F(path.path);
5163 return create_invalid_expression();
5167 * Parses a _builtin_va_start() expression.
5169 static expression_t *parse_va_start(void)
5171 eat(T___builtin_va_start);
5173 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5176 add_anchor_token(',');
5177 expression->va_starte.ap = parse_assignment_expression();
5178 rem_anchor_token(',');
5180 expression_t *const expr = parse_assignment_expression();
5181 if (expr->kind == EXPR_REFERENCE) {
5182 declaration_t *const decl = expr->reference.declaration;
5184 return create_invalid_expression();
5185 if (decl->parent_scope == ¤t_function->scope &&
5186 decl->next == NULL) {
5187 expression->va_starte.parameter = decl;
5192 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
5194 return create_invalid_expression();
5198 * Parses a _builtin_va_arg() expression.
5200 static expression_t *parse_va_arg(void)
5202 eat(T___builtin_va_arg);
5204 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5207 expression->va_arge.ap = parse_assignment_expression();
5209 expression->base.type = parse_typename();
5214 return create_invalid_expression();
5217 static expression_t *parse_builtin_symbol(void)
5219 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5221 symbol_t *symbol = token.v.symbol;
5223 expression->builtin_symbol.symbol = symbol;
5226 type_t *type = get_builtin_symbol_type(symbol);
5227 type = automatic_type_conversion(type);
5229 expression->base.type = type;
5234 * Parses a __builtin_constant() expression.
5236 static expression_t *parse_builtin_constant(void)
5238 eat(T___builtin_constant_p);
5240 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5243 add_anchor_token(')');
5244 expression->builtin_constant.value = parse_assignment_expression();
5245 rem_anchor_token(')');
5247 expression->base.type = type_int;
5251 return create_invalid_expression();
5255 * Parses a __builtin_prefetch() expression.
5257 static expression_t *parse_builtin_prefetch(void)
5259 eat(T___builtin_prefetch);
5261 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5264 add_anchor_token(')');
5265 expression->builtin_prefetch.adr = parse_assignment_expression();
5266 if (token.type == ',') {
5268 expression->builtin_prefetch.rw = parse_assignment_expression();
5270 if (token.type == ',') {
5272 expression->builtin_prefetch.locality = parse_assignment_expression();
5274 rem_anchor_token(')');
5276 expression->base.type = type_void;
5280 return create_invalid_expression();
5284 * Parses a __builtin_is_*() compare expression.
5286 static expression_t *parse_compare_builtin(void)
5288 expression_t *expression;
5290 switch(token.type) {
5291 case T___builtin_isgreater:
5292 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5294 case T___builtin_isgreaterequal:
5295 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5297 case T___builtin_isless:
5298 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5300 case T___builtin_islessequal:
5301 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5303 case T___builtin_islessgreater:
5304 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5306 case T___builtin_isunordered:
5307 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5310 internal_errorf(HERE, "invalid compare builtin found");
5313 expression->base.source_position = HERE;
5317 expression->binary.left = parse_assignment_expression();
5319 expression->binary.right = parse_assignment_expression();
5322 type_t *const orig_type_left = expression->binary.left->base.type;
5323 type_t *const orig_type_right = expression->binary.right->base.type;
5325 type_t *const type_left = skip_typeref(orig_type_left);
5326 type_t *const type_right = skip_typeref(orig_type_right);
5327 if(!is_type_float(type_left) && !is_type_float(type_right)) {
5328 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5329 type_error_incompatible("invalid operands in comparison",
5330 expression->base.source_position, orig_type_left, orig_type_right);
5333 semantic_comparison(&expression->binary);
5338 return create_invalid_expression();
5342 * Parses a __builtin_expect() expression.
5344 static expression_t *parse_builtin_expect(void)
5346 eat(T___builtin_expect);
5348 expression_t *expression
5349 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5352 expression->binary.left = parse_assignment_expression();
5354 expression->binary.right = parse_constant_expression();
5357 expression->base.type = expression->binary.left->base.type;
5361 return create_invalid_expression();
5365 * Parses a MS assume() expression.
5367 static expression_t *parse_assume(void) {
5370 expression_t *expression
5371 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5374 add_anchor_token(')');
5375 expression->unary.value = parse_assignment_expression();
5376 rem_anchor_token(')');
5379 expression->base.type = type_void;
5382 return create_invalid_expression();
5386 * Parse a microsoft __noop expression.
5388 static expression_t *parse_noop_expression(void) {
5389 source_position_t source_position = HERE;
5392 if (token.type == '(') {
5393 /* parse arguments */
5395 add_anchor_token(')');
5396 add_anchor_token(',');
5398 if(token.type != ')') {
5400 (void)parse_assignment_expression();
5401 if(token.type != ',')
5407 rem_anchor_token(',');
5408 rem_anchor_token(')');
5411 /* the result is a (int)0 */
5412 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5413 cnst->base.source_position = source_position;
5414 cnst->base.type = type_int;
5415 cnst->conste.v.int_value = 0;
5416 cnst->conste.is_ms_noop = true;
5421 return create_invalid_expression();
5425 * Parses a primary expression.
5427 static expression_t *parse_primary_expression(void)
5429 switch (token.type) {
5430 case T_INTEGER: return parse_int_const();
5431 case T_CHARACTER_CONSTANT: return parse_character_constant();
5432 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5433 case T_FLOATINGPOINT: return parse_float_const();
5434 case T_STRING_LITERAL:
5435 case T_WIDE_STRING_LITERAL: return parse_string_const();
5436 case T_IDENTIFIER: return parse_reference();
5437 case T___FUNCTION__:
5438 case T___func__: return parse_function_keyword();
5439 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5440 case T___FUNCSIG__: return parse_funcsig_keyword();
5441 case T___FUNCDNAME__: return parse_funcdname_keyword();
5442 case T___builtin_offsetof: return parse_offsetof();
5443 case T___builtin_va_start: return parse_va_start();
5444 case T___builtin_va_arg: return parse_va_arg();
5445 case T___builtin_expect: return parse_builtin_expect();
5446 case T___builtin_alloca:
5447 case T___builtin_nan:
5448 case T___builtin_nand:
5449 case T___builtin_nanf:
5450 case T___builtin_va_end: return parse_builtin_symbol();
5451 case T___builtin_isgreater:
5452 case T___builtin_isgreaterequal:
5453 case T___builtin_isless:
5454 case T___builtin_islessequal:
5455 case T___builtin_islessgreater:
5456 case T___builtin_isunordered: return parse_compare_builtin();
5457 case T___builtin_constant_p: return parse_builtin_constant();
5458 case T___builtin_prefetch: return parse_builtin_prefetch();
5459 case T__assume: return parse_assume();
5461 case '(': return parse_brace_expression();
5462 case T___noop: return parse_noop_expression();
5465 errorf(HERE, "unexpected token %K, expected an expression", &token);
5466 return create_invalid_expression();
5470 * Check if the expression has the character type and issue a warning then.
5472 static void check_for_char_index_type(const expression_t *expression) {
5473 type_t *const type = expression->base.type;
5474 const type_t *const base_type = skip_typeref(type);
5476 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5477 warning.char_subscripts) {
5478 warningf(expression->base.source_position,
5479 "array subscript has type '%T'", type);
5483 static expression_t *parse_array_expression(unsigned precedence,
5489 add_anchor_token(']');
5491 expression_t *inside = parse_expression();
5493 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5495 array_access_expression_t *array_access = &expression->array_access;
5497 type_t *const orig_type_left = left->base.type;
5498 type_t *const orig_type_inside = inside->base.type;
5500 type_t *const type_left = skip_typeref(orig_type_left);
5501 type_t *const type_inside = skip_typeref(orig_type_inside);
5503 type_t *return_type;
5504 if (is_type_pointer(type_left)) {
5505 return_type = type_left->pointer.points_to;
5506 array_access->array_ref = left;
5507 array_access->index = inside;
5508 check_for_char_index_type(inside);
5509 } else if (is_type_pointer(type_inside)) {
5510 return_type = type_inside->pointer.points_to;
5511 array_access->array_ref = inside;
5512 array_access->index = left;
5513 array_access->flipped = true;
5514 check_for_char_index_type(left);
5516 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5518 "array access on object with non-pointer types '%T', '%T'",
5519 orig_type_left, orig_type_inside);
5521 return_type = type_error_type;
5522 array_access->array_ref = create_invalid_expression();
5525 rem_anchor_token(']');
5526 if(token.type != ']') {
5527 parse_error_expected("Problem while parsing array access", ']', 0);
5532 return_type = automatic_type_conversion(return_type);
5533 expression->base.type = return_type;
5538 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5540 expression_t *tp_expression = allocate_expression_zero(kind);
5541 tp_expression->base.type = type_size_t;
5543 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5545 add_anchor_token(')');
5546 tp_expression->typeprop.type = parse_typename();
5547 rem_anchor_token(')');
5550 expression_t *expression = parse_sub_expression(precedence);
5551 expression->base.type = revert_automatic_type_conversion(expression);
5553 tp_expression->typeprop.type = expression->base.type;
5554 tp_expression->typeprop.tp_expression = expression;
5557 return tp_expression;
5559 return create_invalid_expression();
5562 static expression_t *parse_sizeof(unsigned precedence)
5565 return parse_typeprop(EXPR_SIZEOF, precedence);
5568 static expression_t *parse_alignof(unsigned precedence)
5571 return parse_typeprop(EXPR_SIZEOF, precedence);
5574 static expression_t *parse_select_expression(unsigned precedence,
5575 expression_t *compound)
5578 assert(token.type == '.' || token.type == T_MINUSGREATER);
5580 bool is_pointer = (token.type == T_MINUSGREATER);
5583 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5584 select->select.compound = compound;
5586 if(token.type != T_IDENTIFIER) {
5587 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5590 symbol_t *symbol = token.v.symbol;
5591 select->select.symbol = symbol;
5594 type_t *const orig_type = compound->base.type;
5595 type_t *const type = skip_typeref(orig_type);
5597 type_t *type_left = type;
5599 if (!is_type_pointer(type)) {
5600 if (is_type_valid(type)) {
5601 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5603 return create_invalid_expression();
5605 type_left = type->pointer.points_to;
5607 type_left = skip_typeref(type_left);
5609 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5610 type_left->kind != TYPE_COMPOUND_UNION) {
5611 if (is_type_valid(type_left)) {
5612 errorf(HERE, "request for member '%Y' in something not a struct or "
5613 "union, but '%T'", symbol, type_left);
5615 return create_invalid_expression();
5618 declaration_t *const declaration = type_left->compound.declaration;
5620 if(!declaration->init.is_defined) {
5621 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5623 return create_invalid_expression();
5626 declaration_t *iter = find_compound_entry(declaration, symbol);
5628 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5629 return create_invalid_expression();
5632 /* we always do the auto-type conversions; the & and sizeof parser contains
5633 * code to revert this! */
5634 type_t *expression_type = automatic_type_conversion(iter->type);
5636 select->select.compound_entry = iter;
5637 select->base.type = expression_type;
5639 if(expression_type->kind == TYPE_BITFIELD) {
5640 expression_t *extract
5641 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5642 extract->unary.value = select;
5643 extract->base.type = expression_type->bitfield.base;
5652 * Parse a call expression, ie. expression '( ... )'.
5654 * @param expression the function address
5656 static expression_t *parse_call_expression(unsigned precedence,
5657 expression_t *expression)
5660 expression_t *result = allocate_expression_zero(EXPR_CALL);
5661 result->base.source_position = expression->base.source_position;
5663 call_expression_t *call = &result->call;
5664 call->function = expression;
5666 type_t *const orig_type = expression->base.type;
5667 type_t *const type = skip_typeref(orig_type);
5669 function_type_t *function_type = NULL;
5670 if (is_type_pointer(type)) {
5671 type_t *const to_type = skip_typeref(type->pointer.points_to);
5673 if (is_type_function(to_type)) {
5674 function_type = &to_type->function;
5675 call->base.type = function_type->return_type;
5679 if (function_type == NULL && is_type_valid(type)) {
5680 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5683 /* parse arguments */
5685 add_anchor_token(')');
5686 add_anchor_token(',');
5688 if(token.type != ')') {
5689 call_argument_t *last_argument = NULL;
5692 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5694 argument->expression = parse_assignment_expression();
5695 if(last_argument == NULL) {
5696 call->arguments = argument;
5698 last_argument->next = argument;
5700 last_argument = argument;
5702 if(token.type != ',')
5707 rem_anchor_token(',');
5708 rem_anchor_token(')');
5711 if(function_type != NULL) {
5712 function_parameter_t *parameter = function_type->parameters;
5713 call_argument_t *argument = call->arguments;
5714 for( ; parameter != NULL && argument != NULL;
5715 parameter = parameter->next, argument = argument->next) {
5716 type_t *expected_type = parameter->type;
5717 /* TODO report scope in error messages */
5718 expression_t *const arg_expr = argument->expression;
5719 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call", arg_expr->base.source_position);
5720 if (res_type == NULL) {
5721 /* TODO improve error message */
5722 errorf(arg_expr->base.source_position,
5723 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5724 arg_expr, arg_expr->base.type, expected_type);
5726 argument->expression = create_implicit_cast(argument->expression, expected_type);
5729 /* too few parameters */
5730 if(parameter != NULL) {
5731 errorf(HERE, "too few arguments to function '%E'", expression);
5732 } else if(argument != NULL) {
5733 /* too many parameters */
5734 if(!function_type->variadic
5735 && !function_type->unspecified_parameters) {
5736 errorf(HERE, "too many arguments to function '%E'", expression);
5738 /* do default promotion */
5739 for( ; argument != NULL; argument = argument->next) {
5740 type_t *type = argument->expression->base.type;
5742 type = skip_typeref(type);
5743 if(is_type_integer(type)) {
5744 type = promote_integer(type);
5745 } else if(type == type_float) {
5749 argument->expression
5750 = create_implicit_cast(argument->expression, type);
5753 check_format(&result->call);
5756 check_format(&result->call);
5762 return create_invalid_expression();
5765 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5767 static bool same_compound_type(const type_t *type1, const type_t *type2)
5770 is_type_compound(type1) &&
5771 type1->kind == type2->kind &&
5772 type1->compound.declaration == type2->compound.declaration;
5776 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5778 * @param expression the conditional expression
5780 static expression_t *parse_conditional_expression(unsigned precedence,
5781 expression_t *expression)
5784 add_anchor_token(':');
5786 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5788 conditional_expression_t *conditional = &result->conditional;
5789 conditional->condition = expression;
5792 type_t *const condition_type_orig = expression->base.type;
5793 type_t *const condition_type = skip_typeref(condition_type_orig);
5794 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5795 type_error("expected a scalar type in conditional condition",
5796 expression->base.source_position, condition_type_orig);
5799 expression_t *true_expression = parse_expression();
5800 rem_anchor_token(':');
5802 expression_t *false_expression = parse_sub_expression(precedence);
5804 type_t *const orig_true_type = true_expression->base.type;
5805 type_t *const orig_false_type = false_expression->base.type;
5806 type_t *const true_type = skip_typeref(orig_true_type);
5807 type_t *const false_type = skip_typeref(orig_false_type);
5810 type_t *result_type;
5811 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5812 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5813 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5814 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5815 warningf(expression->base.source_position,
5816 "ISO C forbids conditional expression with only one void side");
5818 result_type = type_void;
5819 } else if (is_type_arithmetic(true_type)
5820 && is_type_arithmetic(false_type)) {
5821 result_type = semantic_arithmetic(true_type, false_type);
5823 true_expression = create_implicit_cast(true_expression, result_type);
5824 false_expression = create_implicit_cast(false_expression, result_type);
5826 conditional->true_expression = true_expression;
5827 conditional->false_expression = false_expression;
5828 conditional->base.type = result_type;
5829 } else if (same_compound_type(true_type, false_type)) {
5830 /* just take 1 of the 2 types */
5831 result_type = true_type;
5832 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5833 type_t *pointer_type;
5835 expression_t *other_expression;
5836 if (is_type_pointer(true_type)) {
5837 pointer_type = true_type;
5838 other_type = false_type;
5839 other_expression = false_expression;
5841 pointer_type = false_type;
5842 other_type = true_type;
5843 other_expression = true_expression;
5846 if(is_type_pointer(other_type)) {
5847 if(!pointers_compatible(true_type, false_type)) {
5848 warningf(expression->base.source_position,
5849 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5851 result_type = true_type;
5852 } else if(is_null_pointer_constant(other_expression)) {
5853 result_type = pointer_type;
5854 } else if(is_type_integer(other_type)) {
5855 warningf(expression->base.source_position,
5856 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5857 result_type = pointer_type;
5859 type_error_incompatible("while parsing conditional",
5860 expression->base.source_position, true_type, false_type);
5861 result_type = type_error_type;
5864 /* TODO: one pointer to void*, other some pointer */
5866 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5867 type_error_incompatible("while parsing conditional",
5868 expression->base.source_position, true_type,
5871 result_type = type_error_type;
5874 conditional->true_expression
5875 = create_implicit_cast(true_expression, result_type);
5876 conditional->false_expression
5877 = create_implicit_cast(false_expression, result_type);
5878 conditional->base.type = result_type;
5881 return create_invalid_expression();
5885 * Parse an extension expression.
5887 static expression_t *parse_extension(unsigned precedence)
5889 eat(T___extension__);
5891 /* TODO enable extensions */
5892 expression_t *expression = parse_sub_expression(precedence);
5893 /* TODO disable extensions */
5898 * Parse a __builtin_classify_type() expression.
5900 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5902 eat(T___builtin_classify_type);
5904 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5905 result->base.type = type_int;
5908 add_anchor_token(')');
5909 expression_t *expression = parse_sub_expression(precedence);
5910 rem_anchor_token(')');
5912 result->classify_type.type_expression = expression;
5916 return create_invalid_expression();
5919 static void semantic_incdec(unary_expression_t *expression)
5921 type_t *const orig_type = expression->value->base.type;
5922 type_t *const type = skip_typeref(orig_type);
5923 /* TODO !is_type_real && !is_type_pointer */
5924 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5925 if (is_type_valid(type)) {
5926 /* TODO: improve error message */
5927 errorf(HERE, "operation needs an arithmetic or pointer type");
5932 expression->base.type = orig_type;
5935 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5937 type_t *const orig_type = expression->value->base.type;
5938 type_t *const type = skip_typeref(orig_type);
5939 if(!is_type_arithmetic(type)) {
5940 if (is_type_valid(type)) {
5941 /* TODO: improve error message */
5942 errorf(HERE, "operation needs an arithmetic type");
5947 expression->base.type = orig_type;
5950 static void semantic_unexpr_scalar(unary_expression_t *expression)
5952 type_t *const orig_type = expression->value->base.type;
5953 type_t *const type = skip_typeref(orig_type);
5954 if (!is_type_scalar(type)) {
5955 if (is_type_valid(type)) {
5956 errorf(HERE, "operand of ! must be of scalar type");
5961 expression->base.type = orig_type;
5964 static void semantic_unexpr_integer(unary_expression_t *expression)
5966 type_t *const orig_type = expression->value->base.type;
5967 type_t *const type = skip_typeref(orig_type);
5968 if (!is_type_integer(type)) {
5969 if (is_type_valid(type)) {
5970 errorf(HERE, "operand of ~ must be of integer type");
5975 expression->base.type = orig_type;
5978 static void semantic_dereference(unary_expression_t *expression)
5980 type_t *const orig_type = expression->value->base.type;
5981 type_t *const type = skip_typeref(orig_type);
5982 if(!is_type_pointer(type)) {
5983 if (is_type_valid(type)) {
5984 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5989 type_t *result_type = type->pointer.points_to;
5990 result_type = automatic_type_conversion(result_type);
5991 expression->base.type = result_type;
5995 * Check the semantic of the address taken expression.
5997 static void semantic_take_addr(unary_expression_t *expression)
5999 expression_t *value = expression->value;
6000 value->base.type = revert_automatic_type_conversion(value);
6002 type_t *orig_type = value->base.type;
6003 if(!is_type_valid(orig_type))
6006 if(value->kind == EXPR_REFERENCE) {
6007 declaration_t *const declaration = value->reference.declaration;
6008 if(declaration != NULL) {
6009 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
6010 errorf(expression->base.source_position,
6011 "address of register variable '%Y' requested",
6012 declaration->symbol);
6014 declaration->address_taken = 1;
6018 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6021 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6022 static expression_t *parse_##unexpression_type(unsigned precedence) \
6026 expression_t *unary_expression \
6027 = allocate_expression_zero(unexpression_type); \
6028 unary_expression->base.source_position = HERE; \
6029 unary_expression->unary.value = parse_sub_expression(precedence); \
6031 sfunc(&unary_expression->unary); \
6033 return unary_expression; \
6036 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6037 semantic_unexpr_arithmetic)
6038 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6039 semantic_unexpr_arithmetic)
6040 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6041 semantic_unexpr_scalar)
6042 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6043 semantic_dereference)
6044 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6046 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6047 semantic_unexpr_integer)
6048 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6050 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6053 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6055 static expression_t *parse_##unexpression_type(unsigned precedence, \
6056 expression_t *left) \
6058 (void) precedence; \
6061 expression_t *unary_expression \
6062 = allocate_expression_zero(unexpression_type); \
6063 unary_expression->unary.value = left; \
6065 sfunc(&unary_expression->unary); \
6067 return unary_expression; \
6070 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6071 EXPR_UNARY_POSTFIX_INCREMENT,
6073 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6074 EXPR_UNARY_POSTFIX_DECREMENT,
6077 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6079 /* TODO: handle complex + imaginary types */
6081 /* § 6.3.1.8 Usual arithmetic conversions */
6082 if(type_left == type_long_double || type_right == type_long_double) {
6083 return type_long_double;
6084 } else if(type_left == type_double || type_right == type_double) {
6086 } else if(type_left == type_float || type_right == type_float) {
6090 type_right = promote_integer(type_right);
6091 type_left = promote_integer(type_left);
6093 if(type_left == type_right)
6096 bool signed_left = is_type_signed(type_left);
6097 bool signed_right = is_type_signed(type_right);
6098 int rank_left = get_rank(type_left);
6099 int rank_right = get_rank(type_right);
6100 if(rank_left < rank_right) {
6101 if(signed_left == signed_right || !signed_right) {
6107 if(signed_left == signed_right || !signed_left) {
6116 * Check the semantic restrictions for a binary expression.
6118 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6120 expression_t *const left = expression->left;
6121 expression_t *const right = expression->right;
6122 type_t *const orig_type_left = left->base.type;
6123 type_t *const orig_type_right = right->base.type;
6124 type_t *const type_left = skip_typeref(orig_type_left);
6125 type_t *const type_right = skip_typeref(orig_type_right);
6127 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6128 /* TODO: improve error message */
6129 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6130 errorf(HERE, "operation needs arithmetic types");
6135 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6136 expression->left = create_implicit_cast(left, arithmetic_type);
6137 expression->right = create_implicit_cast(right, arithmetic_type);
6138 expression->base.type = arithmetic_type;
6141 static void semantic_shift_op(binary_expression_t *expression)
6143 expression_t *const left = expression->left;
6144 expression_t *const right = expression->right;
6145 type_t *const orig_type_left = left->base.type;
6146 type_t *const orig_type_right = right->base.type;
6147 type_t * type_left = skip_typeref(orig_type_left);
6148 type_t * type_right = skip_typeref(orig_type_right);
6150 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
6151 /* TODO: improve error message */
6152 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6153 errorf(HERE, "operation needs integer types");
6158 type_left = promote_integer(type_left);
6159 type_right = promote_integer(type_right);
6161 expression->left = create_implicit_cast(left, type_left);
6162 expression->right = create_implicit_cast(right, type_right);
6163 expression->base.type = type_left;
6166 static void semantic_add(binary_expression_t *expression)
6168 expression_t *const left = expression->left;
6169 expression_t *const right = expression->right;
6170 type_t *const orig_type_left = left->base.type;
6171 type_t *const orig_type_right = right->base.type;
6172 type_t *const type_left = skip_typeref(orig_type_left);
6173 type_t *const type_right = skip_typeref(orig_type_right);
6176 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6177 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6178 expression->left = create_implicit_cast(left, arithmetic_type);
6179 expression->right = create_implicit_cast(right, arithmetic_type);
6180 expression->base.type = arithmetic_type;
6182 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6183 expression->base.type = type_left;
6184 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
6185 expression->base.type = type_right;
6186 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6187 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
6191 static void semantic_sub(binary_expression_t *expression)
6193 expression_t *const left = expression->left;
6194 expression_t *const right = expression->right;
6195 type_t *const orig_type_left = left->base.type;
6196 type_t *const orig_type_right = right->base.type;
6197 type_t *const type_left = skip_typeref(orig_type_left);
6198 type_t *const type_right = skip_typeref(orig_type_right);
6201 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6202 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6203 expression->left = create_implicit_cast(left, arithmetic_type);
6204 expression->right = create_implicit_cast(right, arithmetic_type);
6205 expression->base.type = arithmetic_type;
6207 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
6208 expression->base.type = type_left;
6209 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
6210 if(!pointers_compatible(type_left, type_right)) {
6212 "pointers to incompatible objects to binary '-' ('%T', '%T')",
6213 orig_type_left, orig_type_right);
6215 expression->base.type = type_ptrdiff_t;
6217 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6218 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
6219 orig_type_left, orig_type_right);
6224 * Check the semantics of comparison expressions.
6226 * @param expression The expression to check.
6228 static void semantic_comparison(binary_expression_t *expression)
6230 expression_t *left = expression->left;
6231 expression_t *right = expression->right;
6232 type_t *orig_type_left = left->base.type;
6233 type_t *orig_type_right = right->base.type;
6235 type_t *type_left = skip_typeref(orig_type_left);
6236 type_t *type_right = skip_typeref(orig_type_right);
6238 /* TODO non-arithmetic types */
6239 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6240 if (warning.sign_compare &&
6241 (expression->base.kind != EXPR_BINARY_EQUAL &&
6242 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6243 (is_type_signed(type_left) != is_type_signed(type_right))) {
6244 warningf(expression->base.source_position,
6245 "comparison between signed and unsigned");
6247 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6248 expression->left = create_implicit_cast(left, arithmetic_type);
6249 expression->right = create_implicit_cast(right, arithmetic_type);
6250 expression->base.type = arithmetic_type;
6251 if (warning.float_equal &&
6252 (expression->base.kind == EXPR_BINARY_EQUAL ||
6253 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6254 is_type_float(arithmetic_type)) {
6255 warningf(expression->base.source_position,
6256 "comparing floating point with == or != is unsafe");
6258 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6259 /* TODO check compatibility */
6260 } else if (is_type_pointer(type_left)) {
6261 expression->right = create_implicit_cast(right, type_left);
6262 } else if (is_type_pointer(type_right)) {
6263 expression->left = create_implicit_cast(left, type_right);
6264 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6265 type_error_incompatible("invalid operands in comparison",
6266 expression->base.source_position,
6267 type_left, type_right);
6269 expression->base.type = type_int;
6272 static void semantic_arithmetic_assign(binary_expression_t *expression)
6274 expression_t *left = expression->left;
6275 expression_t *right = expression->right;
6276 type_t *orig_type_left = left->base.type;
6277 type_t *orig_type_right = right->base.type;
6279 type_t *type_left = skip_typeref(orig_type_left);
6280 type_t *type_right = skip_typeref(orig_type_right);
6282 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6283 /* TODO: improve error message */
6284 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6285 errorf(HERE, "operation needs arithmetic types");
6290 /* combined instructions are tricky. We can't create an implicit cast on
6291 * the left side, because we need the uncasted form for the store.
6292 * The ast2firm pass has to know that left_type must be right_type
6293 * for the arithmetic operation and create a cast by itself */
6294 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6295 expression->right = create_implicit_cast(right, arithmetic_type);
6296 expression->base.type = type_left;
6299 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6301 expression_t *const left = expression->left;
6302 expression_t *const right = expression->right;
6303 type_t *const orig_type_left = left->base.type;
6304 type_t *const orig_type_right = right->base.type;
6305 type_t *const type_left = skip_typeref(orig_type_left);
6306 type_t *const type_right = skip_typeref(orig_type_right);
6308 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6309 /* combined instructions are tricky. We can't create an implicit cast on
6310 * the left side, because we need the uncasted form for the store.
6311 * The ast2firm pass has to know that left_type must be right_type
6312 * for the arithmetic operation and create a cast by itself */
6313 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6314 expression->right = create_implicit_cast(right, arithmetic_type);
6315 expression->base.type = type_left;
6316 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6317 expression->base.type = type_left;
6318 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6319 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6324 * Check the semantic restrictions of a logical expression.
6326 static void semantic_logical_op(binary_expression_t *expression)
6328 expression_t *const left = expression->left;
6329 expression_t *const right = expression->right;
6330 type_t *const orig_type_left = left->base.type;
6331 type_t *const orig_type_right = right->base.type;
6332 type_t *const type_left = skip_typeref(orig_type_left);
6333 type_t *const type_right = skip_typeref(orig_type_right);
6335 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6336 /* TODO: improve error message */
6337 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6338 errorf(HERE, "operation needs scalar types");
6343 expression->base.type = type_int;
6347 * Checks if a compound type has constant fields.
6349 static bool has_const_fields(const compound_type_t *type)
6351 const scope_t *scope = &type->declaration->scope;
6352 const declaration_t *declaration = scope->declarations;
6354 for (; declaration != NULL; declaration = declaration->next) {
6355 if (declaration->namespc != NAMESPACE_NORMAL)
6358 const type_t *decl_type = skip_typeref(declaration->type);
6359 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6367 * Check the semantic restrictions of a binary assign expression.
6369 static void semantic_binexpr_assign(binary_expression_t *expression)
6371 expression_t *left = expression->left;
6372 type_t *orig_type_left = left->base.type;
6374 type_t *type_left = revert_automatic_type_conversion(left);
6375 type_left = skip_typeref(orig_type_left);
6377 /* must be a modifiable lvalue */
6378 if (is_type_array(type_left)) {
6379 errorf(HERE, "cannot assign to arrays ('%E')", left);
6382 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6383 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6387 if(is_type_incomplete(type_left)) {
6389 "left-hand side of assignment '%E' has incomplete type '%T'",
6390 left, orig_type_left);
6393 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6394 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6395 left, orig_type_left);
6399 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
6400 "assignment", left->base.source_position);
6401 if (res_type == NULL) {
6402 errorf(expression->base.source_position,
6403 "cannot assign to '%T' from '%T'",
6404 orig_type_left, expression->right->base.type);
6406 expression->right = create_implicit_cast(expression->right, res_type);
6409 expression->base.type = orig_type_left;
6413 * Determine if the outermost operation (or parts thereof) of the given
6414 * expression has no effect in order to generate a warning about this fact.
6415 * Therefore in some cases this only examines some of the operands of the
6416 * expression (see comments in the function and examples below).
6418 * f() + 23; // warning, because + has no effect
6419 * x || f(); // no warning, because x controls execution of f()
6420 * x ? y : f(); // warning, because y has no effect
6421 * (void)x; // no warning to be able to suppress the warning
6422 * This function can NOT be used for an "expression has definitely no effect"-
6424 static bool expression_has_effect(const expression_t *const expr)
6426 switch (expr->kind) {
6427 case EXPR_UNKNOWN: break;
6428 case EXPR_INVALID: return true; /* do NOT warn */
6429 case EXPR_REFERENCE: return false;
6430 /* suppress the warning for microsoft __noop operations */
6431 case EXPR_CONST: return expr->conste.is_ms_noop;
6432 case EXPR_CHARACTER_CONSTANT: return false;
6433 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6434 case EXPR_STRING_LITERAL: return false;
6435 case EXPR_WIDE_STRING_LITERAL: return false;
6438 const call_expression_t *const call = &expr->call;
6439 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6442 switch (call->function->builtin_symbol.symbol->ID) {
6443 case T___builtin_va_end: return true;
6444 default: return false;
6448 /* Generate the warning if either the left or right hand side of a
6449 * conditional expression has no effect */
6450 case EXPR_CONDITIONAL: {
6451 const conditional_expression_t *const cond = &expr->conditional;
6453 expression_has_effect(cond->true_expression) &&
6454 expression_has_effect(cond->false_expression);
6457 case EXPR_SELECT: return false;
6458 case EXPR_ARRAY_ACCESS: return false;
6459 case EXPR_SIZEOF: return false;
6460 case EXPR_CLASSIFY_TYPE: return false;
6461 case EXPR_ALIGNOF: return false;
6463 case EXPR_FUNCNAME: return false;
6464 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6465 case EXPR_BUILTIN_CONSTANT_P: return false;
6466 case EXPR_BUILTIN_PREFETCH: return true;
6467 case EXPR_OFFSETOF: return false;
6468 case EXPR_VA_START: return true;
6469 case EXPR_VA_ARG: return true;
6470 case EXPR_STATEMENT: return true; // TODO
6471 case EXPR_COMPOUND_LITERAL: return false;
6473 case EXPR_UNARY_NEGATE: return false;
6474 case EXPR_UNARY_PLUS: return false;
6475 case EXPR_UNARY_BITWISE_NEGATE: return false;
6476 case EXPR_UNARY_NOT: return false;
6477 case EXPR_UNARY_DEREFERENCE: return false;
6478 case EXPR_UNARY_TAKE_ADDRESS: return false;
6479 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6480 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6481 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6482 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6484 /* Treat void casts as if they have an effect in order to being able to
6485 * suppress the warning */
6486 case EXPR_UNARY_CAST: {
6487 type_t *const type = skip_typeref(expr->base.type);
6488 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6491 case EXPR_UNARY_CAST_IMPLICIT: return true;
6492 case EXPR_UNARY_ASSUME: return true;
6493 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6495 case EXPR_BINARY_ADD: return false;
6496 case EXPR_BINARY_SUB: return false;
6497 case EXPR_BINARY_MUL: return false;
6498 case EXPR_BINARY_DIV: return false;
6499 case EXPR_BINARY_MOD: return false;
6500 case EXPR_BINARY_EQUAL: return false;
6501 case EXPR_BINARY_NOTEQUAL: return false;
6502 case EXPR_BINARY_LESS: return false;
6503 case EXPR_BINARY_LESSEQUAL: return false;
6504 case EXPR_BINARY_GREATER: return false;
6505 case EXPR_BINARY_GREATEREQUAL: return false;
6506 case EXPR_BINARY_BITWISE_AND: return false;
6507 case EXPR_BINARY_BITWISE_OR: return false;
6508 case EXPR_BINARY_BITWISE_XOR: return false;
6509 case EXPR_BINARY_SHIFTLEFT: return false;
6510 case EXPR_BINARY_SHIFTRIGHT: return false;
6511 case EXPR_BINARY_ASSIGN: return true;
6512 case EXPR_BINARY_MUL_ASSIGN: return true;
6513 case EXPR_BINARY_DIV_ASSIGN: return true;
6514 case EXPR_BINARY_MOD_ASSIGN: return true;
6515 case EXPR_BINARY_ADD_ASSIGN: return true;
6516 case EXPR_BINARY_SUB_ASSIGN: return true;
6517 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6518 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6519 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6520 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6521 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6523 /* Only examine the right hand side of && and ||, because the left hand
6524 * side already has the effect of controlling the execution of the right
6526 case EXPR_BINARY_LOGICAL_AND:
6527 case EXPR_BINARY_LOGICAL_OR:
6528 /* Only examine the right hand side of a comma expression, because the left
6529 * hand side has a separate warning */
6530 case EXPR_BINARY_COMMA:
6531 return expression_has_effect(expr->binary.right);
6533 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6534 case EXPR_BINARY_ISGREATER: return false;
6535 case EXPR_BINARY_ISGREATEREQUAL: return false;
6536 case EXPR_BINARY_ISLESS: return false;
6537 case EXPR_BINARY_ISLESSEQUAL: return false;
6538 case EXPR_BINARY_ISLESSGREATER: return false;
6539 case EXPR_BINARY_ISUNORDERED: return false;
6542 internal_errorf(HERE, "unexpected expression");
6545 static void semantic_comma(binary_expression_t *expression)
6547 if (warning.unused_value) {
6548 const expression_t *const left = expression->left;
6549 if (!expression_has_effect(left)) {
6550 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6553 expression->base.type = expression->right->base.type;
6556 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6557 static expression_t *parse_##binexpression_type(unsigned precedence, \
6558 expression_t *left) \
6561 source_position_t pos = HERE; \
6563 expression_t *right = parse_sub_expression(precedence + lr); \
6565 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6566 binexpr->base.source_position = pos; \
6567 binexpr->binary.left = left; \
6568 binexpr->binary.right = right; \
6569 sfunc(&binexpr->binary); \
6574 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6575 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6576 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6577 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6578 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6579 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6580 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6581 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6582 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6584 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6585 semantic_comparison, 1)
6586 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6587 semantic_comparison, 1)
6588 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6589 semantic_comparison, 1)
6590 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6591 semantic_comparison, 1)
6593 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6594 semantic_binexpr_arithmetic, 1)
6595 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6596 semantic_binexpr_arithmetic, 1)
6597 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6598 semantic_binexpr_arithmetic, 1)
6599 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6600 semantic_logical_op, 1)
6601 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6602 semantic_logical_op, 1)
6603 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6604 semantic_shift_op, 1)
6605 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6606 semantic_shift_op, 1)
6607 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6608 semantic_arithmetic_addsubb_assign, 0)
6609 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6610 semantic_arithmetic_addsubb_assign, 0)
6611 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6612 semantic_arithmetic_assign, 0)
6613 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6614 semantic_arithmetic_assign, 0)
6615 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6616 semantic_arithmetic_assign, 0)
6617 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6618 semantic_arithmetic_assign, 0)
6619 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6620 semantic_arithmetic_assign, 0)
6621 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6622 semantic_arithmetic_assign, 0)
6623 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6624 semantic_arithmetic_assign, 0)
6625 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6626 semantic_arithmetic_assign, 0)
6628 static expression_t *parse_sub_expression(unsigned precedence)
6630 if(token.type < 0) {
6631 return expected_expression_error();
6634 expression_parser_function_t *parser
6635 = &expression_parsers[token.type];
6636 source_position_t source_position = token.source_position;
6639 if(parser->parser != NULL) {
6640 left = parser->parser(parser->precedence);
6642 left = parse_primary_expression();
6644 assert(left != NULL);
6645 left->base.source_position = source_position;
6648 if(token.type < 0) {
6649 return expected_expression_error();
6652 parser = &expression_parsers[token.type];
6653 if(parser->infix_parser == NULL)
6655 if(parser->infix_precedence < precedence)
6658 left = parser->infix_parser(parser->infix_precedence, left);
6660 assert(left != NULL);
6661 assert(left->kind != EXPR_UNKNOWN);
6662 left->base.source_position = source_position;
6669 * Parse an expression.
6671 static expression_t *parse_expression(void)
6673 return parse_sub_expression(1);
6677 * Register a parser for a prefix-like operator with given precedence.
6679 * @param parser the parser function
6680 * @param token_type the token type of the prefix token
6681 * @param precedence the precedence of the operator
6683 static void register_expression_parser(parse_expression_function parser,
6684 int token_type, unsigned precedence)
6686 expression_parser_function_t *entry = &expression_parsers[token_type];
6688 if(entry->parser != NULL) {
6689 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6690 panic("trying to register multiple expression parsers for a token");
6692 entry->parser = parser;
6693 entry->precedence = precedence;
6697 * Register a parser for an infix operator with given precedence.
6699 * @param parser the parser function
6700 * @param token_type the token type of the infix operator
6701 * @param precedence the precedence of the operator
6703 static void register_infix_parser(parse_expression_infix_function parser,
6704 int token_type, unsigned precedence)
6706 expression_parser_function_t *entry = &expression_parsers[token_type];
6708 if(entry->infix_parser != NULL) {
6709 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6710 panic("trying to register multiple infix expression parsers for a "
6713 entry->infix_parser = parser;
6714 entry->infix_precedence = precedence;
6718 * Initialize the expression parsers.
6720 static void init_expression_parsers(void)
6722 memset(&expression_parsers, 0, sizeof(expression_parsers));
6724 register_infix_parser(parse_array_expression, '[', 30);
6725 register_infix_parser(parse_call_expression, '(', 30);
6726 register_infix_parser(parse_select_expression, '.', 30);
6727 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6728 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6730 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6733 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6734 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6735 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6736 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6737 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6738 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6739 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6740 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6741 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6742 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6743 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6744 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6745 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6746 T_EXCLAMATIONMARKEQUAL, 13);
6747 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6748 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6749 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6750 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6751 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6752 register_infix_parser(parse_conditional_expression, '?', 7);
6753 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6754 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6755 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6756 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6757 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6758 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6759 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6760 T_LESSLESSEQUAL, 2);
6761 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6762 T_GREATERGREATEREQUAL, 2);
6763 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6765 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6767 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6770 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6772 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6773 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6774 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6775 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6776 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6777 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6778 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6780 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6782 register_expression_parser(parse_sizeof, T_sizeof, 25);
6783 register_expression_parser(parse_alignof, T___alignof__, 25);
6784 register_expression_parser(parse_extension, T___extension__, 25);
6785 register_expression_parser(parse_builtin_classify_type,
6786 T___builtin_classify_type, 25);
6790 * Parse a asm statement constraints specification.
6792 static asm_constraint_t *parse_asm_constraints(void)
6794 asm_constraint_t *result = NULL;
6795 asm_constraint_t *last = NULL;
6797 while(token.type == T_STRING_LITERAL || token.type == '[') {
6798 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6799 memset(constraint, 0, sizeof(constraint[0]));
6801 if(token.type == '[') {
6803 if(token.type != T_IDENTIFIER) {
6804 parse_error_expected("while parsing asm constraint",
6808 constraint->symbol = token.v.symbol;
6813 constraint->constraints = parse_string_literals();
6815 constraint->expression = parse_expression();
6819 last->next = constraint;
6821 result = constraint;
6825 if(token.type != ',')
6836 * Parse a asm statement clobber specification.
6838 static asm_clobber_t *parse_asm_clobbers(void)
6840 asm_clobber_t *result = NULL;
6841 asm_clobber_t *last = NULL;
6843 while(token.type == T_STRING_LITERAL) {
6844 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6845 clobber->clobber = parse_string_literals();
6848 last->next = clobber;
6854 if(token.type != ',')
6863 * Parse an asm statement.
6865 static statement_t *parse_asm_statement(void)
6869 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6870 statement->base.source_position = token.source_position;
6872 asm_statement_t *asm_statement = &statement->asms;
6874 if(token.type == T_volatile) {
6876 asm_statement->is_volatile = true;
6880 add_anchor_token(')');
6881 add_anchor_token(':');
6882 asm_statement->asm_text = parse_string_literals();
6884 if(token.type != ':') {
6885 rem_anchor_token(':');
6890 asm_statement->inputs = parse_asm_constraints();
6891 if(token.type != ':') {
6892 rem_anchor_token(':');
6897 asm_statement->outputs = parse_asm_constraints();
6898 if(token.type != ':') {
6899 rem_anchor_token(':');
6902 rem_anchor_token(':');
6905 asm_statement->clobbers = parse_asm_clobbers();
6908 rem_anchor_token(')');
6913 return create_invalid_statement();
6917 * Parse a case statement.
6919 static statement_t *parse_case_statement(void)
6923 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6925 statement->base.source_position = token.source_position;
6926 statement->case_label.expression = parse_expression();
6928 if (c_mode & _GNUC) {
6929 if (token.type == T_DOTDOTDOT) {
6931 statement->case_label.end_range = parse_expression();
6937 if (! is_constant_expression(statement->case_label.expression)) {
6938 errorf(statement->base.source_position,
6939 "case label does not reduce to an integer constant");
6941 /* TODO: check if the case label is already known */
6942 if (current_switch != NULL) {
6943 /* link all cases into the switch statement */
6944 if (current_switch->last_case == NULL) {
6945 current_switch->first_case =
6946 current_switch->last_case = &statement->case_label;
6948 current_switch->last_case->next = &statement->case_label;
6951 errorf(statement->base.source_position,
6952 "case label not within a switch statement");
6955 statement->case_label.statement = parse_statement();
6959 return create_invalid_statement();
6963 * Finds an existing default label of a switch statement.
6965 static case_label_statement_t *
6966 find_default_label(const switch_statement_t *statement)
6968 case_label_statement_t *label = statement->first_case;
6969 for ( ; label != NULL; label = label->next) {
6970 if (label->expression == NULL)
6977 * Parse a default statement.
6979 static statement_t *parse_default_statement(void)
6983 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6985 statement->base.source_position = token.source_position;
6988 if (current_switch != NULL) {
6989 const case_label_statement_t *def_label = find_default_label(current_switch);
6990 if (def_label != NULL) {
6991 errorf(HERE, "multiple default labels in one switch");
6992 errorf(def_label->base.source_position,
6993 "this is the first default label");
6995 /* link all cases into the switch statement */
6996 if (current_switch->last_case == NULL) {
6997 current_switch->first_case =
6998 current_switch->last_case = &statement->case_label;
7000 current_switch->last_case->next = &statement->case_label;
7004 errorf(statement->base.source_position,
7005 "'default' label not within a switch statement");
7007 statement->case_label.statement = parse_statement();
7011 return create_invalid_statement();
7015 * Return the declaration for a given label symbol or create a new one.
7017 static declaration_t *get_label(symbol_t *symbol)
7019 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7020 assert(current_function != NULL);
7021 /* if we found a label in the same function, then we already created the
7023 if(candidate != NULL
7024 && candidate->parent_scope == ¤t_function->scope) {
7028 /* otherwise we need to create a new one */
7029 declaration_t *const declaration = allocate_declaration_zero();
7030 declaration->namespc = NAMESPACE_LABEL;
7031 declaration->symbol = symbol;
7033 label_push(declaration);
7039 * Parse a label statement.
7041 static statement_t *parse_label_statement(void)
7043 assert(token.type == T_IDENTIFIER);
7044 symbol_t *symbol = token.v.symbol;
7047 declaration_t *label = get_label(symbol);
7049 /* if source position is already set then the label is defined twice,
7050 * otherwise it was just mentioned in a goto so far */
7051 if(label->source_position.input_name != NULL) {
7052 errorf(HERE, "duplicate label '%Y' (declared %P)",
7053 symbol, label->source_position);
7055 label->source_position = token.source_position;
7058 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7060 statement->base.source_position = token.source_position;
7061 statement->label.label = label;
7065 if(token.type == '}') {
7066 /* TODO only warn? */
7068 warningf(HERE, "label at end of compound statement");
7069 statement->label.statement = create_empty_statement();
7071 errorf(HERE, "label at end of compound statement");
7072 statement->label.statement = create_invalid_statement();
7076 if (token.type == ';') {
7077 /* eat an empty statement here, to avoid the warning about an empty
7078 * after a label. label:; is commonly used to have a label before
7080 statement->label.statement = create_empty_statement();
7083 statement->label.statement = parse_statement();
7087 /* remember the labels's in a list for later checking */
7088 if (label_last == NULL) {
7089 label_first = &statement->label;
7091 label_last->next = &statement->label;
7093 label_last = &statement->label;
7099 * Parse an if statement.
7101 static statement_t *parse_if(void)
7105 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7106 statement->base.source_position = token.source_position;
7109 add_anchor_token(')');
7110 statement->ifs.condition = parse_expression();
7111 rem_anchor_token(')');
7114 add_anchor_token(T_else);
7115 statement->ifs.true_statement = parse_statement();
7116 rem_anchor_token(T_else);
7118 if(token.type == T_else) {
7120 statement->ifs.false_statement = parse_statement();
7125 return create_invalid_statement();
7129 * Parse a switch statement.
7131 static statement_t *parse_switch(void)
7135 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7136 statement->base.source_position = token.source_position;
7139 expression_t *const expr = parse_expression();
7140 type_t * type = skip_typeref(expr->base.type);
7141 if (is_type_integer(type)) {
7142 type = promote_integer(type);
7143 } else if (is_type_valid(type)) {
7144 errorf(expr->base.source_position,
7145 "switch quantity is not an integer, but '%T'", type);
7146 type = type_error_type;
7148 statement->switchs.expression = create_implicit_cast(expr, type);
7151 switch_statement_t *rem = current_switch;
7152 current_switch = &statement->switchs;
7153 statement->switchs.body = parse_statement();
7154 current_switch = rem;
7156 if (warning.switch_default
7157 && find_default_label(&statement->switchs) == NULL) {
7158 warningf(statement->base.source_position, "switch has no default case");
7163 return create_invalid_statement();
7166 static statement_t *parse_loop_body(statement_t *const loop)
7168 statement_t *const rem = current_loop;
7169 current_loop = loop;
7171 statement_t *const body = parse_statement();
7178 * Parse a while statement.
7180 static statement_t *parse_while(void)
7184 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7185 statement->base.source_position = token.source_position;
7188 add_anchor_token(')');
7189 statement->whiles.condition = parse_expression();
7190 rem_anchor_token(')');
7193 statement->whiles.body = parse_loop_body(statement);
7197 return create_invalid_statement();
7201 * Parse a do statement.
7203 static statement_t *parse_do(void)
7207 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7209 statement->base.source_position = token.source_position;
7211 add_anchor_token(T_while);
7212 statement->do_while.body = parse_loop_body(statement);
7213 rem_anchor_token(T_while);
7217 add_anchor_token(')');
7218 statement->do_while.condition = parse_expression();
7219 rem_anchor_token(')');
7225 return create_invalid_statement();
7229 * Parse a for statement.
7231 static statement_t *parse_for(void)
7235 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7236 statement->base.source_position = token.source_position;
7238 int top = environment_top();
7239 scope_t *last_scope = scope;
7240 set_scope(&statement->fors.scope);
7243 add_anchor_token(')');
7245 if(token.type != ';') {
7246 if(is_declaration_specifier(&token, false)) {
7247 parse_declaration(record_declaration);
7249 expression_t *const init = parse_expression();
7250 statement->fors.initialisation = init;
7251 if (warning.unused_value && !expression_has_effect(init)) {
7252 warningf(init->base.source_position,
7253 "initialisation of 'for'-statement has no effect");
7261 if(token.type != ';') {
7262 statement->fors.condition = parse_expression();
7265 if(token.type != ')') {
7266 expression_t *const step = parse_expression();
7267 statement->fors.step = step;
7268 if (warning.unused_value && !expression_has_effect(step)) {
7269 warningf(step->base.source_position,
7270 "step of 'for'-statement has no effect");
7273 rem_anchor_token(')');
7275 statement->fors.body = parse_loop_body(statement);
7277 assert(scope == &statement->fors.scope);
7278 set_scope(last_scope);
7279 environment_pop_to(top);
7284 rem_anchor_token(')');
7285 assert(scope == &statement->fors.scope);
7286 set_scope(last_scope);
7287 environment_pop_to(top);
7289 return create_invalid_statement();
7293 * Parse a goto statement.
7295 static statement_t *parse_goto(void)
7299 if(token.type != T_IDENTIFIER) {
7300 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
7304 symbol_t *symbol = token.v.symbol;
7307 declaration_t *label = get_label(symbol);
7309 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7310 statement->base.source_position = token.source_position;
7312 statement->gotos.label = label;
7314 /* remember the goto's in a list for later checking */
7315 if (goto_last == NULL) {
7316 goto_first = &statement->gotos;
7318 goto_last->next = &statement->gotos;
7320 goto_last = &statement->gotos;
7326 return create_invalid_statement();
7330 * Parse a continue statement.
7332 static statement_t *parse_continue(void)
7334 statement_t *statement;
7335 if (current_loop == NULL) {
7336 errorf(HERE, "continue statement not within loop");
7339 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7341 statement->base.source_position = token.source_position;
7349 return create_invalid_statement();
7353 * Parse a break statement.
7355 static statement_t *parse_break(void)
7357 statement_t *statement;
7358 if (current_switch == NULL && current_loop == NULL) {
7359 errorf(HERE, "break statement not within loop or switch");
7362 statement = allocate_statement_zero(STATEMENT_BREAK);
7364 statement->base.source_position = token.source_position;
7372 return create_invalid_statement();
7376 * Check if a given declaration represents a local variable.
7378 static bool is_local_var_declaration(const declaration_t *declaration) {
7379 switch ((storage_class_tag_t) declaration->storage_class) {
7380 case STORAGE_CLASS_AUTO:
7381 case STORAGE_CLASS_REGISTER: {
7382 const type_t *type = skip_typeref(declaration->type);
7383 if(is_type_function(type)) {
7395 * Check if a given declaration represents a variable.
7397 static bool is_var_declaration(const declaration_t *declaration) {
7398 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7401 const type_t *type = skip_typeref(declaration->type);
7402 return !is_type_function(type);
7406 * Check if a given expression represents a local variable.
7408 static bool is_local_variable(const expression_t *expression)
7410 if (expression->base.kind != EXPR_REFERENCE) {
7413 const declaration_t *declaration = expression->reference.declaration;
7414 return is_local_var_declaration(declaration);
7418 * Check if a given expression represents a local variable and
7419 * return its declaration then, else return NULL.
7421 declaration_t *expr_is_variable(const expression_t *expression)
7423 if (expression->base.kind != EXPR_REFERENCE) {
7426 declaration_t *declaration = expression->reference.declaration;
7427 if (is_var_declaration(declaration))
7433 * Parse a return statement.
7435 static statement_t *parse_return(void)
7437 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7438 statement->base.source_position = token.source_position;
7442 expression_t *return_value = NULL;
7443 if(token.type != ';') {
7444 return_value = parse_expression();
7448 const type_t *const func_type = current_function->type;
7449 assert(is_type_function(func_type));
7450 type_t *const return_type = skip_typeref(func_type->function.return_type);
7452 if(return_value != NULL) {
7453 type_t *return_value_type = skip_typeref(return_value->base.type);
7455 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7456 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7457 warningf(statement->base.source_position,
7458 "'return' with a value, in function returning void");
7459 return_value = NULL;
7461 type_t *const res_type = semantic_assign(return_type,
7462 return_value, "'return'", statement->base.source_position);
7463 if (res_type == NULL) {
7464 errorf(statement->base.source_position,
7465 "cannot return something of type '%T' in function returning '%T'",
7466 return_value->base.type, return_type);
7468 return_value = create_implicit_cast(return_value, res_type);
7471 /* check for returning address of a local var */
7472 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7473 const expression_t *expression = return_value->unary.value;
7474 if (is_local_variable(expression)) {
7475 warningf(statement->base.source_position,
7476 "function returns address of local variable");
7480 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7481 warningf(statement->base.source_position,
7482 "'return' without value, in function returning non-void");
7485 statement->returns.value = return_value;
7489 return create_invalid_statement();
7493 * Parse a declaration statement.
7495 static statement_t *parse_declaration_statement(void)
7497 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7499 statement->base.source_position = token.source_position;
7501 declaration_t *before = last_declaration;
7502 parse_declaration(record_declaration);
7504 if(before == NULL) {
7505 statement->declaration.declarations_begin = scope->declarations;
7507 statement->declaration.declarations_begin = before->next;
7509 statement->declaration.declarations_end = last_declaration;
7515 * Parse an expression statement, ie. expr ';'.
7517 static statement_t *parse_expression_statement(void)
7519 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7521 statement->base.source_position = token.source_position;
7522 expression_t *const expr = parse_expression();
7523 statement->expression.expression = expr;
7525 if (warning.unused_value && !expression_has_effect(expr)) {
7526 warningf(expr->base.source_position, "statement has no effect");
7533 return create_invalid_statement();
7537 * Parse a statement.
7539 static statement_t *parse_statement(void)
7541 statement_t *statement = NULL;
7543 /* declaration or statement */
7544 add_anchor_token(';');
7545 switch(token.type) {
7547 statement = parse_asm_statement();
7551 statement = parse_case_statement();
7555 statement = parse_default_statement();
7559 statement = parse_compound_statement();
7563 statement = parse_if();
7567 statement = parse_switch();
7571 statement = parse_while();
7575 statement = parse_do();
7579 statement = parse_for();
7583 statement = parse_goto();
7587 statement = parse_continue();
7591 statement = parse_break();
7595 statement = parse_return();
7599 if(warning.empty_statement) {
7600 warningf(HERE, "statement is empty");
7602 statement = create_empty_statement();
7607 if(look_ahead(1)->type == ':') {
7608 statement = parse_label_statement();
7612 if(is_typedef_symbol(token.v.symbol)) {
7613 statement = parse_declaration_statement();
7617 statement = parse_expression_statement();
7620 case T___extension__:
7621 /* this can be a prefix to a declaration or an expression statement */
7622 /* we simply eat it now and parse the rest with tail recursion */
7625 } while(token.type == T___extension__);
7626 statement = parse_statement();
7630 statement = parse_declaration_statement();
7634 statement = parse_expression_statement();
7637 rem_anchor_token(';');
7639 assert(statement != NULL
7640 && statement->base.source_position.input_name != NULL);
7646 * Parse a compound statement.
7648 static statement_t *parse_compound_statement(void)
7650 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7652 statement->base.source_position = token.source_position;
7655 add_anchor_token('}');
7657 int top = environment_top();
7658 scope_t *last_scope = scope;
7659 set_scope(&statement->compound.scope);
7661 statement_t *last_statement = NULL;
7663 while(token.type != '}' && token.type != T_EOF) {
7664 statement_t *sub_statement = parse_statement();
7665 if(is_invalid_statement(sub_statement)) {
7666 /* an error occurred. if we are at an anchor, return */
7672 if(last_statement != NULL) {
7673 last_statement->base.next = sub_statement;
7675 statement->compound.statements = sub_statement;
7678 while(sub_statement->base.next != NULL)
7679 sub_statement = sub_statement->base.next;
7681 last_statement = sub_statement;
7684 if(token.type == '}') {
7687 errorf(statement->base.source_position,
7688 "end of file while looking for closing '}'");
7692 rem_anchor_token('}');
7693 assert(scope == &statement->compound.scope);
7694 set_scope(last_scope);
7695 environment_pop_to(top);
7701 * Initialize builtin types.
7703 static void initialize_builtin_types(void)
7705 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7706 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7707 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7708 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7709 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7710 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7711 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7712 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7714 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7715 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7716 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7717 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7721 * Check for unused global static functions and variables
7723 static void check_unused_globals(void)
7725 if (!warning.unused_function && !warning.unused_variable)
7728 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7729 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7732 type_t *const type = decl->type;
7734 if (is_type_function(skip_typeref(type))) {
7735 if (!warning.unused_function || decl->is_inline)
7738 s = (decl->init.statement != NULL ? "defined" : "declared");
7740 if (!warning.unused_variable)
7746 warningf(decl->source_position, "'%#T' %s but not used",
7747 type, decl->symbol, s);
7752 * Parse a translation unit.
7754 static translation_unit_t *parse_translation_unit(void)
7756 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7758 assert(global_scope == NULL);
7759 global_scope = &unit->scope;
7761 assert(scope == NULL);
7762 set_scope(&unit->scope);
7764 initialize_builtin_types();
7766 while(token.type != T_EOF) {
7767 if (token.type == ';') {
7768 /* TODO error in strict mode */
7769 warningf(HERE, "stray ';' outside of function");
7772 parse_external_declaration();
7776 assert(scope == &unit->scope);
7778 last_declaration = NULL;
7780 assert(global_scope == &unit->scope);
7781 check_unused_globals();
7782 global_scope = NULL;
7790 * @return the translation unit or NULL if errors occurred.
7792 translation_unit_t *parse(void)
7794 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7795 label_stack = NEW_ARR_F(stack_entry_t, 0);
7796 diagnostic_count = 0;
7800 type_set_output(stderr);
7801 ast_set_output(stderr);
7803 lookahead_bufpos = 0;
7804 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7807 translation_unit_t *unit = parse_translation_unit();
7809 DEL_ARR_F(environment_stack);
7810 DEL_ARR_F(label_stack);
7816 * Initialize the parser.
7818 void init_parser(void)
7821 /* add predefined symbols for extended-decl-modifier */
7822 sym_align = symbol_table_insert("align");
7823 sym_allocate = symbol_table_insert("allocate");
7824 sym_dllimport = symbol_table_insert("dllimport");
7825 sym_dllexport = symbol_table_insert("dllexport");
7826 sym_naked = symbol_table_insert("naked");
7827 sym_noinline = symbol_table_insert("noinline");
7828 sym_noreturn = symbol_table_insert("noreturn");
7829 sym_nothrow = symbol_table_insert("nothrow");
7830 sym_novtable = symbol_table_insert("novtable");
7831 sym_property = symbol_table_insert("property");
7832 sym_get = symbol_table_insert("get");
7833 sym_put = symbol_table_insert("put");
7834 sym_selectany = symbol_table_insert("selectany");
7835 sym_thread = symbol_table_insert("thread");
7836 sym_uuid = symbol_table_insert("uuid");
7837 sym_deprecated = symbol_table_insert("deprecated");
7838 sym_restrict = symbol_table_insert("restrict");
7839 sym_noalias = symbol_table_insert("noalias");
7841 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7843 init_expression_parsers();
7844 obstack_init(&temp_obst);
7846 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7847 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7851 * Terminate the parser.
7853 void exit_parser(void)
7855 obstack_free(&temp_obst, NULL);