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 * Allocate a statement node of given kind and initialize all
244 static statement_t *allocate_statement_zero(statement_kind_t kind)
246 size_t size = get_statement_struct_size(kind);
247 statement_t *res = allocate_ast_zero(size);
249 res->base.kind = kind;
254 * Creates a new invalid statement.
256 static statement_t *create_invalid_statement(void)
258 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
259 statement->base.source_position = token.source_position;
264 * Allocate a new empty statement.
266 static statement_t *create_empty_statement(void)
268 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
269 statement->base.source_position = token.source_position;
274 * Returns the size of an expression node.
276 * @param kind the expression kind
278 static size_t get_expression_struct_size(expression_kind_t kind)
280 static const size_t sizes[] = {
281 [EXPR_INVALID] = sizeof(expression_base_t),
282 [EXPR_REFERENCE] = sizeof(reference_expression_t),
283 [EXPR_CONST] = sizeof(const_expression_t),
284 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
285 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
286 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
287 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
288 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
289 [EXPR_CALL] = sizeof(call_expression_t),
290 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
291 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
292 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
293 [EXPR_SELECT] = sizeof(select_expression_t),
294 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
295 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
296 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
297 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
298 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
299 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
300 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
301 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
302 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
303 [EXPR_VA_START] = sizeof(va_start_expression_t),
304 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
305 [EXPR_STATEMENT] = sizeof(statement_expression_t),
307 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
308 return sizes[EXPR_UNARY_FIRST];
310 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
311 return sizes[EXPR_BINARY_FIRST];
313 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
314 assert(sizes[kind] != 0);
319 * Allocate an expression node of given kind and initialize all
322 static expression_t *allocate_expression_zero(expression_kind_t kind)
324 size_t size = get_expression_struct_size(kind);
325 expression_t *res = allocate_ast_zero(size);
327 res->base.kind = kind;
328 res->base.type = type_error_type;
333 * Returns the size of a type node.
335 * @param kind the type kind
337 static size_t get_type_struct_size(type_kind_t kind)
339 static const size_t sizes[] = {
340 [TYPE_ATOMIC] = sizeof(atomic_type_t),
341 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
342 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
343 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
344 [TYPE_ENUM] = sizeof(enum_type_t),
345 [TYPE_FUNCTION] = sizeof(function_type_t),
346 [TYPE_POINTER] = sizeof(pointer_type_t),
347 [TYPE_ARRAY] = sizeof(array_type_t),
348 [TYPE_BUILTIN] = sizeof(builtin_type_t),
349 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
350 [TYPE_TYPEOF] = sizeof(typeof_type_t),
352 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
353 assert(kind <= TYPE_TYPEOF);
354 assert(sizes[kind] != 0);
359 * Allocate a type node of given kind and initialize all
362 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
364 size_t size = get_type_struct_size(kind);
365 type_t *res = obstack_alloc(type_obst, size);
366 memset(res, 0, size);
368 res->base.kind = kind;
369 res->base.source_position = source_position;
374 * Returns the size of an initializer node.
376 * @param kind the initializer kind
378 static size_t get_initializer_size(initializer_kind_t kind)
380 static const size_t sizes[] = {
381 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
382 [INITIALIZER_STRING] = sizeof(initializer_string_t),
383 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
384 [INITIALIZER_LIST] = sizeof(initializer_list_t),
385 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
387 assert(kind < sizeof(sizes) / sizeof(*sizes));
388 assert(sizes[kind] != 0);
393 * Allocate an initializer node of given kind and initialize all
396 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
398 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
405 * Free a type from the type obstack.
407 static void free_type(void *type)
409 obstack_free(type_obst, type);
413 * Returns the index of the top element of the environment stack.
415 static size_t environment_top(void)
417 return ARR_LEN(environment_stack);
421 * Returns the index of the top element of the label stack.
423 static size_t label_top(void)
425 return ARR_LEN(label_stack);
429 * Return the next token.
431 static inline void next_token(void)
433 token = lookahead_buffer[lookahead_bufpos];
434 lookahead_buffer[lookahead_bufpos] = lexer_token;
437 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
440 print_token(stderr, &token);
441 fprintf(stderr, "\n");
446 * Return the next token with a given lookahead.
448 static inline const token_t *look_ahead(int num)
450 assert(num > 0 && num <= MAX_LOOKAHEAD);
451 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
452 return &lookahead_buffer[pos];
456 * Adds a token to the token anchor set (a multi-set).
458 static void add_anchor_token(int token_type) {
459 assert(0 <= token_type && token_type < T_LAST_TOKEN);
460 ++token_anchor_set[token_type];
464 * Remove a token from the token anchor set (a multi-set).
466 static void rem_anchor_token(int token_type) {
467 assert(0 <= token_type && token_type < T_LAST_TOKEN);
468 --token_anchor_set[token_type];
471 static bool at_anchor(void) {
474 return token_anchor_set[token.type];
478 * Eat tokens until a matching token is found.
480 static void eat_until_matching_token(int type) {
481 unsigned parenthesis_count = 0;
482 unsigned brace_count = 0;
483 unsigned bracket_count = 0;
484 int end_token = type;
493 while(token.type != end_token ||
494 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
498 case '(': ++parenthesis_count; break;
499 case '{': ++brace_count; break;
500 case '[': ++bracket_count; break;
502 if(parenthesis_count > 0)
510 if(bracket_count > 0)
521 * Eat input tokens until an anchor is found.
523 static void eat_until_anchor(void) {
524 if(token.type == T_EOF)
526 while(token_anchor_set[token.type] == 0) {
527 if(token.type == '(' || token.type == '{' || token.type == '[')
528 eat_until_matching_token(token.type);
529 if(token.type == T_EOF)
535 static void eat_block(void) {
536 eat_until_matching_token('{');
537 if(token.type == '}')
542 * eat all token until a ';' is reached
543 * or a stop token is found.
545 static void eat_statement(void) {
546 eat_until_matching_token(';');
547 if(token.type == ';')
551 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
554 * Report a parse error because an expected token was not found.
556 static void parse_error_expected(const char *message, ...)
558 if(message != NULL) {
559 errorf(HERE, "%s", message);
562 va_start(ap, message);
563 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
568 * Report a type error.
570 static void type_error(const char *msg, const source_position_t source_position,
573 errorf(source_position, "%s, but found type '%T'", msg, type);
577 * Report an incompatible type.
579 static void type_error_incompatible(const char *msg,
580 const source_position_t source_position, type_t *type1, type_t *type2)
582 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
586 * Expect the the current token is the expected token.
587 * If not, generate an error, eat the current statement,
588 * and goto the end_error label.
590 #define expect(expected) \
592 if(UNLIKELY(token.type != (expected))) { \
593 parse_error_expected(NULL, (expected), 0); \
594 add_anchor_token(expected); \
595 eat_until_anchor(); \
596 rem_anchor_token(expected); \
602 static void set_scope(scope_t *new_scope)
605 scope->last_declaration = last_declaration;
609 last_declaration = new_scope->last_declaration;
613 * Search a symbol in a given namespace and returns its declaration or
614 * NULL if this symbol was not found.
616 static declaration_t *get_declaration(const symbol_t *const symbol,
617 const namespace_t namespc)
619 declaration_t *declaration = symbol->declaration;
620 for( ; declaration != NULL; declaration = declaration->symbol_next) {
621 if(declaration->namespc == namespc)
629 * pushs an environment_entry on the environment stack and links the
630 * corresponding symbol to the new entry
632 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
634 symbol_t *symbol = declaration->symbol;
635 namespace_t namespc = (namespace_t) declaration->namespc;
637 /* replace/add declaration into declaration list of the symbol */
638 declaration_t *iter = symbol->declaration;
640 symbol->declaration = declaration;
642 declaration_t *iter_last = NULL;
643 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
644 /* replace an entry? */
645 if(iter->namespc == namespc) {
646 if(iter_last == NULL) {
647 symbol->declaration = declaration;
649 iter_last->symbol_next = declaration;
651 declaration->symbol_next = iter->symbol_next;
656 assert(iter_last->symbol_next == NULL);
657 iter_last->symbol_next = declaration;
661 /* remember old declaration */
663 entry.symbol = symbol;
664 entry.old_declaration = iter;
665 entry.namespc = (unsigned short) namespc;
666 ARR_APP1(stack_entry_t, *stack_ptr, entry);
669 static void environment_push(declaration_t *declaration)
671 assert(declaration->source_position.input_name != NULL);
672 assert(declaration->parent_scope != NULL);
673 stack_push(&environment_stack, declaration);
676 static void label_push(declaration_t *declaration)
678 declaration->parent_scope = ¤t_function->scope;
679 stack_push(&label_stack, declaration);
683 * pops symbols from the environment stack until @p new_top is the top element
685 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
687 stack_entry_t *stack = *stack_ptr;
688 size_t top = ARR_LEN(stack);
691 assert(new_top <= top);
695 for(i = top; i > new_top; --i) {
696 stack_entry_t *entry = &stack[i - 1];
698 declaration_t *old_declaration = entry->old_declaration;
699 symbol_t *symbol = entry->symbol;
700 namespace_t namespc = (namespace_t)entry->namespc;
702 /* replace/remove declaration */
703 declaration_t *declaration = symbol->declaration;
704 assert(declaration != NULL);
705 if(declaration->namespc == namespc) {
706 if(old_declaration == NULL) {
707 symbol->declaration = declaration->symbol_next;
709 symbol->declaration = old_declaration;
712 declaration_t *iter_last = declaration;
713 declaration_t *iter = declaration->symbol_next;
714 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
715 /* replace an entry? */
716 if(iter->namespc == namespc) {
717 assert(iter_last != NULL);
718 iter_last->symbol_next = old_declaration;
719 if(old_declaration != NULL) {
720 old_declaration->symbol_next = iter->symbol_next;
725 assert(iter != NULL);
729 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
732 static void environment_pop_to(size_t new_top)
734 stack_pop_to(&environment_stack, new_top);
737 static void label_pop_to(size_t new_top)
739 stack_pop_to(&label_stack, new_top);
743 static int get_rank(const type_t *type)
745 assert(!is_typeref(type));
746 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
747 * and esp. footnote 108). However we can't fold constants (yet), so we
748 * can't decide whether unsigned int is possible, while int always works.
749 * (unsigned int would be preferable when possible... for stuff like
750 * struct { enum { ... } bla : 4; } ) */
751 if(type->kind == TYPE_ENUM)
752 return ATOMIC_TYPE_INT;
754 assert(type->kind == TYPE_ATOMIC);
755 return type->atomic.akind;
758 static type_t *promote_integer(type_t *type)
760 if(type->kind == TYPE_BITFIELD)
761 type = type->bitfield.base;
763 if(get_rank(type) < ATOMIC_TYPE_INT)
770 * Create a cast expression.
772 * @param expression the expression to cast
773 * @param dest_type the destination type
775 static expression_t *create_cast_expression(expression_t *expression,
778 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
780 cast->unary.value = expression;
781 cast->base.type = dest_type;
787 * Check if a given expression represents the 0 pointer constant.
789 static bool is_null_pointer_constant(const expression_t *expression)
791 /* skip void* cast */
792 if(expression->kind == EXPR_UNARY_CAST
793 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
794 expression = expression->unary.value;
797 /* TODO: not correct yet, should be any constant integer expression
798 * which evaluates to 0 */
799 if (expression->kind != EXPR_CONST)
802 type_t *const type = skip_typeref(expression->base.type);
803 if (!is_type_integer(type))
806 return expression->conste.v.int_value == 0;
810 * Create an implicit cast expression.
812 * @param expression the expression to cast
813 * @param dest_type the destination type
815 static expression_t *create_implicit_cast(expression_t *expression,
818 type_t *const source_type = expression->base.type;
820 if (source_type == dest_type)
823 return create_cast_expression(expression, dest_type);
826 /** Implements the rules from § 6.5.16.1 */
827 static type_t *semantic_assign(type_t *orig_type_left,
828 const expression_t *const right,
831 type_t *const orig_type_right = right->base.type;
832 type_t *const type_left = skip_typeref(orig_type_left);
833 type_t *const type_right = skip_typeref(orig_type_right);
835 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
836 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
837 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
838 && is_type_pointer(type_right))) {
839 return orig_type_left;
842 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
843 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
844 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
846 /* the left type has all qualifiers from the right type */
847 unsigned missing_qualifiers
848 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
849 if(missing_qualifiers != 0) {
850 errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
851 return orig_type_left;
854 points_to_left = get_unqualified_type(points_to_left);
855 points_to_right = get_unqualified_type(points_to_right);
857 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
858 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
859 return orig_type_left;
862 if (!types_compatible(points_to_left, points_to_right)) {
863 warningf(right->base.source_position,
864 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
865 orig_type_left, context, right, orig_type_right);
868 return orig_type_left;
871 if ((is_type_compound(type_left) && is_type_compound(type_right))
872 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
873 type_t *const unqual_type_left = get_unqualified_type(type_left);
874 type_t *const unqual_type_right = get_unqualified_type(type_right);
875 if (types_compatible(unqual_type_left, unqual_type_right)) {
876 return orig_type_left;
880 if (!is_type_valid(type_left))
883 if (!is_type_valid(type_right))
884 return orig_type_right;
889 static expression_t *parse_constant_expression(void)
891 /* start parsing at precedence 7 (conditional expression) */
892 expression_t *result = parse_sub_expression(7);
894 if(!is_constant_expression(result)) {
895 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
901 static expression_t *parse_assignment_expression(void)
903 /* start parsing at precedence 2 (assignment expression) */
904 return parse_sub_expression(2);
907 static type_t *make_global_typedef(const char *name, type_t *type)
909 symbol_t *const symbol = symbol_table_insert(name);
911 declaration_t *const declaration = allocate_declaration_zero();
912 declaration->namespc = NAMESPACE_NORMAL;
913 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
914 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
915 declaration->type = type;
916 declaration->symbol = symbol;
917 declaration->source_position = builtin_source_position;
919 record_declaration(declaration);
921 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
922 typedef_type->typedeft.declaration = declaration;
927 static string_t parse_string_literals(void)
929 assert(token.type == T_STRING_LITERAL);
930 string_t result = token.v.string;
934 while (token.type == T_STRING_LITERAL) {
935 result = concat_strings(&result, &token.v.string);
942 typedef enum gnu_attribute_kind_t {
953 GNU_AK_ALWAYS_INLINE,
957 } gnu_attribute_kind_t;
959 static const char *gnu_attribute_names[GNU_AK_LAST] = {
960 [GNU_AK_CONST] = "const",
961 [GNU_AK_VOLATILE] = "volatile",
962 [GNU_AK_CDECL] = "cdecl",
963 [GNU_AK_STDCALL] = "stdcall",
964 [GNU_AK_FASTCALL] = "fastcall",
965 [GNU_AK_DEPRECATED] = "deprecated",
966 [GNU_AK_NOINLINE] = "noinline",
967 [GNU_AK_NORETURN] = "noreturn",
968 [GNU_AK_NAKED] = "naked",
969 [GNU_AK_PURE] = "pure",
970 [GNU_AK_ALWAYS_INLINE] = "always_inline",
971 [GNU_AK_MALLOC] = "malloc",
972 [GNU_AK_WEAK] = "weak",
976 * compare two string, ignoring double underscores on the second.
978 static int strcmp_underscore(const char *s1, const char *s2) {
979 if(s2[0] == '_' && s2[1] == '_') {
981 size_t l1 = strlen(s1);
982 if(l1 + 2 != strlen(s2)) {
986 return strncmp(s1, s2, l1);
988 return strcmp(s1, s2);
992 * Parse one GNU attribute.
994 * Note that attribute names can be specified WITH or WITHOUT
995 * double underscores, ie const or __const__.
997 * The following attributes are parsed without arguments
1012 static void parse_gnu_attribute(void)
1014 eat(T___attribute__);
1019 if(token.type == T_const) {
1021 } else if(token.type == T_volatile) {
1023 } else if(token.type == T_cdecl) {
1024 /* __attribute__((cdecl)), WITH ms mode */
1026 } else if(token.type != T_IDENTIFIER) {
1027 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER);
1030 const symbol_t *sym = token.v.symbol;
1034 gnu_attribute_kind_t kind;
1035 for(kind = 0; kind < GNU_AK_LAST; ++kind) {
1036 if(strcmp_underscore(gnu_attribute_names[kind], name) == 0)
1042 case GNU_AK_VOLATILE:
1046 case GNU_AK_STDCALL:
1048 case GNU_AK_FASTCALL:
1050 case GNU_AK_DEPRECATED:
1052 case GNU_AK_NOINLINE:
1054 case GNU_AK_NORETURN:
1060 case GNU_AK_ALWAYS_INLINE:
1067 warningf(HERE, "unrecognized attribute '%s'", name);
1069 /* skip possible arguments */
1070 if(token.type == '(')
1071 eat_until_matching_token('(');
1074 if(token.type != ',')
1085 * Parse GNU attributes.
1087 static void parse_attributes(void)
1090 switch(token.type) {
1091 case T___attribute__: {
1092 parse_gnu_attribute();
1098 if(token.type != T_STRING_LITERAL) {
1099 parse_error_expected("while parsing assembler attribute",
1101 eat_until_matching_token('(');
1104 parse_string_literals();
1109 goto attributes_finished;
1114 attributes_finished:
1118 static designator_t *parse_designation(void)
1120 designator_t *result = NULL;
1121 designator_t *last = NULL;
1124 designator_t *designator;
1125 switch(token.type) {
1127 designator = allocate_ast_zero(sizeof(designator[0]));
1128 designator->source_position = token.source_position;
1130 add_anchor_token(']');
1131 designator->array_index = parse_constant_expression();
1132 rem_anchor_token(']');
1136 designator = allocate_ast_zero(sizeof(designator[0]));
1137 designator->source_position = token.source_position;
1139 if(token.type != T_IDENTIFIER) {
1140 parse_error_expected("while parsing designator",
1144 designator->symbol = token.v.symbol;
1152 assert(designator != NULL);
1154 last->next = designator;
1156 result = designator;
1164 static initializer_t *initializer_from_string(array_type_t *type,
1165 const string_t *const string)
1167 /* TODO: check len vs. size of array type */
1170 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1171 initializer->string.string = *string;
1176 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1177 wide_string_t *const string)
1179 /* TODO: check len vs. size of array type */
1182 initializer_t *const initializer =
1183 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1184 initializer->wide_string.string = *string;
1190 * Build an initializer from a given expression.
1192 static initializer_t *initializer_from_expression(type_t *orig_type,
1193 expression_t *expression)
1195 /* TODO check that expression is a constant expression */
1197 /* § 6.7.8.14/15 char array may be initialized by string literals */
1198 type_t *type = skip_typeref(orig_type);
1199 type_t *expr_type_orig = expression->base.type;
1200 type_t *expr_type = skip_typeref(expr_type_orig);
1201 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1202 array_type_t *const array_type = &type->array;
1203 type_t *const element_type = skip_typeref(array_type->element_type);
1205 if (element_type->kind == TYPE_ATOMIC) {
1206 atomic_type_kind_t akind = element_type->atomic.akind;
1207 switch (expression->kind) {
1208 case EXPR_STRING_LITERAL:
1209 if (akind == ATOMIC_TYPE_CHAR
1210 || akind == ATOMIC_TYPE_SCHAR
1211 || akind == ATOMIC_TYPE_UCHAR) {
1212 return initializer_from_string(array_type,
1213 &expression->string.value);
1216 case EXPR_WIDE_STRING_LITERAL: {
1217 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1218 if (get_unqualified_type(element_type) == bare_wchar_type) {
1219 return initializer_from_wide_string(array_type,
1220 &expression->wide_string.value);
1230 type_t *const res_type = semantic_assign(type, expression, "initializer");
1231 if (res_type == NULL)
1234 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1235 result->value.value = create_implicit_cast(expression, res_type);
1241 * Checks if a given expression can be used as an constant initializer.
1243 static bool is_initializer_constant(const expression_t *expression)
1245 return is_constant_expression(expression)
1246 || is_address_constant(expression);
1250 * Parses an scalar initializer.
1252 * § 6.7.8.11; eat {} without warning
1254 static initializer_t *parse_scalar_initializer(type_t *type,
1255 bool must_be_constant)
1257 /* there might be extra {} hierarchies */
1259 while(token.type == '{') {
1262 warningf(HERE, "extra curly braces around scalar initializer");
1267 expression_t *expression = parse_assignment_expression();
1268 if(must_be_constant && !is_initializer_constant(expression)) {
1269 errorf(expression->base.source_position,
1270 "Initialisation expression '%E' is not constant\n",
1274 initializer_t *initializer = initializer_from_expression(type, expression);
1276 if(initializer == NULL) {
1277 errorf(expression->base.source_position,
1278 "expression '%E' (type '%T') doesn't match expected type '%T'",
1279 expression, expression->base.type, type);
1284 bool additional_warning_displayed = false;
1286 if(token.type == ',') {
1289 if(token.type != '}') {
1290 if(!additional_warning_displayed) {
1291 warningf(HERE, "additional elements in scalar initializer");
1292 additional_warning_displayed = true;
1303 * An entry in the type path.
1305 typedef struct type_path_entry_t type_path_entry_t;
1306 struct type_path_entry_t {
1307 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1309 size_t index; /**< For array types: the current index. */
1310 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1315 * A type path expression a position inside compound or array types.
1317 typedef struct type_path_t type_path_t;
1318 struct type_path_t {
1319 type_path_entry_t *path; /**< An flexible array containing the current path. */
1320 type_t *top_type; /**< type of the element the path points */
1321 size_t max_index; /**< largest index in outermost array */
1325 * Prints a type path for debugging.
1327 static __attribute__((unused)) void debug_print_type_path(
1328 const type_path_t *path)
1330 size_t len = ARR_LEN(path->path);
1332 for(size_t i = 0; i < len; ++i) {
1333 const type_path_entry_t *entry = & path->path[i];
1335 type_t *type = skip_typeref(entry->type);
1336 if(is_type_compound(type)) {
1337 /* in gcc mode structs can have no members */
1338 if(entry->v.compound_entry == NULL) {
1342 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1343 } else if(is_type_array(type)) {
1344 fprintf(stderr, "[%zd]", entry->v.index);
1346 fprintf(stderr, "-INVALID-");
1349 if(path->top_type != NULL) {
1350 fprintf(stderr, " (");
1351 print_type(path->top_type);
1352 fprintf(stderr, ")");
1357 * Return the top type path entry, ie. in a path
1358 * (type).a.b returns the b.
1360 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1362 size_t len = ARR_LEN(path->path);
1364 return &path->path[len-1];
1368 * Enlarge the type path by an (empty) element.
1370 static type_path_entry_t *append_to_type_path(type_path_t *path)
1372 size_t len = ARR_LEN(path->path);
1373 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1375 type_path_entry_t *result = & path->path[len];
1376 memset(result, 0, sizeof(result[0]));
1381 * Descending into a sub-type. Enter the scope of the current
1384 static void descend_into_subtype(type_path_t *path)
1386 type_t *orig_top_type = path->top_type;
1387 type_t *top_type = skip_typeref(orig_top_type);
1389 assert(is_type_compound(top_type) || is_type_array(top_type));
1391 type_path_entry_t *top = append_to_type_path(path);
1392 top->type = top_type;
1394 if(is_type_compound(top_type)) {
1395 declaration_t *declaration = top_type->compound.declaration;
1396 declaration_t *entry = declaration->scope.declarations;
1397 top->v.compound_entry = entry;
1400 path->top_type = entry->type;
1402 path->top_type = NULL;
1405 assert(is_type_array(top_type));
1408 path->top_type = top_type->array.element_type;
1413 * Pop an entry from the given type path, ie. returning from
1414 * (type).a.b to (type).a
1416 static void ascend_from_subtype(type_path_t *path)
1418 type_path_entry_t *top = get_type_path_top(path);
1420 path->top_type = top->type;
1422 size_t len = ARR_LEN(path->path);
1423 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1427 * Pop entries from the given type path until the given
1428 * path level is reached.
1430 static void ascend_to(type_path_t *path, size_t top_path_level)
1432 size_t len = ARR_LEN(path->path);
1434 while(len > top_path_level) {
1435 ascend_from_subtype(path);
1436 len = ARR_LEN(path->path);
1440 static bool walk_designator(type_path_t *path, const designator_t *designator,
1441 bool used_in_offsetof)
1443 for( ; designator != NULL; designator = designator->next) {
1444 type_path_entry_t *top = get_type_path_top(path);
1445 type_t *orig_type = top->type;
1447 type_t *type = skip_typeref(orig_type);
1449 if(designator->symbol != NULL) {
1450 symbol_t *symbol = designator->symbol;
1451 if(!is_type_compound(type)) {
1452 if(is_type_valid(type)) {
1453 errorf(designator->source_position,
1454 "'.%Y' designator used for non-compound type '%T'",
1460 declaration_t *declaration = type->compound.declaration;
1461 declaration_t *iter = declaration->scope.declarations;
1462 for( ; iter != NULL; iter = iter->next) {
1463 if(iter->symbol == symbol) {
1468 errorf(designator->source_position,
1469 "'%T' has no member named '%Y'", orig_type, symbol);
1472 if(used_in_offsetof) {
1473 type_t *real_type = skip_typeref(iter->type);
1474 if(real_type->kind == TYPE_BITFIELD) {
1475 errorf(designator->source_position,
1476 "offsetof designator '%Y' may not specify bitfield",
1482 top->type = orig_type;
1483 top->v.compound_entry = iter;
1484 orig_type = iter->type;
1486 expression_t *array_index = designator->array_index;
1487 assert(designator->array_index != NULL);
1489 if(!is_type_array(type)) {
1490 if(is_type_valid(type)) {
1491 errorf(designator->source_position,
1492 "[%E] designator used for non-array type '%T'",
1493 array_index, orig_type);
1497 if(!is_type_valid(array_index->base.type)) {
1501 long index = fold_constant(array_index);
1502 if(!used_in_offsetof) {
1504 errorf(designator->source_position,
1505 "array index [%E] must be positive", array_index);
1508 if(type->array.size_constant == true) {
1509 long array_size = type->array.size;
1510 if(index >= array_size) {
1511 errorf(designator->source_position,
1512 "designator [%E] (%d) exceeds array size %d",
1513 array_index, index, array_size);
1519 top->type = orig_type;
1520 top->v.index = (size_t) index;
1521 orig_type = type->array.element_type;
1523 path->top_type = orig_type;
1525 if(designator->next != NULL) {
1526 descend_into_subtype(path);
1535 static void advance_current_object(type_path_t *path, size_t top_path_level)
1537 type_path_entry_t *top = get_type_path_top(path);
1539 type_t *type = skip_typeref(top->type);
1540 if(is_type_union(type)) {
1541 /* in unions only the first element is initialized */
1542 top->v.compound_entry = NULL;
1543 } else if(is_type_struct(type)) {
1544 declaration_t *entry = top->v.compound_entry;
1546 entry = entry->next;
1547 top->v.compound_entry = entry;
1549 path->top_type = entry->type;
1553 assert(is_type_array(type));
1557 if(!type->array.size_constant || top->v.index < type->array.size) {
1562 /* we're past the last member of the current sub-aggregate, try if we
1563 * can ascend in the type hierarchy and continue with another subobject */
1564 size_t len = ARR_LEN(path->path);
1566 if(len > top_path_level) {
1567 ascend_from_subtype(path);
1568 advance_current_object(path, top_path_level);
1570 path->top_type = NULL;
1575 * skip until token is found.
1577 static void skip_until(int type) {
1578 while(token.type != type) {
1579 if(token.type == T_EOF)
1586 * skip any {...} blocks until a closing braket is reached.
1588 static void skip_initializers(void)
1590 if(token.type == '{')
1593 while(token.type != '}') {
1594 if(token.type == T_EOF)
1596 if(token.type == '{') {
1604 static initializer_t *create_empty_initializer(void)
1606 static initializer_t empty_initializer
1607 = { .list = { { INITIALIZER_LIST }, 0 } };
1608 return &empty_initializer;
1612 * Parse a part of an initialiser for a struct or union,
1614 static initializer_t *parse_sub_initializer(type_path_t *path,
1615 type_t *outer_type, size_t top_path_level,
1616 parse_initializer_env_t *env)
1618 if(token.type == '}') {
1619 /* empty initializer */
1620 return create_empty_initializer();
1623 type_t *orig_type = path->top_type;
1624 type_t *type = NULL;
1626 if (orig_type == NULL) {
1627 /* We are initializing an empty compound. */
1629 type = skip_typeref(orig_type);
1631 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1632 * initializers in this case. */
1633 if(!is_type_valid(type)) {
1634 skip_initializers();
1635 return create_empty_initializer();
1639 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1642 designator_t *designator = NULL;
1643 if(token.type == '.' || token.type == '[') {
1644 designator = parse_designation();
1646 /* reset path to toplevel, evaluate designator from there */
1647 ascend_to(path, top_path_level);
1648 if(!walk_designator(path, designator, false)) {
1649 /* can't continue after designation error */
1653 initializer_t *designator_initializer
1654 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1655 designator_initializer->designator.designator = designator;
1656 ARR_APP1(initializer_t*, initializers, designator_initializer);
1661 if(token.type == '{') {
1662 if(type != NULL && is_type_scalar(type)) {
1663 sub = parse_scalar_initializer(type, env->must_be_constant);
1667 if (env->declaration != NULL)
1668 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1669 env->declaration->symbol);
1671 errorf(HERE, "extra brace group at end of initializer");
1673 descend_into_subtype(path);
1675 add_anchor_token('}');
1676 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1678 rem_anchor_token('}');
1681 ascend_from_subtype(path);
1685 goto error_parse_next;
1689 /* must be an expression */
1690 expression_t *expression = parse_assignment_expression();
1692 if(env->must_be_constant && !is_initializer_constant(expression)) {
1693 errorf(expression->base.source_position,
1694 "Initialisation expression '%E' is not constant\n",
1699 /* we are already outside, ... */
1703 /* handle { "string" } special case */
1704 if((expression->kind == EXPR_STRING_LITERAL
1705 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1706 && outer_type != NULL) {
1707 sub = initializer_from_expression(outer_type, expression);
1709 if(token.type == ',') {
1712 if(token.type != '}') {
1713 warningf(HERE, "excessive elements in initializer for type '%T'",
1716 /* TODO: eat , ... */
1721 /* descend into subtypes until expression matches type */
1723 orig_type = path->top_type;
1724 type = skip_typeref(orig_type);
1726 sub = initializer_from_expression(orig_type, expression);
1730 if(!is_type_valid(type)) {
1733 if(is_type_scalar(type)) {
1734 errorf(expression->base.source_position,
1735 "expression '%E' doesn't match expected type '%T'",
1736 expression, orig_type);
1740 descend_into_subtype(path);
1744 /* update largest index of top array */
1745 const type_path_entry_t *first = &path->path[0];
1746 type_t *first_type = first->type;
1747 first_type = skip_typeref(first_type);
1748 if(is_type_array(first_type)) {
1749 size_t index = first->v.index;
1750 if(index > path->max_index)
1751 path->max_index = index;
1755 /* append to initializers list */
1756 ARR_APP1(initializer_t*, initializers, sub);
1759 if(env->declaration != NULL)
1760 warningf(HERE, "excess elements in struct initializer for '%Y'",
1761 env->declaration->symbol);
1763 warningf(HERE, "excess elements in struct initializer");
1767 if(token.type == '}') {
1771 if(token.type == '}') {
1776 /* advance to the next declaration if we are not at the end */
1777 advance_current_object(path, top_path_level);
1778 orig_type = path->top_type;
1779 if(orig_type != NULL)
1780 type = skip_typeref(orig_type);
1786 size_t len = ARR_LEN(initializers);
1787 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1788 initializer_t *result = allocate_ast_zero(size);
1789 result->kind = INITIALIZER_LIST;
1790 result->list.len = len;
1791 memcpy(&result->list.initializers, initializers,
1792 len * sizeof(initializers[0]));
1794 DEL_ARR_F(initializers);
1795 ascend_to(path, top_path_level);
1800 skip_initializers();
1801 DEL_ARR_F(initializers);
1802 ascend_to(path, top_path_level);
1807 * Parses an initializer. Parsers either a compound literal
1808 * (env->declaration == NULL) or an initializer of a declaration.
1810 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1812 type_t *type = skip_typeref(env->type);
1813 initializer_t *result = NULL;
1816 if(is_type_scalar(type)) {
1817 result = parse_scalar_initializer(type, env->must_be_constant);
1818 } else if(token.type == '{') {
1822 memset(&path, 0, sizeof(path));
1823 path.top_type = env->type;
1824 path.path = NEW_ARR_F(type_path_entry_t, 0);
1826 descend_into_subtype(&path);
1828 add_anchor_token('}');
1829 result = parse_sub_initializer(&path, env->type, 1, env);
1830 rem_anchor_token('}');
1832 max_index = path.max_index;
1833 DEL_ARR_F(path.path);
1837 /* parse_scalar_initializer() also works in this case: we simply
1838 * have an expression without {} around it */
1839 result = parse_scalar_initializer(type, env->must_be_constant);
1842 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1843 * the array type size */
1844 if(is_type_array(type) && type->array.size_expression == NULL
1845 && result != NULL) {
1847 switch (result->kind) {
1848 case INITIALIZER_LIST:
1849 size = max_index + 1;
1852 case INITIALIZER_STRING:
1853 size = result->string.string.size;
1856 case INITIALIZER_WIDE_STRING:
1857 size = result->wide_string.string.size;
1861 internal_errorf(HERE, "invalid initializer type");
1864 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1865 cnst->base.type = type_size_t;
1866 cnst->conste.v.int_value = size;
1868 type_t *new_type = duplicate_type(type);
1870 new_type->array.size_expression = cnst;
1871 new_type->array.size_constant = true;
1872 new_type->array.size = size;
1873 env->type = new_type;
1881 static declaration_t *append_declaration(declaration_t *declaration);
1883 static declaration_t *parse_compound_type_specifier(bool is_struct)
1891 symbol_t *symbol = NULL;
1892 declaration_t *declaration = NULL;
1894 if (token.type == T___attribute__) {
1899 if(token.type == T_IDENTIFIER) {
1900 symbol = token.v.symbol;
1904 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1906 declaration = get_declaration(symbol, NAMESPACE_UNION);
1908 } else if(token.type != '{') {
1910 parse_error_expected("while parsing struct type specifier",
1911 T_IDENTIFIER, '{', 0);
1913 parse_error_expected("while parsing union type specifier",
1914 T_IDENTIFIER, '{', 0);
1920 if(declaration == NULL) {
1921 declaration = allocate_declaration_zero();
1922 declaration->namespc =
1923 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1924 declaration->source_position = token.source_position;
1925 declaration->symbol = symbol;
1926 declaration->parent_scope = scope;
1927 if (symbol != NULL) {
1928 environment_push(declaration);
1930 append_declaration(declaration);
1933 if(token.type == '{') {
1934 if(declaration->init.is_defined) {
1935 assert(symbol != NULL);
1936 errorf(HERE, "multiple definitions of '%s %Y'",
1937 is_struct ? "struct" : "union", symbol);
1938 declaration->scope.declarations = NULL;
1940 declaration->init.is_defined = true;
1942 parse_compound_type_entries(declaration);
1949 static void parse_enum_entries(type_t *const enum_type)
1953 if(token.type == '}') {
1955 errorf(HERE, "empty enum not allowed");
1959 add_anchor_token('}');
1961 if(token.type != T_IDENTIFIER) {
1962 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1964 rem_anchor_token('}');
1968 declaration_t *const entry = allocate_declaration_zero();
1969 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1970 entry->type = enum_type;
1971 entry->symbol = token.v.symbol;
1972 entry->source_position = token.source_position;
1975 if(token.type == '=') {
1977 expression_t *value = parse_constant_expression();
1979 value = create_implicit_cast(value, enum_type);
1980 entry->init.enum_value = value;
1985 record_declaration(entry);
1987 if(token.type != ',')
1990 } while(token.type != '}');
1991 rem_anchor_token('}');
1999 static type_t *parse_enum_specifier(void)
2003 declaration_t *declaration;
2006 if(token.type == T_IDENTIFIER) {
2007 symbol = token.v.symbol;
2010 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2011 } else if(token.type != '{') {
2012 parse_error_expected("while parsing enum type specifier",
2013 T_IDENTIFIER, '{', 0);
2020 if(declaration == NULL) {
2021 declaration = allocate_declaration_zero();
2022 declaration->namespc = NAMESPACE_ENUM;
2023 declaration->source_position = token.source_position;
2024 declaration->symbol = symbol;
2025 declaration->parent_scope = scope;
2028 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
2029 type->enumt.declaration = declaration;
2031 if(token.type == '{') {
2032 if(declaration->init.is_defined) {
2033 errorf(HERE, "multiple definitions of enum %Y", symbol);
2035 if (symbol != NULL) {
2036 environment_push(declaration);
2038 append_declaration(declaration);
2039 declaration->init.is_defined = 1;
2041 parse_enum_entries(type);
2049 * if a symbol is a typedef to another type, return true
2051 static bool is_typedef_symbol(symbol_t *symbol)
2053 const declaration_t *const declaration =
2054 get_declaration(symbol, NAMESPACE_NORMAL);
2056 declaration != NULL &&
2057 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2060 static type_t *parse_typeof(void)
2067 add_anchor_token(')');
2069 expression_t *expression = NULL;
2072 switch(token.type) {
2073 case T___extension__:
2074 /* this can be a prefix to a typename or an expression */
2075 /* we simply eat it now. */
2078 } while(token.type == T___extension__);
2082 if(is_typedef_symbol(token.v.symbol)) {
2083 type = parse_typename();
2085 expression = parse_expression();
2086 type = expression->base.type;
2091 type = parse_typename();
2095 expression = parse_expression();
2096 type = expression->base.type;
2100 rem_anchor_token(')');
2103 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
2104 typeof_type->typeoft.expression = expression;
2105 typeof_type->typeoft.typeof_type = type;
2113 SPECIFIER_SIGNED = 1 << 0,
2114 SPECIFIER_UNSIGNED = 1 << 1,
2115 SPECIFIER_LONG = 1 << 2,
2116 SPECIFIER_INT = 1 << 3,
2117 SPECIFIER_DOUBLE = 1 << 4,
2118 SPECIFIER_CHAR = 1 << 5,
2119 SPECIFIER_SHORT = 1 << 6,
2120 SPECIFIER_LONG_LONG = 1 << 7,
2121 SPECIFIER_FLOAT = 1 << 8,
2122 SPECIFIER_BOOL = 1 << 9,
2123 SPECIFIER_VOID = 1 << 10,
2124 SPECIFIER_INT8 = 1 << 11,
2125 SPECIFIER_INT16 = 1 << 12,
2126 SPECIFIER_INT32 = 1 << 13,
2127 SPECIFIER_INT64 = 1 << 14,
2128 SPECIFIER_INT128 = 1 << 15,
2129 #ifdef PROVIDE_COMPLEX
2130 SPECIFIER_COMPLEX = 1 << 16,
2131 SPECIFIER_IMAGINARY = 1 << 17,
2135 static type_t *create_builtin_type(symbol_t *const symbol,
2136 type_t *const real_type)
2138 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2139 type->builtin.symbol = symbol;
2140 type->builtin.real_type = real_type;
2142 type_t *result = typehash_insert(type);
2143 if (type != result) {
2150 static type_t *get_typedef_type(symbol_t *symbol)
2152 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2153 if(declaration == NULL
2154 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2157 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2158 type->typedeft.declaration = declaration;
2164 * check for the allowed MS alignment values.
2166 static bool check_elignment_value(long long intvalue) {
2167 if(intvalue < 1 || intvalue > 8192) {
2168 errorf(HERE, "illegal alignment value");
2171 unsigned v = (unsigned)intvalue;
2172 for(unsigned i = 1; i <= 8192; i += i) {
2176 errorf(HERE, "alignment must be power of two");
2180 #define DET_MOD(name, tag) do { \
2181 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2182 *modifiers |= tag; \
2185 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2187 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2190 if(token.type == T_restrict) {
2192 DET_MOD(restrict, DM_RESTRICT);
2194 } else if(token.type != T_IDENTIFIER)
2196 symbol_t *symbol = token.v.symbol;
2197 if(symbol == sym_align) {
2200 if(token.type != T_INTEGER)
2202 if(check_elignment_value(token.v.intvalue)) {
2203 if(specifiers->alignment != 0)
2204 warningf(HERE, "align used more than once");
2205 specifiers->alignment = (unsigned char)token.v.intvalue;
2209 } else if(symbol == sym_allocate) {
2212 if(token.type != T_IDENTIFIER)
2214 (void)token.v.symbol;
2216 } else if(symbol == sym_dllimport) {
2218 DET_MOD(dllimport, DM_DLLIMPORT);
2219 } else if(symbol == sym_dllexport) {
2221 DET_MOD(dllexport, DM_DLLEXPORT);
2222 } else if(symbol == sym_thread) {
2224 DET_MOD(thread, DM_THREAD);
2225 } else if(symbol == sym_naked) {
2227 DET_MOD(naked, DM_NAKED);
2228 } else if(symbol == sym_noinline) {
2230 DET_MOD(noinline, DM_NOINLINE);
2231 } else if(symbol == sym_noreturn) {
2233 DET_MOD(noreturn, DM_NORETURN);
2234 } else if(symbol == sym_nothrow) {
2236 DET_MOD(nothrow, DM_NOTHROW);
2237 } else if(symbol == sym_novtable) {
2239 DET_MOD(novtable, DM_NOVTABLE);
2240 } else if(symbol == sym_property) {
2244 bool is_get = false;
2245 if(token.type != T_IDENTIFIER)
2247 if(token.v.symbol == sym_get) {
2249 } else if(token.v.symbol == sym_put) {
2251 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2256 if(token.type != T_IDENTIFIER)
2259 if(specifiers->get_property_sym != NULL) {
2260 errorf(HERE, "get property name already specified");
2262 specifiers->get_property_sym = token.v.symbol;
2265 if(specifiers->put_property_sym != NULL) {
2266 errorf(HERE, "put property name already specified");
2268 specifiers->put_property_sym = token.v.symbol;
2272 if(token.type == ',') {
2279 } else if(symbol == sym_selectany) {
2281 DET_MOD(selectany, DM_SELECTANY);
2282 } else if(symbol == sym_uuid) {
2285 if(token.type != T_STRING_LITERAL)
2289 } else if(symbol == sym_deprecated) {
2291 if(specifiers->deprecated != 0)
2292 warningf(HERE, "deprecated used more than once");
2293 specifiers->deprecated = 1;
2294 if(token.type == '(') {
2296 if(token.type == T_STRING_LITERAL) {
2297 specifiers->deprecated_string = token.v.string.begin;
2300 errorf(HERE, "string literal expected");
2304 } else if(symbol == sym_noalias) {
2306 DET_MOD(noalias, DM_NOALIAS);
2308 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2310 if(token.type == '(')
2314 if (token.type == ',')
2321 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2323 type_t *type = NULL;
2324 unsigned type_qualifiers = 0;
2325 unsigned type_specifiers = 0;
2328 specifiers->source_position = token.source_position;
2331 switch(token.type) {
2334 #define MATCH_STORAGE_CLASS(token, class) \
2336 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2337 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2339 specifiers->declared_storage_class = class; \
2343 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2344 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2345 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2346 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2347 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2352 add_anchor_token(')');
2353 parse_microsoft_extended_decl_modifier(specifiers);
2354 rem_anchor_token(')');
2359 switch (specifiers->declared_storage_class) {
2360 case STORAGE_CLASS_NONE:
2361 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2364 case STORAGE_CLASS_EXTERN:
2365 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2368 case STORAGE_CLASS_STATIC:
2369 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2373 errorf(HERE, "multiple storage classes in declaration specifiers");
2379 /* type qualifiers */
2380 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2382 type_qualifiers |= qualifier; \
2386 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2387 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2388 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2389 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2390 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2391 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2392 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2393 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2395 case T___extension__:
2400 /* type specifiers */
2401 #define MATCH_SPECIFIER(token, specifier, name) \
2404 if(type_specifiers & specifier) { \
2405 errorf(HERE, "multiple " name " type specifiers given"); \
2407 type_specifiers |= specifier; \
2411 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2412 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2413 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2414 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2415 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2416 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2417 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2418 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2419 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2420 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2421 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2422 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2423 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2424 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2425 #ifdef PROVIDE_COMPLEX
2426 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2427 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2429 case T__forceinline:
2430 /* only in microsoft mode */
2431 specifiers->decl_modifiers |= DM_FORCEINLINE;
2435 specifiers->is_inline = true;
2440 if(type_specifiers & SPECIFIER_LONG_LONG) {
2441 errorf(HERE, "multiple type specifiers given");
2442 } else if(type_specifiers & SPECIFIER_LONG) {
2443 type_specifiers |= SPECIFIER_LONG_LONG;
2445 type_specifiers |= SPECIFIER_LONG;
2450 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2452 type->compound.declaration = parse_compound_type_specifier(true);
2456 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2458 type->compound.declaration = parse_compound_type_specifier(false);
2462 type = parse_enum_specifier();
2465 type = parse_typeof();
2467 case T___builtin_va_list:
2468 type = duplicate_type(type_valist);
2472 case T___attribute__:
2476 case T_IDENTIFIER: {
2477 /* only parse identifier if we haven't found a type yet */
2478 if(type != NULL || type_specifiers != 0)
2479 goto finish_specifiers;
2481 type_t *typedef_type = get_typedef_type(token.v.symbol);
2483 if(typedef_type == NULL)
2484 goto finish_specifiers;
2487 type = typedef_type;
2491 /* function specifier */
2493 goto finish_specifiers;
2500 atomic_type_kind_t atomic_type;
2502 /* match valid basic types */
2503 switch(type_specifiers) {
2504 case SPECIFIER_VOID:
2505 atomic_type = ATOMIC_TYPE_VOID;
2507 case SPECIFIER_CHAR:
2508 atomic_type = ATOMIC_TYPE_CHAR;
2510 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2511 atomic_type = ATOMIC_TYPE_SCHAR;
2513 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2514 atomic_type = ATOMIC_TYPE_UCHAR;
2516 case SPECIFIER_SHORT:
2517 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2518 case SPECIFIER_SHORT | SPECIFIER_INT:
2519 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2520 atomic_type = ATOMIC_TYPE_SHORT;
2522 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2523 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2524 atomic_type = ATOMIC_TYPE_USHORT;
2527 case SPECIFIER_SIGNED:
2528 case SPECIFIER_SIGNED | SPECIFIER_INT:
2529 atomic_type = ATOMIC_TYPE_INT;
2531 case SPECIFIER_UNSIGNED:
2532 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2533 atomic_type = ATOMIC_TYPE_UINT;
2535 case SPECIFIER_LONG:
2536 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2537 case SPECIFIER_LONG | SPECIFIER_INT:
2538 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2539 atomic_type = ATOMIC_TYPE_LONG;
2541 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2542 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2543 atomic_type = ATOMIC_TYPE_ULONG;
2545 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2546 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2547 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2548 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2550 atomic_type = ATOMIC_TYPE_LONGLONG;
2552 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2553 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2555 atomic_type = ATOMIC_TYPE_ULONGLONG;
2558 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2559 atomic_type = unsigned_int8_type_kind;
2562 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2563 atomic_type = unsigned_int16_type_kind;
2566 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2567 atomic_type = unsigned_int32_type_kind;
2570 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2571 atomic_type = unsigned_int64_type_kind;
2574 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2575 atomic_type = unsigned_int128_type_kind;
2578 case SPECIFIER_INT8:
2579 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2580 atomic_type = int8_type_kind;
2583 case SPECIFIER_INT16:
2584 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2585 atomic_type = int16_type_kind;
2588 case SPECIFIER_INT32:
2589 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2590 atomic_type = int32_type_kind;
2593 case SPECIFIER_INT64:
2594 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2595 atomic_type = int64_type_kind;
2598 case SPECIFIER_INT128:
2599 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2600 atomic_type = int128_type_kind;
2603 case SPECIFIER_FLOAT:
2604 atomic_type = ATOMIC_TYPE_FLOAT;
2606 case SPECIFIER_DOUBLE:
2607 atomic_type = ATOMIC_TYPE_DOUBLE;
2609 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2610 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2612 case SPECIFIER_BOOL:
2613 atomic_type = ATOMIC_TYPE_BOOL;
2615 #ifdef PROVIDE_COMPLEX
2616 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2617 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2619 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2620 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2622 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2623 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2625 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2626 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2628 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2629 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2631 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2632 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2636 /* invalid specifier combination, give an error message */
2637 if(type_specifiers == 0) {
2638 if (! strict_mode) {
2639 if (warning.implicit_int) {
2640 warningf(HERE, "no type specifiers in declaration, using 'int'");
2642 atomic_type = ATOMIC_TYPE_INT;
2645 errorf(HERE, "no type specifiers given in declaration");
2647 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2648 (type_specifiers & SPECIFIER_UNSIGNED)) {
2649 errorf(HERE, "signed and unsigned specifiers gives");
2650 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2651 errorf(HERE, "only integer types can be signed or unsigned");
2653 errorf(HERE, "multiple datatypes in declaration");
2655 atomic_type = ATOMIC_TYPE_INVALID;
2658 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2659 type->atomic.akind = atomic_type;
2662 if(type_specifiers != 0) {
2663 errorf(HERE, "multiple datatypes in declaration");
2667 type->base.qualifiers = type_qualifiers;
2668 /* FIXME: check type qualifiers here */
2670 type_t *result = typehash_insert(type);
2671 if(newtype && result != type) {
2675 specifiers->type = result;
2680 static type_qualifiers_t parse_type_qualifiers(void)
2682 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2685 switch(token.type) {
2686 /* type qualifiers */
2687 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2688 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2689 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2690 /* microsoft extended type modifiers */
2691 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2692 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2693 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2694 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2695 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2698 return type_qualifiers;
2703 static declaration_t *parse_identifier_list(void)
2705 declaration_t *declarations = NULL;
2706 declaration_t *last_declaration = NULL;
2708 declaration_t *const declaration = allocate_declaration_zero();
2709 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2710 declaration->source_position = token.source_position;
2711 declaration->symbol = token.v.symbol;
2714 if(last_declaration != NULL) {
2715 last_declaration->next = declaration;
2717 declarations = declaration;
2719 last_declaration = declaration;
2721 if(token.type != ',')
2724 } while(token.type == T_IDENTIFIER);
2726 return declarations;
2729 static void semantic_parameter(declaration_t *declaration)
2731 /* TODO: improve error messages */
2733 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2734 errorf(HERE, "typedef not allowed in parameter list");
2735 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2736 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2737 errorf(HERE, "parameter may only have none or register storage class");
2740 type_t *const orig_type = declaration->type;
2741 type_t * type = skip_typeref(orig_type);
2743 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2744 * into a pointer. § 6.7.5.3 (7) */
2745 if (is_type_array(type)) {
2746 type_t *const element_type = type->array.element_type;
2748 type = make_pointer_type(element_type, type->base.qualifiers);
2750 declaration->type = type;
2753 if(is_type_incomplete(type)) {
2754 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2755 orig_type, declaration->symbol);
2759 static declaration_t *parse_parameter(void)
2761 declaration_specifiers_t specifiers;
2762 memset(&specifiers, 0, sizeof(specifiers));
2764 parse_declaration_specifiers(&specifiers);
2766 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2768 semantic_parameter(declaration);
2773 static declaration_t *parse_parameters(function_type_t *type)
2775 if(token.type == T_IDENTIFIER) {
2776 symbol_t *symbol = token.v.symbol;
2777 if(!is_typedef_symbol(symbol)) {
2778 type->kr_style_parameters = true;
2779 return parse_identifier_list();
2783 if(token.type == ')') {
2784 type->unspecified_parameters = 1;
2787 if(token.type == T_void && look_ahead(1)->type == ')') {
2792 declaration_t *declarations = NULL;
2793 declaration_t *declaration;
2794 declaration_t *last_declaration = NULL;
2795 function_parameter_t *parameter;
2796 function_parameter_t *last_parameter = NULL;
2799 switch(token.type) {
2803 return declarations;
2806 case T___extension__:
2808 declaration = parse_parameter();
2810 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2811 memset(parameter, 0, sizeof(parameter[0]));
2812 parameter->type = declaration->type;
2814 if(last_parameter != NULL) {
2815 last_declaration->next = declaration;
2816 last_parameter->next = parameter;
2818 type->parameters = parameter;
2819 declarations = declaration;
2821 last_parameter = parameter;
2822 last_declaration = declaration;
2826 return declarations;
2828 if(token.type != ',')
2829 return declarations;
2839 } construct_type_kind_t;
2841 typedef struct construct_type_t construct_type_t;
2842 struct construct_type_t {
2843 construct_type_kind_t kind;
2844 construct_type_t *next;
2847 typedef struct parsed_pointer_t parsed_pointer_t;
2848 struct parsed_pointer_t {
2849 construct_type_t construct_type;
2850 type_qualifiers_t type_qualifiers;
2853 typedef struct construct_function_type_t construct_function_type_t;
2854 struct construct_function_type_t {
2855 construct_type_t construct_type;
2856 type_t *function_type;
2859 typedef struct parsed_array_t parsed_array_t;
2860 struct parsed_array_t {
2861 construct_type_t construct_type;
2862 type_qualifiers_t type_qualifiers;
2868 typedef struct construct_base_type_t construct_base_type_t;
2869 struct construct_base_type_t {
2870 construct_type_t construct_type;
2874 static construct_type_t *parse_pointer_declarator(void)
2878 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2879 memset(pointer, 0, sizeof(pointer[0]));
2880 pointer->construct_type.kind = CONSTRUCT_POINTER;
2881 pointer->type_qualifiers = parse_type_qualifiers();
2883 return (construct_type_t*) pointer;
2886 static construct_type_t *parse_array_declarator(void)
2889 add_anchor_token(']');
2891 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2892 memset(array, 0, sizeof(array[0]));
2893 array->construct_type.kind = CONSTRUCT_ARRAY;
2895 if(token.type == T_static) {
2896 array->is_static = true;
2900 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2901 if(type_qualifiers != 0) {
2902 if(token.type == T_static) {
2903 array->is_static = true;
2907 array->type_qualifiers = type_qualifiers;
2909 if(token.type == '*' && look_ahead(1)->type == ']') {
2910 array->is_variable = true;
2912 } else if(token.type != ']') {
2913 array->size = parse_assignment_expression();
2916 rem_anchor_token(']');
2919 return (construct_type_t*) array;
2924 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2927 add_anchor_token(')');
2930 if(declaration != NULL) {
2931 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2933 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2936 declaration_t *parameters = parse_parameters(&type->function);
2937 if(declaration != NULL) {
2938 declaration->scope.declarations = parameters;
2941 construct_function_type_t *construct_function_type =
2942 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2943 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2944 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2945 construct_function_type->function_type = type;
2947 rem_anchor_token(')');
2951 return (construct_type_t*) construct_function_type;
2954 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2955 bool may_be_abstract)
2957 /* construct a single linked list of construct_type_t's which describe
2958 * how to construct the final declarator type */
2959 construct_type_t *first = NULL;
2960 construct_type_t *last = NULL;
2963 while(token.type == '*') {
2964 construct_type_t *type = parse_pointer_declarator();
2975 /* TODO: find out if this is correct */
2978 construct_type_t *inner_types = NULL;
2980 switch(token.type) {
2982 if(declaration == NULL) {
2983 errorf(HERE, "no identifier expected in typename");
2985 declaration->symbol = token.v.symbol;
2986 declaration->source_position = token.source_position;
2992 add_anchor_token(')');
2993 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2994 rem_anchor_token(')');
3000 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
3001 /* avoid a loop in the outermost scope, because eat_statement doesn't
3003 if(token.type == '}' && current_function == NULL) {
3011 construct_type_t *p = last;
3014 construct_type_t *type;
3015 switch(token.type) {
3017 type = parse_function_declarator(declaration);
3020 type = parse_array_declarator();
3023 goto declarator_finished;
3026 /* insert in the middle of the list (behind p) */
3028 type->next = p->next;
3039 declarator_finished:
3042 /* append inner_types at the end of the list, we don't to set last anymore
3043 * as it's not needed anymore */
3045 assert(first == NULL);
3046 first = inner_types;
3048 last->next = inner_types;
3056 static type_t *construct_declarator_type(construct_type_t *construct_list,
3059 construct_type_t *iter = construct_list;
3060 for( ; iter != NULL; iter = iter->next) {
3061 switch(iter->kind) {
3062 case CONSTRUCT_INVALID:
3063 internal_errorf(HERE, "invalid type construction found");
3064 case CONSTRUCT_FUNCTION: {
3065 construct_function_type_t *construct_function_type
3066 = (construct_function_type_t*) iter;
3068 type_t *function_type = construct_function_type->function_type;
3070 function_type->function.return_type = type;
3072 type_t *skipped_return_type = skip_typeref(type);
3073 if (is_type_function(skipped_return_type)) {
3074 errorf(HERE, "function returning function is not allowed");
3075 type = type_error_type;
3076 } else if (is_type_array(skipped_return_type)) {
3077 errorf(HERE, "function returning array is not allowed");
3078 type = type_error_type;
3080 type = function_type;
3085 case CONSTRUCT_POINTER: {
3086 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3087 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
3088 pointer_type->pointer.points_to = type;
3089 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3091 type = pointer_type;
3095 case CONSTRUCT_ARRAY: {
3096 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3097 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
3099 expression_t *size_expression = parsed_array->size;
3100 if(size_expression != NULL) {
3102 = create_implicit_cast(size_expression, type_size_t);
3105 array_type->base.qualifiers = parsed_array->type_qualifiers;
3106 array_type->array.element_type = type;
3107 array_type->array.is_static = parsed_array->is_static;
3108 array_type->array.is_variable = parsed_array->is_variable;
3109 array_type->array.size_expression = size_expression;
3111 if(size_expression != NULL) {
3112 if(is_constant_expression(size_expression)) {
3113 array_type->array.size_constant = true;
3114 array_type->array.size
3115 = fold_constant(size_expression);
3117 array_type->array.is_vla = true;
3121 type_t *skipped_type = skip_typeref(type);
3122 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3123 errorf(HERE, "array of void is not allowed");
3124 type = type_error_type;
3132 type_t *hashed_type = typehash_insert(type);
3133 if(hashed_type != type) {
3134 /* the function type was constructed earlier freeing it here will
3135 * destroy other types... */
3136 if(iter->kind != CONSTRUCT_FUNCTION) {
3146 static declaration_t *parse_declarator(
3147 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3149 declaration_t *const declaration = allocate_declaration_zero();
3150 declaration->declared_storage_class = specifiers->declared_storage_class;
3151 declaration->modifiers = specifiers->decl_modifiers;
3152 declaration->deprecated = specifiers->deprecated;
3153 declaration->deprecated_string = specifiers->deprecated_string;
3154 declaration->get_property_sym = specifiers->get_property_sym;
3155 declaration->put_property_sym = specifiers->put_property_sym;
3156 declaration->is_inline = specifiers->is_inline;
3158 declaration->storage_class = specifiers->declared_storage_class;
3159 if(declaration->storage_class == STORAGE_CLASS_NONE
3160 && scope != global_scope) {
3161 declaration->storage_class = STORAGE_CLASS_AUTO;
3164 if(specifiers->alignment != 0) {
3165 /* TODO: add checks here */
3166 declaration->alignment = specifiers->alignment;
3169 construct_type_t *construct_type
3170 = parse_inner_declarator(declaration, may_be_abstract);
3171 type_t *const type = specifiers->type;
3172 declaration->type = construct_declarator_type(construct_type, type);
3174 if(construct_type != NULL) {
3175 obstack_free(&temp_obst, construct_type);
3181 static type_t *parse_abstract_declarator(type_t *base_type)
3183 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3185 type_t *result = construct_declarator_type(construct_type, base_type);
3186 if(construct_type != NULL) {
3187 obstack_free(&temp_obst, construct_type);
3193 static declaration_t *append_declaration(declaration_t* const declaration)
3195 if (last_declaration != NULL) {
3196 last_declaration->next = declaration;
3198 scope->declarations = declaration;
3200 last_declaration = declaration;
3205 * Check if the declaration of main is suspicious. main should be a
3206 * function with external linkage, returning int, taking either zero
3207 * arguments, two, or three arguments of appropriate types, ie.
3209 * int main([ int argc, char **argv [, char **env ] ]).
3211 * @param decl the declaration to check
3212 * @param type the function type of the declaration
3214 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3216 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3217 warningf(decl->source_position, "'main' is normally a non-static function");
3219 if (skip_typeref(func_type->return_type) != type_int) {
3220 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3222 const function_parameter_t *parm = func_type->parameters;
3224 type_t *const first_type = parm->type;
3225 if (!types_compatible(skip_typeref(first_type), type_int)) {
3226 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3230 type_t *const second_type = parm->type;
3231 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3232 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3236 type_t *const third_type = parm->type;
3237 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3238 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3242 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3246 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3252 * Check if a symbol is the equal to "main".
3254 static bool is_sym_main(const symbol_t *const sym)
3256 return strcmp(sym->string, "main") == 0;
3259 static declaration_t *internal_record_declaration(
3260 declaration_t *const declaration,
3261 const bool is_function_definition)
3263 const symbol_t *const symbol = declaration->symbol;
3264 const namespace_t namespc = (namespace_t)declaration->namespc;
3266 type_t *const orig_type = declaration->type;
3267 type_t *const type = skip_typeref(orig_type);
3268 if (is_type_function(type) &&
3269 type->function.unspecified_parameters &&
3270 warning.strict_prototypes) {
3271 warningf(declaration->source_position,
3272 "function declaration '%#T' is not a prototype",
3273 orig_type, declaration->symbol);
3276 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3277 check_type_of_main(declaration, &type->function);
3280 assert(declaration->symbol != NULL);
3281 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3283 assert(declaration != previous_declaration);
3284 if (previous_declaration != NULL) {
3285 if (previous_declaration->parent_scope == scope) {
3286 /* can happen for K&R style declarations */
3287 if(previous_declaration->type == NULL) {
3288 previous_declaration->type = declaration->type;
3291 const type_t *prev_type = skip_typeref(previous_declaration->type);
3292 if (!types_compatible(type, prev_type)) {
3293 errorf(declaration->source_position,
3294 "declaration '%#T' is incompatible with "
3295 "previous declaration '%#T'",
3296 orig_type, symbol, previous_declaration->type, symbol);
3297 errorf(previous_declaration->source_position,
3298 "previous declaration of '%Y' was here", symbol);
3300 unsigned old_storage_class = previous_declaration->storage_class;
3301 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3302 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3303 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3304 return previous_declaration;
3307 unsigned new_storage_class = declaration->storage_class;
3309 if(is_type_incomplete(prev_type)) {
3310 previous_declaration->type = type;
3314 /* pretend no storage class means extern for function
3315 * declarations (except if the previous declaration is neither
3316 * none nor extern) */
3317 if (is_type_function(type)) {
3318 switch (old_storage_class) {
3319 case STORAGE_CLASS_NONE:
3320 old_storage_class = STORAGE_CLASS_EXTERN;
3322 case STORAGE_CLASS_EXTERN:
3323 if (is_function_definition) {
3324 if (warning.missing_prototypes &&
3325 prev_type->function.unspecified_parameters &&
3326 !is_sym_main(symbol)) {
3327 warningf(declaration->source_position,
3328 "no previous prototype for '%#T'",
3331 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3332 new_storage_class = STORAGE_CLASS_EXTERN;
3340 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3341 new_storage_class == STORAGE_CLASS_EXTERN) {
3342 warn_redundant_declaration:
3343 if (warning.redundant_decls) {
3344 warningf(declaration->source_position,
3345 "redundant declaration for '%Y'", symbol);
3346 warningf(previous_declaration->source_position,
3347 "previous declaration of '%Y' was here",
3350 } else if (current_function == NULL) {
3351 if (old_storage_class != STORAGE_CLASS_STATIC &&
3352 new_storage_class == STORAGE_CLASS_STATIC) {
3353 errorf(declaration->source_position,
3354 "static declaration of '%Y' follows non-static declaration",
3356 errorf(previous_declaration->source_position,
3357 "previous declaration of '%Y' was here", symbol);
3359 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3360 goto warn_redundant_declaration;
3362 if (new_storage_class == STORAGE_CLASS_NONE) {
3363 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3364 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3368 if (old_storage_class == new_storage_class) {
3369 errorf(declaration->source_position,
3370 "redeclaration of '%Y'", symbol);
3372 errorf(declaration->source_position,
3373 "redeclaration of '%Y' with different linkage",
3376 errorf(previous_declaration->source_position,
3377 "previous declaration of '%Y' was here", symbol);
3380 return previous_declaration;
3382 } else if (is_function_definition) {
3383 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3384 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3385 warningf(declaration->source_position,
3386 "no previous prototype for '%#T'", orig_type, symbol);
3387 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3388 warningf(declaration->source_position,
3389 "no previous declaration for '%#T'", orig_type,
3393 } else if (warning.missing_declarations &&
3394 scope == global_scope &&
3395 !is_type_function(type) && (
3396 declaration->storage_class == STORAGE_CLASS_NONE ||
3397 declaration->storage_class == STORAGE_CLASS_THREAD
3399 warningf(declaration->source_position,
3400 "no previous declaration for '%#T'", orig_type, symbol);
3403 assert(declaration->parent_scope == NULL);
3404 assert(scope != NULL);
3406 declaration->parent_scope = scope;
3408 environment_push(declaration);
3409 return append_declaration(declaration);
3412 static declaration_t *record_declaration(declaration_t *declaration)
3414 return internal_record_declaration(declaration, false);
3417 static declaration_t *record_function_definition(declaration_t *declaration)
3419 return internal_record_declaration(declaration, true);
3422 static void parser_error_multiple_definition(declaration_t *declaration,
3423 const source_position_t source_position)
3425 errorf(source_position, "multiple definition of symbol '%Y'",
3426 declaration->symbol);
3427 errorf(declaration->source_position,
3428 "this is the location of the previous definition.");
3431 static bool is_declaration_specifier(const token_t *token,
3432 bool only_type_specifiers)
3434 switch(token->type) {
3438 return is_typedef_symbol(token->v.symbol);
3440 case T___extension__:
3443 return !only_type_specifiers;
3450 static void parse_init_declarator_rest(declaration_t *declaration)
3454 type_t *orig_type = declaration->type;
3455 type_t *type = skip_typeref(orig_type);
3457 if(declaration->init.initializer != NULL) {
3458 parser_error_multiple_definition(declaration, token.source_position);
3461 bool must_be_constant = false;
3462 if(declaration->storage_class == STORAGE_CLASS_STATIC
3463 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3464 || declaration->parent_scope == global_scope) {
3465 must_be_constant = true;
3468 parse_initializer_env_t env;
3469 env.type = orig_type;
3470 env.must_be_constant = must_be_constant;
3471 env.declaration = declaration;
3473 initializer_t *initializer = parse_initializer(&env);
3475 if(env.type != orig_type) {
3476 orig_type = env.type;
3477 type = skip_typeref(orig_type);
3478 declaration->type = env.type;
3481 if(is_type_function(type)) {
3482 errorf(declaration->source_position,
3483 "initializers not allowed for function types at declator '%Y' (type '%T')",
3484 declaration->symbol, orig_type);
3486 declaration->init.initializer = initializer;
3490 /* parse rest of a declaration without any declarator */
3491 static void parse_anonymous_declaration_rest(
3492 const declaration_specifiers_t *specifiers,
3493 parsed_declaration_func finished_declaration)
3497 declaration_t *const declaration = allocate_declaration_zero();
3498 declaration->type = specifiers->type;
3499 declaration->declared_storage_class = specifiers->declared_storage_class;
3500 declaration->source_position = specifiers->source_position;
3501 declaration->modifiers = specifiers->decl_modifiers;
3503 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3504 warningf(declaration->source_position, "useless storage class in empty declaration");
3506 declaration->storage_class = STORAGE_CLASS_NONE;
3508 type_t *type = declaration->type;
3509 switch (type->kind) {
3510 case TYPE_COMPOUND_STRUCT:
3511 case TYPE_COMPOUND_UNION: {
3512 if (type->compound.declaration->symbol == NULL) {
3513 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3522 warningf(declaration->source_position, "empty declaration");
3526 finished_declaration(declaration);
3529 static void parse_declaration_rest(declaration_t *ndeclaration,
3530 const declaration_specifiers_t *specifiers,
3531 parsed_declaration_func finished_declaration)
3533 add_anchor_token(';');
3534 add_anchor_token('=');
3535 add_anchor_token(',');
3537 declaration_t *declaration = finished_declaration(ndeclaration);
3539 type_t *orig_type = declaration->type;
3540 type_t *type = skip_typeref(orig_type);
3542 if (type->kind != TYPE_FUNCTION &&
3543 declaration->is_inline &&
3544 is_type_valid(type)) {
3545 warningf(declaration->source_position,
3546 "variable '%Y' declared 'inline'\n", declaration->symbol);
3549 if(token.type == '=') {
3550 parse_init_declarator_rest(declaration);
3553 if(token.type != ',')
3557 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3562 rem_anchor_token(';');
3563 rem_anchor_token('=');
3564 rem_anchor_token(',');
3567 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3569 symbol_t *symbol = declaration->symbol;
3570 if(symbol == NULL) {
3571 errorf(HERE, "anonymous declaration not valid as function parameter");
3574 namespace_t namespc = (namespace_t) declaration->namespc;
3575 if(namespc != NAMESPACE_NORMAL) {
3576 return record_declaration(declaration);
3579 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3580 if(previous_declaration == NULL ||
3581 previous_declaration->parent_scope != scope) {
3582 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3587 if(previous_declaration->type == NULL) {
3588 previous_declaration->type = declaration->type;
3589 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3590 previous_declaration->storage_class = declaration->storage_class;
3591 previous_declaration->parent_scope = scope;
3592 return previous_declaration;
3594 return record_declaration(declaration);
3598 static void parse_declaration(parsed_declaration_func finished_declaration)
3600 declaration_specifiers_t specifiers;
3601 memset(&specifiers, 0, sizeof(specifiers));
3602 parse_declaration_specifiers(&specifiers);
3604 if(token.type == ';') {
3605 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3607 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3608 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3612 static void parse_kr_declaration_list(declaration_t *declaration)
3614 type_t *type = skip_typeref(declaration->type);
3615 if(!is_type_function(type))
3618 if(!type->function.kr_style_parameters)
3621 /* push function parameters */
3622 int top = environment_top();
3623 scope_t *last_scope = scope;
3624 set_scope(&declaration->scope);
3626 declaration_t *parameter = declaration->scope.declarations;
3627 for( ; parameter != NULL; parameter = parameter->next) {
3628 assert(parameter->parent_scope == NULL);
3629 parameter->parent_scope = scope;
3630 environment_push(parameter);
3633 /* parse declaration list */
3634 while(is_declaration_specifier(&token, false)) {
3635 parse_declaration(finished_kr_declaration);
3638 /* pop function parameters */
3639 assert(scope == &declaration->scope);
3640 set_scope(last_scope);
3641 environment_pop_to(top);
3643 /* update function type */
3644 type_t *new_type = duplicate_type(type);
3645 new_type->function.kr_style_parameters = false;
3647 function_parameter_t *parameters = NULL;
3648 function_parameter_t *last_parameter = NULL;
3650 declaration_t *parameter_declaration = declaration->scope.declarations;
3651 for( ; parameter_declaration != NULL;
3652 parameter_declaration = parameter_declaration->next) {
3653 type_t *parameter_type = parameter_declaration->type;
3654 if(parameter_type == NULL) {
3656 errorf(HERE, "no type specified for function parameter '%Y'",
3657 parameter_declaration->symbol);
3659 if (warning.implicit_int) {
3660 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3661 parameter_declaration->symbol);
3663 parameter_type = type_int;
3664 parameter_declaration->type = parameter_type;
3668 semantic_parameter(parameter_declaration);
3669 parameter_type = parameter_declaration->type;
3671 function_parameter_t *function_parameter
3672 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3673 memset(function_parameter, 0, sizeof(function_parameter[0]));
3675 function_parameter->type = parameter_type;
3676 if(last_parameter != NULL) {
3677 last_parameter->next = function_parameter;
3679 parameters = function_parameter;
3681 last_parameter = function_parameter;
3683 new_type->function.parameters = parameters;
3685 type = typehash_insert(new_type);
3686 if(type != new_type) {
3687 obstack_free(type_obst, new_type);
3690 declaration->type = type;
3693 static bool first_err = true;
3696 * When called with first_err set, prints the name of the current function,
3699 static void print_in_function(void) {
3702 diagnosticf("%s: In function '%Y':\n",
3703 current_function->source_position.input_name,
3704 current_function->symbol);
3709 * Check if all labels are defined in the current function.
3710 * Check if all labels are used in the current function.
3712 static void check_labels(void)
3714 for (const goto_statement_t *goto_statement = goto_first;
3715 goto_statement != NULL;
3716 goto_statement = goto_statement->next) {
3717 declaration_t *label = goto_statement->label;
3720 if (label->source_position.input_name == NULL) {
3721 print_in_function();
3722 errorf(goto_statement->base.source_position,
3723 "label '%Y' used but not defined", label->symbol);
3726 goto_first = goto_last = NULL;
3728 if (warning.unused_label) {
3729 for (const label_statement_t *label_statement = label_first;
3730 label_statement != NULL;
3731 label_statement = label_statement->next) {
3732 const declaration_t *label = label_statement->label;
3734 if (! label->used) {
3735 print_in_function();
3736 warningf(label_statement->base.source_position,
3737 "label '%Y' defined but not used", label->symbol);
3741 label_first = label_last = NULL;
3745 * Check declarations of current_function for unused entities.
3747 static void check_declarations(void)
3749 if (warning.unused_parameter) {
3750 const scope_t *scope = ¤t_function->scope;
3752 const declaration_t *parameter = scope->declarations;
3753 for (; parameter != NULL; parameter = parameter->next) {
3754 if (! parameter->used) {
3755 print_in_function();
3756 warningf(parameter->source_position,
3757 "unused parameter '%Y'", parameter->symbol);
3761 if (warning.unused_variable) {
3765 static void parse_external_declaration(void)
3767 /* function-definitions and declarations both start with declaration
3769 declaration_specifiers_t specifiers;
3770 memset(&specifiers, 0, sizeof(specifiers));
3772 add_anchor_token(';');
3773 parse_declaration_specifiers(&specifiers);
3774 rem_anchor_token(';');
3776 /* must be a declaration */
3777 if(token.type == ';') {
3778 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3782 add_anchor_token(',');
3783 add_anchor_token('=');
3784 rem_anchor_token(';');
3786 /* declarator is common to both function-definitions and declarations */
3787 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3789 rem_anchor_token(',');
3790 rem_anchor_token('=');
3791 rem_anchor_token(';');
3793 /* must be a declaration */
3794 if(token.type == ',' || token.type == '=' || token.type == ';') {
3795 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3799 /* must be a function definition */
3800 parse_kr_declaration_list(ndeclaration);
3802 if(token.type != '{') {
3803 parse_error_expected("while parsing function definition", '{', 0);
3804 eat_until_matching_token(';');
3808 type_t *type = ndeclaration->type;
3810 /* note that we don't skip typerefs: the standard doesn't allow them here
3811 * (so we can't use is_type_function here) */
3812 if(type->kind != TYPE_FUNCTION) {
3813 if (is_type_valid(type)) {
3814 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3815 type, ndeclaration->symbol);
3821 /* § 6.7.5.3 (14) a function definition with () means no
3822 * parameters (and not unspecified parameters) */
3823 if(type->function.unspecified_parameters) {
3824 type_t *duplicate = duplicate_type(type);
3825 duplicate->function.unspecified_parameters = false;
3827 type = typehash_insert(duplicate);
3828 if(type != duplicate) {
3829 obstack_free(type_obst, duplicate);
3831 ndeclaration->type = type;
3834 declaration_t *const declaration = record_function_definition(ndeclaration);
3835 if(ndeclaration != declaration) {
3836 declaration->scope = ndeclaration->scope;
3838 type = skip_typeref(declaration->type);
3840 /* push function parameters and switch scope */
3841 int top = environment_top();
3842 scope_t *last_scope = scope;
3843 set_scope(&declaration->scope);
3845 declaration_t *parameter = declaration->scope.declarations;
3846 for( ; parameter != NULL; parameter = parameter->next) {
3847 if(parameter->parent_scope == &ndeclaration->scope) {
3848 parameter->parent_scope = scope;
3850 assert(parameter->parent_scope == NULL
3851 || parameter->parent_scope == scope);
3852 parameter->parent_scope = scope;
3853 environment_push(parameter);
3856 if(declaration->init.statement != NULL) {
3857 parser_error_multiple_definition(declaration, token.source_position);
3859 goto end_of_parse_external_declaration;
3861 /* parse function body */
3862 int label_stack_top = label_top();
3863 declaration_t *old_current_function = current_function;
3864 current_function = declaration;
3866 declaration->init.statement = parse_compound_statement();
3869 check_declarations();
3871 assert(current_function == declaration);
3872 current_function = old_current_function;
3873 label_pop_to(label_stack_top);
3876 end_of_parse_external_declaration:
3877 assert(scope == &declaration->scope);
3878 set_scope(last_scope);
3879 environment_pop_to(top);
3882 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3883 source_position_t source_position)
3885 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3886 type->bitfield.base = base;
3887 type->bitfield.size = size;
3892 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3895 declaration_t *iter = compound_declaration->scope.declarations;
3896 for( ; iter != NULL; iter = iter->next) {
3897 if(iter->namespc != NAMESPACE_NORMAL)
3900 if(iter->symbol == NULL) {
3901 type_t *type = skip_typeref(iter->type);
3902 if(is_type_compound(type)) {
3903 declaration_t *result
3904 = find_compound_entry(type->compound.declaration, symbol);
3911 if(iter->symbol == symbol) {
3919 static void parse_compound_declarators(declaration_t *struct_declaration,
3920 const declaration_specifiers_t *specifiers)
3922 declaration_t *last_declaration = struct_declaration->scope.declarations;
3923 if(last_declaration != NULL) {
3924 while(last_declaration->next != NULL) {
3925 last_declaration = last_declaration->next;
3930 declaration_t *declaration;
3932 if(token.type == ':') {
3933 source_position_t source_position = HERE;
3936 type_t *base_type = specifiers->type;
3937 expression_t *size = parse_constant_expression();
3939 if(!is_type_integer(skip_typeref(base_type))) {
3940 errorf(HERE, "bitfield base type '%T' is not an integer type",
3944 type_t *type = make_bitfield_type(base_type, size, source_position);
3946 declaration = allocate_declaration_zero();
3947 declaration->namespc = NAMESPACE_NORMAL;
3948 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3949 declaration->storage_class = STORAGE_CLASS_NONE;
3950 declaration->source_position = source_position;
3951 declaration->modifiers = specifiers->decl_modifiers;
3952 declaration->type = type;
3954 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3956 type_t *orig_type = declaration->type;
3957 type_t *type = skip_typeref(orig_type);
3959 if(token.type == ':') {
3960 source_position_t source_position = HERE;
3962 expression_t *size = parse_constant_expression();
3964 if(!is_type_integer(type)) {
3965 errorf(HERE, "bitfield base type '%T' is not an "
3966 "integer type", orig_type);
3969 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3970 declaration->type = bitfield_type;
3972 /* TODO we ignore arrays for now... what is missing is a check
3973 * that they're at the end of the struct */
3974 if(is_type_incomplete(type) && !is_type_array(type)) {
3976 "compound member '%Y' has incomplete type '%T'",
3977 declaration->symbol, orig_type);
3978 } else if(is_type_function(type)) {
3979 errorf(HERE, "compound member '%Y' must not have function "
3980 "type '%T'", declaration->symbol, orig_type);
3985 /* make sure we don't define a symbol multiple times */
3986 symbol_t *symbol = declaration->symbol;
3987 if(symbol != NULL) {
3988 declaration_t *prev_decl
3989 = find_compound_entry(struct_declaration, symbol);
3991 if(prev_decl != NULL) {
3992 assert(prev_decl->symbol == symbol);
3993 errorf(declaration->source_position,
3994 "multiple declarations of symbol '%Y'", symbol);
3995 errorf(prev_decl->source_position,
3996 "previous declaration of '%Y' was here", symbol);
4000 /* append declaration */
4001 if(last_declaration != NULL) {
4002 last_declaration->next = declaration;
4004 struct_declaration->scope.declarations = declaration;
4006 last_declaration = declaration;
4008 if(token.type != ',')
4018 static void parse_compound_type_entries(declaration_t *compound_declaration)
4021 add_anchor_token('}');
4023 while(token.type != '}' && token.type != T_EOF) {
4024 declaration_specifiers_t specifiers;
4025 memset(&specifiers, 0, sizeof(specifiers));
4026 parse_declaration_specifiers(&specifiers);
4028 parse_compound_declarators(compound_declaration, &specifiers);
4030 rem_anchor_token('}');
4032 if(token.type == T_EOF) {
4033 errorf(HERE, "EOF while parsing struct");
4038 static type_t *parse_typename(void)
4040 declaration_specifiers_t specifiers;
4041 memset(&specifiers, 0, sizeof(specifiers));
4042 parse_declaration_specifiers(&specifiers);
4043 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4044 /* TODO: improve error message, user does probably not know what a
4045 * storage class is...
4047 errorf(HERE, "typename may not have a storage class");
4050 type_t *result = parse_abstract_declarator(specifiers.type);
4058 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4059 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4060 expression_t *left);
4062 typedef struct expression_parser_function_t expression_parser_function_t;
4063 struct expression_parser_function_t {
4064 unsigned precedence;
4065 parse_expression_function parser;
4066 unsigned infix_precedence;
4067 parse_expression_infix_function infix_parser;
4070 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4073 * Creates a new invalid expression.
4075 static expression_t *create_invalid_expression(void)
4077 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
4078 expression->base.source_position = token.source_position;
4083 * Prints an error message if an expression was expected but not read
4085 static expression_t *expected_expression_error(void)
4087 /* skip the error message if the error token was read */
4088 if (token.type != T_ERROR) {
4089 errorf(HERE, "expected expression, got token '%K'", &token);
4093 return create_invalid_expression();
4097 * Parse a string constant.
4099 static expression_t *parse_string_const(void)
4102 if (token.type == T_STRING_LITERAL) {
4103 string_t res = token.v.string;
4105 while (token.type == T_STRING_LITERAL) {
4106 res = concat_strings(&res, &token.v.string);
4109 if (token.type != T_WIDE_STRING_LITERAL) {
4110 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4111 /* note: that we use type_char_ptr here, which is already the
4112 * automatic converted type. revert_automatic_type_conversion
4113 * will construct the array type */
4114 cnst->base.type = type_char_ptr;
4115 cnst->string.value = res;
4119 wres = concat_string_wide_string(&res, &token.v.wide_string);
4121 wres = token.v.wide_string;
4126 switch (token.type) {
4127 case T_WIDE_STRING_LITERAL:
4128 wres = concat_wide_strings(&wres, &token.v.wide_string);
4131 case T_STRING_LITERAL:
4132 wres = concat_wide_string_string(&wres, &token.v.string);
4136 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4137 cnst->base.type = type_wchar_t_ptr;
4138 cnst->wide_string.value = wres;
4147 * Parse an integer constant.
4149 static expression_t *parse_int_const(void)
4151 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4152 cnst->base.source_position = HERE;
4153 cnst->base.type = token.datatype;
4154 cnst->conste.v.int_value = token.v.intvalue;
4162 * Parse a character constant.
4164 static expression_t *parse_character_constant(void)
4166 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4168 cnst->base.source_position = HERE;
4169 cnst->base.type = token.datatype;
4170 cnst->conste.v.character = token.v.string;
4172 if (cnst->conste.v.character.size != 1) {
4173 if (warning.multichar && (c_mode & _GNUC)) {
4175 warningf(HERE, "multi-character character constant");
4177 errorf(HERE, "more than 1 characters in character constant");
4186 * Parse a wide character constant.
4188 static expression_t *parse_wide_character_constant(void)
4190 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4192 cnst->base.source_position = HERE;
4193 cnst->base.type = token.datatype;
4194 cnst->conste.v.wide_character = token.v.wide_string;
4196 if (cnst->conste.v.wide_character.size != 1) {
4197 if (warning.multichar && (c_mode & _GNUC)) {
4199 warningf(HERE, "multi-character character constant");
4201 errorf(HERE, "more than 1 characters in character constant");
4210 * Parse a float constant.
4212 static expression_t *parse_float_const(void)
4214 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4215 cnst->base.type = token.datatype;
4216 cnst->conste.v.float_value = token.v.floatvalue;
4223 static declaration_t *create_implicit_function(symbol_t *symbol,
4224 const source_position_t source_position)
4226 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4227 ntype->function.return_type = type_int;
4228 ntype->function.unspecified_parameters = true;
4230 type_t *type = typehash_insert(ntype);
4235 declaration_t *const declaration = allocate_declaration_zero();
4236 declaration->storage_class = STORAGE_CLASS_EXTERN;
4237 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4238 declaration->type = type;
4239 declaration->symbol = symbol;
4240 declaration->source_position = source_position;
4241 declaration->parent_scope = global_scope;
4243 scope_t *old_scope = scope;
4244 set_scope(global_scope);
4246 environment_push(declaration);
4247 /* prepends the declaration to the global declarations list */
4248 declaration->next = scope->declarations;
4249 scope->declarations = declaration;
4251 assert(scope == global_scope);
4252 set_scope(old_scope);
4258 * Creates a return_type (func)(argument_type) function type if not
4261 * @param return_type the return type
4262 * @param argument_type the argument type
4264 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4266 function_parameter_t *parameter
4267 = obstack_alloc(type_obst, sizeof(parameter[0]));
4268 memset(parameter, 0, sizeof(parameter[0]));
4269 parameter->type = argument_type;
4271 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4272 type->function.return_type = return_type;
4273 type->function.parameters = parameter;
4275 type_t *result = typehash_insert(type);
4276 if(result != type) {
4284 * Creates a function type for some function like builtins.
4286 * @param symbol the symbol describing the builtin
4288 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4290 switch(symbol->ID) {
4291 case T___builtin_alloca:
4292 return make_function_1_type(type_void_ptr, type_size_t);
4293 case T___builtin_nan:
4294 return make_function_1_type(type_double, type_char_ptr);
4295 case T___builtin_nanf:
4296 return make_function_1_type(type_float, type_char_ptr);
4297 case T___builtin_nand:
4298 return make_function_1_type(type_long_double, type_char_ptr);
4299 case T___builtin_va_end:
4300 return make_function_1_type(type_void, type_valist);
4302 internal_errorf(HERE, "not implemented builtin symbol found");
4307 * Performs automatic type cast as described in § 6.3.2.1.
4309 * @param orig_type the original type
4311 static type_t *automatic_type_conversion(type_t *orig_type)
4313 type_t *type = skip_typeref(orig_type);
4314 if(is_type_array(type)) {
4315 array_type_t *array_type = &type->array;
4316 type_t *element_type = array_type->element_type;
4317 unsigned qualifiers = array_type->type.qualifiers;
4319 return make_pointer_type(element_type, qualifiers);
4322 if(is_type_function(type)) {
4323 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4330 * reverts the automatic casts of array to pointer types and function
4331 * to function-pointer types as defined § 6.3.2.1
4333 type_t *revert_automatic_type_conversion(const expression_t *expression)
4335 switch (expression->kind) {
4336 case EXPR_REFERENCE: return expression->reference.declaration->type;
4337 case EXPR_SELECT: return expression->select.compound_entry->type;
4339 case EXPR_UNARY_DEREFERENCE: {
4340 const expression_t *const value = expression->unary.value;
4341 type_t *const type = skip_typeref(value->base.type);
4342 assert(is_type_pointer(type));
4343 return type->pointer.points_to;
4346 case EXPR_BUILTIN_SYMBOL:
4347 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4349 case EXPR_ARRAY_ACCESS: {
4350 const expression_t *array_ref = expression->array_access.array_ref;
4351 type_t *type_left = skip_typeref(array_ref->base.type);
4352 if (!is_type_valid(type_left))
4354 assert(is_type_pointer(type_left));
4355 return type_left->pointer.points_to;
4358 case EXPR_STRING_LITERAL: {
4359 size_t size = expression->string.value.size;
4360 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4363 case EXPR_WIDE_STRING_LITERAL: {
4364 size_t size = expression->wide_string.value.size;
4365 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4368 case EXPR_COMPOUND_LITERAL:
4369 return expression->compound_literal.type;
4374 return expression->base.type;
4377 static expression_t *parse_reference(void)
4379 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4381 reference_expression_t *ref = &expression->reference;
4382 ref->symbol = token.v.symbol;
4384 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4386 source_position_t source_position = token.source_position;
4389 if(declaration == NULL) {
4390 if (! strict_mode && token.type == '(') {
4391 /* an implicitly defined function */
4392 if (warning.implicit_function_declaration) {
4393 warningf(HERE, "implicit declaration of function '%Y'",
4397 declaration = create_implicit_function(ref->symbol,
4400 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4401 return create_invalid_expression();
4405 type_t *type = declaration->type;
4407 /* we always do the auto-type conversions; the & and sizeof parser contains
4408 * code to revert this! */
4409 type = automatic_type_conversion(type);
4411 ref->declaration = declaration;
4412 ref->base.type = type;
4414 /* this declaration is used */
4415 declaration->used = true;
4417 /* check for deprecated functions */
4418 if(declaration->deprecated != 0) {
4419 const char *prefix = "";
4420 if (is_type_function(declaration->type))
4421 prefix = "function ";
4423 if (declaration->deprecated_string != NULL) {
4424 warningf(source_position,
4425 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4426 declaration->deprecated_string);
4428 warningf(source_position,
4429 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4436 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4440 /* TODO check if explicit cast is allowed and issue warnings/errors */
4443 static expression_t *parse_compound_literal(type_t *type)
4445 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4447 parse_initializer_env_t env;
4449 env.declaration = NULL;
4450 env.must_be_constant = false;
4451 initializer_t *initializer = parse_initializer(&env);
4454 expression->compound_literal.initializer = initializer;
4455 expression->compound_literal.type = type;
4456 expression->base.type = automatic_type_conversion(type);
4462 * Parse a cast expression.
4464 static expression_t *parse_cast(void)
4466 source_position_t source_position = token.source_position;
4468 type_t *type = parse_typename();
4470 /* matching add_anchor_token() is at call site */
4471 rem_anchor_token(')');
4474 if(token.type == '{') {
4475 return parse_compound_literal(type);
4478 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4479 cast->base.source_position = source_position;
4481 expression_t *value = parse_sub_expression(20);
4483 check_cast_allowed(value, type);
4485 cast->base.type = type;
4486 cast->unary.value = value;
4490 return create_invalid_expression();
4494 * Parse a statement expression.
4496 static expression_t *parse_statement_expression(void)
4498 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4500 statement_t *statement = parse_compound_statement();
4501 expression->statement.statement = statement;
4502 expression->base.source_position = statement->base.source_position;
4504 /* find last statement and use its type */
4505 type_t *type = type_void;
4506 const statement_t *stmt = statement->compound.statements;
4508 while (stmt->base.next != NULL)
4509 stmt = stmt->base.next;
4511 if (stmt->kind == STATEMENT_EXPRESSION) {
4512 type = stmt->expression.expression->base.type;
4515 warningf(expression->base.source_position, "empty statement expression ({})");
4517 expression->base.type = type;
4523 return create_invalid_expression();
4527 * Parse a braced expression.
4529 static expression_t *parse_brace_expression(void)
4532 add_anchor_token(')');
4534 switch(token.type) {
4536 /* gcc extension: a statement expression */
4537 return parse_statement_expression();
4541 return parse_cast();
4543 if(is_typedef_symbol(token.v.symbol)) {
4544 return parse_cast();
4548 expression_t *result = parse_expression();
4549 rem_anchor_token(')');
4554 return create_invalid_expression();
4557 static expression_t *parse_function_keyword(void)
4562 if (current_function == NULL) {
4563 errorf(HERE, "'__func__' used outside of a function");
4566 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4567 expression->base.type = type_char_ptr;
4568 expression->funcname.kind = FUNCNAME_FUNCTION;
4573 static expression_t *parse_pretty_function_keyword(void)
4575 eat(T___PRETTY_FUNCTION__);
4577 if (current_function == NULL) {
4578 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4581 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4582 expression->base.type = type_char_ptr;
4583 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
4588 static expression_t *parse_funcsig_keyword(void)
4592 if (current_function == NULL) {
4593 errorf(HERE, "'__FUNCSIG__' used outside of a function");
4596 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4597 expression->base.type = type_char_ptr;
4598 expression->funcname.kind = FUNCNAME_FUNCSIG;
4603 static expression_t *parse_funcdname_keyword(void)
4605 eat(T___FUNCDNAME__);
4607 if (current_function == NULL) {
4608 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
4611 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4612 expression->base.type = type_char_ptr;
4613 expression->funcname.kind = FUNCNAME_FUNCDNAME;
4618 static designator_t *parse_designator(void)
4620 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4621 result->source_position = HERE;
4623 if(token.type != T_IDENTIFIER) {
4624 parse_error_expected("while parsing member designator",
4628 result->symbol = token.v.symbol;
4631 designator_t *last_designator = result;
4633 if(token.type == '.') {
4635 if(token.type != T_IDENTIFIER) {
4636 parse_error_expected("while parsing member designator",
4640 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4641 designator->source_position = HERE;
4642 designator->symbol = token.v.symbol;
4645 last_designator->next = designator;
4646 last_designator = designator;
4649 if(token.type == '[') {
4651 add_anchor_token(']');
4652 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4653 designator->source_position = HERE;
4654 designator->array_index = parse_expression();
4655 rem_anchor_token(']');
4657 if(designator->array_index == NULL) {
4661 last_designator->next = designator;
4662 last_designator = designator;
4674 * Parse the __builtin_offsetof() expression.
4676 static expression_t *parse_offsetof(void)
4678 eat(T___builtin_offsetof);
4680 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4681 expression->base.type = type_size_t;
4684 add_anchor_token(',');
4685 type_t *type = parse_typename();
4686 rem_anchor_token(',');
4688 add_anchor_token(')');
4689 designator_t *designator = parse_designator();
4690 rem_anchor_token(')');
4693 expression->offsetofe.type = type;
4694 expression->offsetofe.designator = designator;
4697 memset(&path, 0, sizeof(path));
4698 path.top_type = type;
4699 path.path = NEW_ARR_F(type_path_entry_t, 0);
4701 descend_into_subtype(&path);
4703 if(!walk_designator(&path, designator, true)) {
4704 return create_invalid_expression();
4707 DEL_ARR_F(path.path);
4711 return create_invalid_expression();
4715 * Parses a _builtin_va_start() expression.
4717 static expression_t *parse_va_start(void)
4719 eat(T___builtin_va_start);
4721 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4724 add_anchor_token(',');
4725 expression->va_starte.ap = parse_assignment_expression();
4726 rem_anchor_token(',');
4728 expression_t *const expr = parse_assignment_expression();
4729 if (expr->kind == EXPR_REFERENCE) {
4730 declaration_t *const decl = expr->reference.declaration;
4732 return create_invalid_expression();
4733 if (decl->parent_scope == ¤t_function->scope &&
4734 decl->next == NULL) {
4735 expression->va_starte.parameter = decl;
4740 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4742 return create_invalid_expression();
4746 * Parses a _builtin_va_arg() expression.
4748 static expression_t *parse_va_arg(void)
4750 eat(T___builtin_va_arg);
4752 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4755 expression->va_arge.ap = parse_assignment_expression();
4757 expression->base.type = parse_typename();
4762 return create_invalid_expression();
4765 static expression_t *parse_builtin_symbol(void)
4767 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4769 symbol_t *symbol = token.v.symbol;
4771 expression->builtin_symbol.symbol = symbol;
4774 type_t *type = get_builtin_symbol_type(symbol);
4775 type = automatic_type_conversion(type);
4777 expression->base.type = type;
4782 * Parses a __builtin_constant() expression.
4784 static expression_t *parse_builtin_constant(void)
4786 eat(T___builtin_constant_p);
4788 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4791 add_anchor_token(')');
4792 expression->builtin_constant.value = parse_assignment_expression();
4793 rem_anchor_token(')');
4795 expression->base.type = type_int;
4799 return create_invalid_expression();
4803 * Parses a __builtin_prefetch() expression.
4805 static expression_t *parse_builtin_prefetch(void)
4807 eat(T___builtin_prefetch);
4809 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4812 add_anchor_token(')');
4813 expression->builtin_prefetch.adr = parse_assignment_expression();
4814 if (token.type == ',') {
4816 expression->builtin_prefetch.rw = parse_assignment_expression();
4818 if (token.type == ',') {
4820 expression->builtin_prefetch.locality = parse_assignment_expression();
4822 rem_anchor_token(')');
4824 expression->base.type = type_void;
4828 return create_invalid_expression();
4832 * Parses a __builtin_is_*() compare expression.
4834 static expression_t *parse_compare_builtin(void)
4836 expression_t *expression;
4838 switch(token.type) {
4839 case T___builtin_isgreater:
4840 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4842 case T___builtin_isgreaterequal:
4843 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4845 case T___builtin_isless:
4846 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4848 case T___builtin_islessequal:
4849 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4851 case T___builtin_islessgreater:
4852 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4854 case T___builtin_isunordered:
4855 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4858 internal_errorf(HERE, "invalid compare builtin found");
4861 expression->base.source_position = HERE;
4865 expression->binary.left = parse_assignment_expression();
4867 expression->binary.right = parse_assignment_expression();
4870 type_t *const orig_type_left = expression->binary.left->base.type;
4871 type_t *const orig_type_right = expression->binary.right->base.type;
4873 type_t *const type_left = skip_typeref(orig_type_left);
4874 type_t *const type_right = skip_typeref(orig_type_right);
4875 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4876 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4877 type_error_incompatible("invalid operands in comparison",
4878 expression->base.source_position, orig_type_left, orig_type_right);
4881 semantic_comparison(&expression->binary);
4886 return create_invalid_expression();
4890 * Parses a __builtin_expect() expression.
4892 static expression_t *parse_builtin_expect(void)
4894 eat(T___builtin_expect);
4896 expression_t *expression
4897 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4900 expression->binary.left = parse_assignment_expression();
4902 expression->binary.right = parse_constant_expression();
4905 expression->base.type = expression->binary.left->base.type;
4909 return create_invalid_expression();
4913 * Parses a MS assume() expression.
4915 static expression_t *parse_assume(void) {
4918 expression_t *expression
4919 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4922 add_anchor_token(')');
4923 expression->unary.value = parse_assignment_expression();
4924 rem_anchor_token(')');
4927 expression->base.type = type_void;
4930 return create_invalid_expression();
4934 * Parse a microsoft __noop expression.
4936 static expression_t *parse_noop_expression(void) {
4937 source_position_t source_position = HERE;
4940 if (token.type == '(') {
4941 /* parse arguments */
4943 add_anchor_token(')');
4944 add_anchor_token(',');
4946 if(token.type != ')') {
4948 (void)parse_assignment_expression();
4949 if(token.type != ',')
4955 rem_anchor_token(',');
4956 rem_anchor_token(')');
4959 /* the result is a (int)0 */
4960 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4961 cnst->base.source_position = source_position;
4962 cnst->base.type = type_int;
4963 cnst->conste.v.int_value = 0;
4964 cnst->conste.is_ms_noop = true;
4969 return create_invalid_expression();
4973 * Parses a primary expression.
4975 static expression_t *parse_primary_expression(void)
4977 switch (token.type) {
4978 case T_INTEGER: return parse_int_const();
4979 case T_CHARACTER_CONSTANT: return parse_character_constant();
4980 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4981 case T_FLOATINGPOINT: return parse_float_const();
4982 case T_STRING_LITERAL:
4983 case T_WIDE_STRING_LITERAL: return parse_string_const();
4984 case T_IDENTIFIER: return parse_reference();
4985 case T___FUNCTION__:
4986 case T___func__: return parse_function_keyword();
4987 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4988 case T___FUNCSIG__: return parse_funcsig_keyword();
4989 case T___FUNCDNAME__: return parse_funcdname_keyword();
4990 case T___builtin_offsetof: return parse_offsetof();
4991 case T___builtin_va_start: return parse_va_start();
4992 case T___builtin_va_arg: return parse_va_arg();
4993 case T___builtin_expect: return parse_builtin_expect();
4994 case T___builtin_alloca:
4995 case T___builtin_nan:
4996 case T___builtin_nand:
4997 case T___builtin_nanf:
4998 case T___builtin_va_end: return parse_builtin_symbol();
4999 case T___builtin_isgreater:
5000 case T___builtin_isgreaterequal:
5001 case T___builtin_isless:
5002 case T___builtin_islessequal:
5003 case T___builtin_islessgreater:
5004 case T___builtin_isunordered: return parse_compare_builtin();
5005 case T___builtin_constant_p: return parse_builtin_constant();
5006 case T___builtin_prefetch: return parse_builtin_prefetch();
5007 case T__assume: return parse_assume();
5009 case '(': return parse_brace_expression();
5010 case T___noop: return parse_noop_expression();
5013 errorf(HERE, "unexpected token %K, expected an expression", &token);
5014 return create_invalid_expression();
5018 * Check if the expression has the character type and issue a warning then.
5020 static void check_for_char_index_type(const expression_t *expression) {
5021 type_t *const type = expression->base.type;
5022 const type_t *const base_type = skip_typeref(type);
5024 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5025 warning.char_subscripts) {
5026 warningf(expression->base.source_position,
5027 "array subscript has type '%T'", type);
5031 static expression_t *parse_array_expression(unsigned precedence,
5037 add_anchor_token(']');
5039 expression_t *inside = parse_expression();
5041 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5043 array_access_expression_t *array_access = &expression->array_access;
5045 type_t *const orig_type_left = left->base.type;
5046 type_t *const orig_type_inside = inside->base.type;
5048 type_t *const type_left = skip_typeref(orig_type_left);
5049 type_t *const type_inside = skip_typeref(orig_type_inside);
5051 type_t *return_type;
5052 if (is_type_pointer(type_left)) {
5053 return_type = type_left->pointer.points_to;
5054 array_access->array_ref = left;
5055 array_access->index = inside;
5056 check_for_char_index_type(inside);
5057 } else if (is_type_pointer(type_inside)) {
5058 return_type = type_inside->pointer.points_to;
5059 array_access->array_ref = inside;
5060 array_access->index = left;
5061 array_access->flipped = true;
5062 check_for_char_index_type(left);
5064 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5066 "array access on object with non-pointer types '%T', '%T'",
5067 orig_type_left, orig_type_inside);
5069 return_type = type_error_type;
5070 array_access->array_ref = create_invalid_expression();
5073 rem_anchor_token(']');
5074 if(token.type != ']') {
5075 parse_error_expected("Problem while parsing array access", ']', 0);
5080 return_type = automatic_type_conversion(return_type);
5081 expression->base.type = return_type;
5086 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
5088 expression_t *tp_expression = allocate_expression_zero(kind);
5089 tp_expression->base.type = type_size_t;
5091 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5093 add_anchor_token(')');
5094 tp_expression->typeprop.type = parse_typename();
5095 rem_anchor_token(')');
5098 expression_t *expression = parse_sub_expression(precedence);
5099 expression->base.type = revert_automatic_type_conversion(expression);
5101 tp_expression->typeprop.type = expression->base.type;
5102 tp_expression->typeprop.tp_expression = expression;
5105 return tp_expression;
5107 return create_invalid_expression();
5110 static expression_t *parse_sizeof(unsigned precedence)
5113 return parse_typeprop(EXPR_SIZEOF, precedence);
5116 static expression_t *parse_alignof(unsigned precedence)
5119 return parse_typeprop(EXPR_SIZEOF, precedence);
5122 static expression_t *parse_select_expression(unsigned precedence,
5123 expression_t *compound)
5126 assert(token.type == '.' || token.type == T_MINUSGREATER);
5128 bool is_pointer = (token.type == T_MINUSGREATER);
5131 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5132 select->select.compound = compound;
5134 if(token.type != T_IDENTIFIER) {
5135 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5138 symbol_t *symbol = token.v.symbol;
5139 select->select.symbol = symbol;
5142 type_t *const orig_type = compound->base.type;
5143 type_t *const type = skip_typeref(orig_type);
5145 type_t *type_left = type;
5147 if (!is_type_pointer(type)) {
5148 if (is_type_valid(type)) {
5149 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5151 return create_invalid_expression();
5153 type_left = type->pointer.points_to;
5155 type_left = skip_typeref(type_left);
5157 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5158 type_left->kind != TYPE_COMPOUND_UNION) {
5159 if (is_type_valid(type_left)) {
5160 errorf(HERE, "request for member '%Y' in something not a struct or "
5161 "union, but '%T'", symbol, type_left);
5163 return create_invalid_expression();
5166 declaration_t *const declaration = type_left->compound.declaration;
5168 if(!declaration->init.is_defined) {
5169 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5171 return create_invalid_expression();
5174 declaration_t *iter = find_compound_entry(declaration, symbol);
5176 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5177 return create_invalid_expression();
5180 /* we always do the auto-type conversions; the & and sizeof parser contains
5181 * code to revert this! */
5182 type_t *expression_type = automatic_type_conversion(iter->type);
5184 select->select.compound_entry = iter;
5185 select->base.type = expression_type;
5187 if(expression_type->kind == TYPE_BITFIELD) {
5188 expression_t *extract
5189 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5190 extract->unary.value = select;
5191 extract->base.type = expression_type->bitfield.base;
5200 * Parse a call expression, ie. expression '( ... )'.
5202 * @param expression the function address
5204 static expression_t *parse_call_expression(unsigned precedence,
5205 expression_t *expression)
5208 expression_t *result = allocate_expression_zero(EXPR_CALL);
5209 result->base.source_position = expression->base.source_position;
5211 call_expression_t *call = &result->call;
5212 call->function = expression;
5214 type_t *const orig_type = expression->base.type;
5215 type_t *const type = skip_typeref(orig_type);
5217 function_type_t *function_type = NULL;
5218 if (is_type_pointer(type)) {
5219 type_t *const to_type = skip_typeref(type->pointer.points_to);
5221 if (is_type_function(to_type)) {
5222 function_type = &to_type->function;
5223 call->base.type = function_type->return_type;
5227 if (function_type == NULL && is_type_valid(type)) {
5228 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5231 /* parse arguments */
5233 add_anchor_token(')');
5234 add_anchor_token(',');
5236 if(token.type != ')') {
5237 call_argument_t *last_argument = NULL;
5240 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5242 argument->expression = parse_assignment_expression();
5243 if(last_argument == NULL) {
5244 call->arguments = argument;
5246 last_argument->next = argument;
5248 last_argument = argument;
5250 if(token.type != ',')
5255 rem_anchor_token(',');
5256 rem_anchor_token(')');
5259 if(function_type != NULL) {
5260 function_parameter_t *parameter = function_type->parameters;
5261 call_argument_t *argument = call->arguments;
5262 for( ; parameter != NULL && argument != NULL;
5263 parameter = parameter->next, argument = argument->next) {
5264 type_t *expected_type = parameter->type;
5265 /* TODO report scope in error messages */
5266 expression_t *const arg_expr = argument->expression;
5267 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
5268 if (res_type == NULL) {
5269 /* TODO improve error message */
5270 errorf(arg_expr->base.source_position,
5271 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5272 arg_expr, arg_expr->base.type, expected_type);
5274 argument->expression = create_implicit_cast(argument->expression, expected_type);
5277 /* too few parameters */
5278 if(parameter != NULL) {
5279 errorf(HERE, "too few arguments to function '%E'", expression);
5280 } else if(argument != NULL) {
5281 /* too many parameters */
5282 if(!function_type->variadic
5283 && !function_type->unspecified_parameters) {
5284 errorf(HERE, "too many arguments to function '%E'", expression);
5286 /* do default promotion */
5287 for( ; argument != NULL; argument = argument->next) {
5288 type_t *type = argument->expression->base.type;
5290 type = skip_typeref(type);
5291 if(is_type_integer(type)) {
5292 type = promote_integer(type);
5293 } else if(type == type_float) {
5297 argument->expression
5298 = create_implicit_cast(argument->expression, type);
5301 check_format(&result->call);
5304 check_format(&result->call);
5310 return create_invalid_expression();
5313 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5315 static bool same_compound_type(const type_t *type1, const type_t *type2)
5318 is_type_compound(type1) &&
5319 type1->kind == type2->kind &&
5320 type1->compound.declaration == type2->compound.declaration;
5324 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5326 * @param expression the conditional expression
5328 static expression_t *parse_conditional_expression(unsigned precedence,
5329 expression_t *expression)
5332 add_anchor_token(':');
5334 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5336 conditional_expression_t *conditional = &result->conditional;
5337 conditional->condition = expression;
5340 type_t *const condition_type_orig = expression->base.type;
5341 type_t *const condition_type = skip_typeref(condition_type_orig);
5342 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5343 type_error("expected a scalar type in conditional condition",
5344 expression->base.source_position, condition_type_orig);
5347 expression_t *true_expression = parse_expression();
5348 rem_anchor_token(':');
5350 expression_t *false_expression = parse_sub_expression(precedence);
5352 type_t *const orig_true_type = true_expression->base.type;
5353 type_t *const orig_false_type = false_expression->base.type;
5354 type_t *const true_type = skip_typeref(orig_true_type);
5355 type_t *const false_type = skip_typeref(orig_false_type);
5358 type_t *result_type;
5359 if(is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
5360 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5361 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
5362 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
5363 warningf(expression->base.source_position,
5364 "ISO C forbids conditional expression with only one void side");
5366 result_type = type_void;
5367 } else if (is_type_arithmetic(true_type)
5368 && is_type_arithmetic(false_type)) {
5369 result_type = semantic_arithmetic(true_type, false_type);
5371 true_expression = create_implicit_cast(true_expression, result_type);
5372 false_expression = create_implicit_cast(false_expression, result_type);
5374 conditional->true_expression = true_expression;
5375 conditional->false_expression = false_expression;
5376 conditional->base.type = result_type;
5377 } else if (same_compound_type(true_type, false_type)) {
5378 /* just take 1 of the 2 types */
5379 result_type = true_type;
5380 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
5381 type_t *pointer_type;
5383 expression_t *other_expression;
5384 if (is_type_pointer(true_type)) {
5385 pointer_type = true_type;
5386 other_type = false_type;
5387 other_expression = false_expression;
5389 pointer_type = false_type;
5390 other_type = true_type;
5391 other_expression = true_expression;
5394 if(is_type_pointer(other_type)) {
5395 if(!pointers_compatible(true_type, false_type)) {
5396 warningf(expression->base.source_position,
5397 "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
5399 result_type = true_type;
5400 } else if(is_null_pointer_constant(other_expression)) {
5401 result_type = pointer_type;
5402 } else if(is_type_integer(other_type)) {
5403 warningf(expression->base.source_position,
5404 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
5405 result_type = pointer_type;
5407 type_error_incompatible("while parsing conditional",
5408 expression->base.source_position, true_type, false_type);
5409 result_type = type_error_type;
5412 /* TODO: one pointer to void*, other some pointer */
5414 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5415 type_error_incompatible("while parsing conditional",
5416 expression->base.source_position, true_type,
5419 result_type = type_error_type;
5422 conditional->true_expression
5423 = create_implicit_cast(true_expression, result_type);
5424 conditional->false_expression
5425 = create_implicit_cast(false_expression, result_type);
5426 conditional->base.type = result_type;
5429 return create_invalid_expression();
5433 * Parse an extension expression.
5435 static expression_t *parse_extension(unsigned precedence)
5437 eat(T___extension__);
5439 /* TODO enable extensions */
5440 expression_t *expression = parse_sub_expression(precedence);
5441 /* TODO disable extensions */
5446 * Parse a __builtin_classify_type() expression.
5448 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5450 eat(T___builtin_classify_type);
5452 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5453 result->base.type = type_int;
5456 add_anchor_token(')');
5457 expression_t *expression = parse_sub_expression(precedence);
5458 rem_anchor_token(')');
5460 result->classify_type.type_expression = expression;
5464 return create_invalid_expression();
5467 static void semantic_incdec(unary_expression_t *expression)
5469 type_t *const orig_type = expression->value->base.type;
5470 type_t *const type = skip_typeref(orig_type);
5471 /* TODO !is_type_real && !is_type_pointer */
5472 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5473 if (is_type_valid(type)) {
5474 /* TODO: improve error message */
5475 errorf(HERE, "operation needs an arithmetic or pointer type");
5480 expression->base.type = orig_type;
5483 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5485 type_t *const orig_type = expression->value->base.type;
5486 type_t *const type = skip_typeref(orig_type);
5487 if(!is_type_arithmetic(type)) {
5488 if (is_type_valid(type)) {
5489 /* TODO: improve error message */
5490 errorf(HERE, "operation needs an arithmetic type");
5495 expression->base.type = orig_type;
5498 static void semantic_unexpr_scalar(unary_expression_t *expression)
5500 type_t *const orig_type = expression->value->base.type;
5501 type_t *const type = skip_typeref(orig_type);
5502 if (!is_type_scalar(type)) {
5503 if (is_type_valid(type)) {
5504 errorf(HERE, "operand of ! must be of scalar type");
5509 expression->base.type = orig_type;
5512 static void semantic_unexpr_integer(unary_expression_t *expression)
5514 type_t *const orig_type = expression->value->base.type;
5515 type_t *const type = skip_typeref(orig_type);
5516 if (!is_type_integer(type)) {
5517 if (is_type_valid(type)) {
5518 errorf(HERE, "operand of ~ must be of integer type");
5523 expression->base.type = orig_type;
5526 static void semantic_dereference(unary_expression_t *expression)
5528 type_t *const orig_type = expression->value->base.type;
5529 type_t *const type = skip_typeref(orig_type);
5530 if(!is_type_pointer(type)) {
5531 if (is_type_valid(type)) {
5532 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5537 type_t *result_type = type->pointer.points_to;
5538 result_type = automatic_type_conversion(result_type);
5539 expression->base.type = result_type;
5543 * Check the semantic of the address taken expression.
5545 static void semantic_take_addr(unary_expression_t *expression)
5547 expression_t *value = expression->value;
5548 value->base.type = revert_automatic_type_conversion(value);
5550 type_t *orig_type = value->base.type;
5551 if(!is_type_valid(orig_type))
5554 if(value->kind == EXPR_REFERENCE) {
5555 declaration_t *const declaration = value->reference.declaration;
5556 if(declaration != NULL) {
5557 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5558 errorf(expression->base.source_position,
5559 "address of register variable '%Y' requested",
5560 declaration->symbol);
5562 declaration->address_taken = 1;
5566 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5569 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5570 static expression_t *parse_##unexpression_type(unsigned precedence) \
5574 expression_t *unary_expression \
5575 = allocate_expression_zero(unexpression_type); \
5576 unary_expression->base.source_position = HERE; \
5577 unary_expression->unary.value = parse_sub_expression(precedence); \
5579 sfunc(&unary_expression->unary); \
5581 return unary_expression; \
5584 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5585 semantic_unexpr_arithmetic)
5586 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5587 semantic_unexpr_arithmetic)
5588 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5589 semantic_unexpr_scalar)
5590 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5591 semantic_dereference)
5592 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5594 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5595 semantic_unexpr_integer)
5596 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5598 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5601 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5603 static expression_t *parse_##unexpression_type(unsigned precedence, \
5604 expression_t *left) \
5606 (void) precedence; \
5609 expression_t *unary_expression \
5610 = allocate_expression_zero(unexpression_type); \
5611 unary_expression->unary.value = left; \
5613 sfunc(&unary_expression->unary); \
5615 return unary_expression; \
5618 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5619 EXPR_UNARY_POSTFIX_INCREMENT,
5621 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5622 EXPR_UNARY_POSTFIX_DECREMENT,
5625 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5627 /* TODO: handle complex + imaginary types */
5629 /* § 6.3.1.8 Usual arithmetic conversions */
5630 if(type_left == type_long_double || type_right == type_long_double) {
5631 return type_long_double;
5632 } else if(type_left == type_double || type_right == type_double) {
5634 } else if(type_left == type_float || type_right == type_float) {
5638 type_right = promote_integer(type_right);
5639 type_left = promote_integer(type_left);
5641 if(type_left == type_right)
5644 bool signed_left = is_type_signed(type_left);
5645 bool signed_right = is_type_signed(type_right);
5646 int rank_left = get_rank(type_left);
5647 int rank_right = get_rank(type_right);
5648 if(rank_left < rank_right) {
5649 if(signed_left == signed_right || !signed_right) {
5655 if(signed_left == signed_right || !signed_left) {
5664 * Check the semantic restrictions for a binary expression.
5666 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5668 expression_t *const left = expression->left;
5669 expression_t *const right = expression->right;
5670 type_t *const orig_type_left = left->base.type;
5671 type_t *const orig_type_right = right->base.type;
5672 type_t *const type_left = skip_typeref(orig_type_left);
5673 type_t *const type_right = skip_typeref(orig_type_right);
5675 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5676 /* TODO: improve error message */
5677 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5678 errorf(HERE, "operation needs arithmetic types");
5683 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5684 expression->left = create_implicit_cast(left, arithmetic_type);
5685 expression->right = create_implicit_cast(right, arithmetic_type);
5686 expression->base.type = arithmetic_type;
5689 static void semantic_shift_op(binary_expression_t *expression)
5691 expression_t *const left = expression->left;
5692 expression_t *const right = expression->right;
5693 type_t *const orig_type_left = left->base.type;
5694 type_t *const orig_type_right = right->base.type;
5695 type_t * type_left = skip_typeref(orig_type_left);
5696 type_t * type_right = skip_typeref(orig_type_right);
5698 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5699 /* TODO: improve error message */
5700 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5701 errorf(HERE, "operation needs integer types");
5706 type_left = promote_integer(type_left);
5707 type_right = promote_integer(type_right);
5709 expression->left = create_implicit_cast(left, type_left);
5710 expression->right = create_implicit_cast(right, type_right);
5711 expression->base.type = type_left;
5714 static void semantic_add(binary_expression_t *expression)
5716 expression_t *const left = expression->left;
5717 expression_t *const right = expression->right;
5718 type_t *const orig_type_left = left->base.type;
5719 type_t *const orig_type_right = right->base.type;
5720 type_t *const type_left = skip_typeref(orig_type_left);
5721 type_t *const type_right = skip_typeref(orig_type_right);
5724 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5725 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5726 expression->left = create_implicit_cast(left, arithmetic_type);
5727 expression->right = create_implicit_cast(right, arithmetic_type);
5728 expression->base.type = arithmetic_type;
5730 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5731 expression->base.type = type_left;
5732 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5733 expression->base.type = type_right;
5734 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5735 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5739 static void semantic_sub(binary_expression_t *expression)
5741 expression_t *const left = expression->left;
5742 expression_t *const right = expression->right;
5743 type_t *const orig_type_left = left->base.type;
5744 type_t *const orig_type_right = right->base.type;
5745 type_t *const type_left = skip_typeref(orig_type_left);
5746 type_t *const type_right = skip_typeref(orig_type_right);
5749 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5750 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5751 expression->left = create_implicit_cast(left, arithmetic_type);
5752 expression->right = create_implicit_cast(right, arithmetic_type);
5753 expression->base.type = arithmetic_type;
5755 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5756 expression->base.type = type_left;
5757 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5758 if(!pointers_compatible(type_left, type_right)) {
5760 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5761 orig_type_left, orig_type_right);
5763 expression->base.type = type_ptrdiff_t;
5765 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5766 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5767 orig_type_left, orig_type_right);
5772 * Check the semantics of comparison expressions.
5774 * @param expression The expression to check.
5776 static void semantic_comparison(binary_expression_t *expression)
5778 expression_t *left = expression->left;
5779 expression_t *right = expression->right;
5780 type_t *orig_type_left = left->base.type;
5781 type_t *orig_type_right = right->base.type;
5783 type_t *type_left = skip_typeref(orig_type_left);
5784 type_t *type_right = skip_typeref(orig_type_right);
5786 /* TODO non-arithmetic types */
5787 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5788 if (warning.sign_compare &&
5789 (expression->base.kind != EXPR_BINARY_EQUAL &&
5790 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5791 (is_type_signed(type_left) != is_type_signed(type_right))) {
5792 warningf(expression->base.source_position,
5793 "comparison between signed and unsigned");
5795 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5796 expression->left = create_implicit_cast(left, arithmetic_type);
5797 expression->right = create_implicit_cast(right, arithmetic_type);
5798 expression->base.type = arithmetic_type;
5799 if (warning.float_equal &&
5800 (expression->base.kind == EXPR_BINARY_EQUAL ||
5801 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5802 is_type_float(arithmetic_type)) {
5803 warningf(expression->base.source_position,
5804 "comparing floating point with == or != is unsafe");
5806 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5807 /* TODO check compatibility */
5808 } else if (is_type_pointer(type_left)) {
5809 expression->right = create_implicit_cast(right, type_left);
5810 } else if (is_type_pointer(type_right)) {
5811 expression->left = create_implicit_cast(left, type_right);
5812 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5813 type_error_incompatible("invalid operands in comparison",
5814 expression->base.source_position,
5815 type_left, type_right);
5817 expression->base.type = type_int;
5820 static void semantic_arithmetic_assign(binary_expression_t *expression)
5822 expression_t *left = expression->left;
5823 expression_t *right = expression->right;
5824 type_t *orig_type_left = left->base.type;
5825 type_t *orig_type_right = right->base.type;
5827 type_t *type_left = skip_typeref(orig_type_left);
5828 type_t *type_right = skip_typeref(orig_type_right);
5830 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5831 /* TODO: improve error message */
5832 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5833 errorf(HERE, "operation needs arithmetic types");
5838 /* combined instructions are tricky. We can't create an implicit cast on
5839 * the left side, because we need the uncasted form for the store.
5840 * The ast2firm pass has to know that left_type must be right_type
5841 * for the arithmetic operation and create a cast by itself */
5842 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5843 expression->right = create_implicit_cast(right, arithmetic_type);
5844 expression->base.type = type_left;
5847 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5849 expression_t *const left = expression->left;
5850 expression_t *const right = expression->right;
5851 type_t *const orig_type_left = left->base.type;
5852 type_t *const orig_type_right = right->base.type;
5853 type_t *const type_left = skip_typeref(orig_type_left);
5854 type_t *const type_right = skip_typeref(orig_type_right);
5856 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5857 /* combined instructions are tricky. We can't create an implicit cast on
5858 * the left side, because we need the uncasted form for the store.
5859 * The ast2firm pass has to know that left_type must be right_type
5860 * for the arithmetic operation and create a cast by itself */
5861 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5862 expression->right = create_implicit_cast(right, arithmetic_type);
5863 expression->base.type = type_left;
5864 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5865 expression->base.type = type_left;
5866 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5867 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5872 * Check the semantic restrictions of a logical expression.
5874 static void semantic_logical_op(binary_expression_t *expression)
5876 expression_t *const left = expression->left;
5877 expression_t *const right = expression->right;
5878 type_t *const orig_type_left = left->base.type;
5879 type_t *const orig_type_right = right->base.type;
5880 type_t *const type_left = skip_typeref(orig_type_left);
5881 type_t *const type_right = skip_typeref(orig_type_right);
5883 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5884 /* TODO: improve error message */
5885 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5886 errorf(HERE, "operation needs scalar types");
5891 expression->base.type = type_int;
5895 * Checks if a compound type has constant fields.
5897 static bool has_const_fields(const compound_type_t *type)
5899 const scope_t *scope = &type->declaration->scope;
5900 const declaration_t *declaration = scope->declarations;
5902 for (; declaration != NULL; declaration = declaration->next) {
5903 if (declaration->namespc != NAMESPACE_NORMAL)
5906 const type_t *decl_type = skip_typeref(declaration->type);
5907 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5915 * Check the semantic restrictions of a binary assign expression.
5917 static void semantic_binexpr_assign(binary_expression_t *expression)
5919 expression_t *left = expression->left;
5920 type_t *orig_type_left = left->base.type;
5922 type_t *type_left = revert_automatic_type_conversion(left);
5923 type_left = skip_typeref(orig_type_left);
5925 /* must be a modifiable lvalue */
5926 if (is_type_array(type_left)) {
5927 errorf(HERE, "cannot assign to arrays ('%E')", left);
5930 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5931 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5935 if(is_type_incomplete(type_left)) {
5937 "left-hand side of assignment '%E' has incomplete type '%T'",
5938 left, orig_type_left);
5941 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5942 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5943 left, orig_type_left);
5947 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5949 if (res_type == NULL) {
5950 errorf(expression->base.source_position,
5951 "cannot assign to '%T' from '%T'",
5952 orig_type_left, expression->right->base.type);
5954 expression->right = create_implicit_cast(expression->right, res_type);
5957 expression->base.type = orig_type_left;
5961 * Determine if the outermost operation (or parts thereof) of the given
5962 * expression has no effect in order to generate a warning about this fact.
5963 * Therefore in some cases this only examines some of the operands of the
5964 * expression (see comments in the function and examples below).
5966 * f() + 23; // warning, because + has no effect
5967 * x || f(); // no warning, because x controls execution of f()
5968 * x ? y : f(); // warning, because y has no effect
5969 * (void)x; // no warning to be able to suppress the warning
5970 * This function can NOT be used for an "expression has definitely no effect"-
5972 static bool expression_has_effect(const expression_t *const expr)
5974 switch (expr->kind) {
5975 case EXPR_UNKNOWN: break;
5976 case EXPR_INVALID: return true; /* do NOT warn */
5977 case EXPR_REFERENCE: return false;
5978 /* suppress the warning for microsoft __noop operations */
5979 case EXPR_CONST: return expr->conste.is_ms_noop;
5980 case EXPR_CHARACTER_CONSTANT: return false;
5981 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5982 case EXPR_STRING_LITERAL: return false;
5983 case EXPR_WIDE_STRING_LITERAL: return false;
5986 const call_expression_t *const call = &expr->call;
5987 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5990 switch (call->function->builtin_symbol.symbol->ID) {
5991 case T___builtin_va_end: return true;
5992 default: return false;
5996 /* Generate the warning if either the left or right hand side of a
5997 * conditional expression has no effect */
5998 case EXPR_CONDITIONAL: {
5999 const conditional_expression_t *const cond = &expr->conditional;
6001 expression_has_effect(cond->true_expression) &&
6002 expression_has_effect(cond->false_expression);
6005 case EXPR_SELECT: return false;
6006 case EXPR_ARRAY_ACCESS: return false;
6007 case EXPR_SIZEOF: return false;
6008 case EXPR_CLASSIFY_TYPE: return false;
6009 case EXPR_ALIGNOF: return false;
6011 case EXPR_FUNCNAME: return false;
6012 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6013 case EXPR_BUILTIN_CONSTANT_P: return false;
6014 case EXPR_BUILTIN_PREFETCH: return true;
6015 case EXPR_OFFSETOF: return false;
6016 case EXPR_VA_START: return true;
6017 case EXPR_VA_ARG: return true;
6018 case EXPR_STATEMENT: return true; // TODO
6019 case EXPR_COMPOUND_LITERAL: return false;
6021 case EXPR_UNARY_NEGATE: return false;
6022 case EXPR_UNARY_PLUS: return false;
6023 case EXPR_UNARY_BITWISE_NEGATE: return false;
6024 case EXPR_UNARY_NOT: return false;
6025 case EXPR_UNARY_DEREFERENCE: return false;
6026 case EXPR_UNARY_TAKE_ADDRESS: return false;
6027 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
6028 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
6029 case EXPR_UNARY_PREFIX_INCREMENT: return true;
6030 case EXPR_UNARY_PREFIX_DECREMENT: return true;
6032 /* Treat void casts as if they have an effect in order to being able to
6033 * suppress the warning */
6034 case EXPR_UNARY_CAST: {
6035 type_t *const type = skip_typeref(expr->base.type);
6036 return is_type_atomic(type, ATOMIC_TYPE_VOID);
6039 case EXPR_UNARY_CAST_IMPLICIT: return true;
6040 case EXPR_UNARY_ASSUME: return true;
6041 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
6043 case EXPR_BINARY_ADD: return false;
6044 case EXPR_BINARY_SUB: return false;
6045 case EXPR_BINARY_MUL: return false;
6046 case EXPR_BINARY_DIV: return false;
6047 case EXPR_BINARY_MOD: return false;
6048 case EXPR_BINARY_EQUAL: return false;
6049 case EXPR_BINARY_NOTEQUAL: return false;
6050 case EXPR_BINARY_LESS: return false;
6051 case EXPR_BINARY_LESSEQUAL: return false;
6052 case EXPR_BINARY_GREATER: return false;
6053 case EXPR_BINARY_GREATEREQUAL: return false;
6054 case EXPR_BINARY_BITWISE_AND: return false;
6055 case EXPR_BINARY_BITWISE_OR: return false;
6056 case EXPR_BINARY_BITWISE_XOR: return false;
6057 case EXPR_BINARY_SHIFTLEFT: return false;
6058 case EXPR_BINARY_SHIFTRIGHT: return false;
6059 case EXPR_BINARY_ASSIGN: return true;
6060 case EXPR_BINARY_MUL_ASSIGN: return true;
6061 case EXPR_BINARY_DIV_ASSIGN: return true;
6062 case EXPR_BINARY_MOD_ASSIGN: return true;
6063 case EXPR_BINARY_ADD_ASSIGN: return true;
6064 case EXPR_BINARY_SUB_ASSIGN: return true;
6065 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
6066 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
6067 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
6068 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
6069 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
6071 /* Only examine the right hand side of && and ||, because the left hand
6072 * side already has the effect of controlling the execution of the right
6074 case EXPR_BINARY_LOGICAL_AND:
6075 case EXPR_BINARY_LOGICAL_OR:
6076 /* Only examine the right hand side of a comma expression, because the left
6077 * hand side has a separate warning */
6078 case EXPR_BINARY_COMMA:
6079 return expression_has_effect(expr->binary.right);
6081 case EXPR_BINARY_BUILTIN_EXPECT: return true;
6082 case EXPR_BINARY_ISGREATER: return false;
6083 case EXPR_BINARY_ISGREATEREQUAL: return false;
6084 case EXPR_BINARY_ISLESS: return false;
6085 case EXPR_BINARY_ISLESSEQUAL: return false;
6086 case EXPR_BINARY_ISLESSGREATER: return false;
6087 case EXPR_BINARY_ISUNORDERED: return false;
6090 internal_errorf(HERE, "unexpected expression");
6093 static void semantic_comma(binary_expression_t *expression)
6095 if (warning.unused_value) {
6096 const expression_t *const left = expression->left;
6097 if (!expression_has_effect(left)) {
6098 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
6101 expression->base.type = expression->right->base.type;
6104 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
6105 static expression_t *parse_##binexpression_type(unsigned precedence, \
6106 expression_t *left) \
6109 source_position_t pos = HERE; \
6111 expression_t *right = parse_sub_expression(precedence + lr); \
6113 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
6114 binexpr->base.source_position = pos; \
6115 binexpr->binary.left = left; \
6116 binexpr->binary.right = right; \
6117 sfunc(&binexpr->binary); \
6122 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
6123 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
6124 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
6125 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
6126 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
6127 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
6128 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
6129 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
6130 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
6132 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
6133 semantic_comparison, 1)
6134 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
6135 semantic_comparison, 1)
6136 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
6137 semantic_comparison, 1)
6138 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
6139 semantic_comparison, 1)
6141 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6142 semantic_binexpr_arithmetic, 1)
6143 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6144 semantic_binexpr_arithmetic, 1)
6145 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6146 semantic_binexpr_arithmetic, 1)
6147 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6148 semantic_logical_op, 1)
6149 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6150 semantic_logical_op, 1)
6151 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6152 semantic_shift_op, 1)
6153 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6154 semantic_shift_op, 1)
6155 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6156 semantic_arithmetic_addsubb_assign, 0)
6157 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6158 semantic_arithmetic_addsubb_assign, 0)
6159 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6160 semantic_arithmetic_assign, 0)
6161 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6162 semantic_arithmetic_assign, 0)
6163 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6164 semantic_arithmetic_assign, 0)
6165 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6166 semantic_arithmetic_assign, 0)
6167 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6168 semantic_arithmetic_assign, 0)
6169 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6170 semantic_arithmetic_assign, 0)
6171 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6172 semantic_arithmetic_assign, 0)
6173 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6174 semantic_arithmetic_assign, 0)
6176 static expression_t *parse_sub_expression(unsigned precedence)
6178 if(token.type < 0) {
6179 return expected_expression_error();
6182 expression_parser_function_t *parser
6183 = &expression_parsers[token.type];
6184 source_position_t source_position = token.source_position;
6187 if(parser->parser != NULL) {
6188 left = parser->parser(parser->precedence);
6190 left = parse_primary_expression();
6192 assert(left != NULL);
6193 left->base.source_position = source_position;
6196 if(token.type < 0) {
6197 return expected_expression_error();
6200 parser = &expression_parsers[token.type];
6201 if(parser->infix_parser == NULL)
6203 if(parser->infix_precedence < precedence)
6206 left = parser->infix_parser(parser->infix_precedence, left);
6208 assert(left != NULL);
6209 assert(left->kind != EXPR_UNKNOWN);
6210 left->base.source_position = source_position;
6217 * Parse an expression.
6219 static expression_t *parse_expression(void)
6221 return parse_sub_expression(1);
6225 * Register a parser for a prefix-like operator with given precedence.
6227 * @param parser the parser function
6228 * @param token_type the token type of the prefix token
6229 * @param precedence the precedence of the operator
6231 static void register_expression_parser(parse_expression_function parser,
6232 int token_type, unsigned precedence)
6234 expression_parser_function_t *entry = &expression_parsers[token_type];
6236 if(entry->parser != NULL) {
6237 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6238 panic("trying to register multiple expression parsers for a token");
6240 entry->parser = parser;
6241 entry->precedence = precedence;
6245 * Register a parser for an infix operator with given precedence.
6247 * @param parser the parser function
6248 * @param token_type the token type of the infix operator
6249 * @param precedence the precedence of the operator
6251 static void register_infix_parser(parse_expression_infix_function parser,
6252 int token_type, unsigned precedence)
6254 expression_parser_function_t *entry = &expression_parsers[token_type];
6256 if(entry->infix_parser != NULL) {
6257 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6258 panic("trying to register multiple infix expression parsers for a "
6261 entry->infix_parser = parser;
6262 entry->infix_precedence = precedence;
6266 * Initialize the expression parsers.
6268 static void init_expression_parsers(void)
6270 memset(&expression_parsers, 0, sizeof(expression_parsers));
6272 register_infix_parser(parse_array_expression, '[', 30);
6273 register_infix_parser(parse_call_expression, '(', 30);
6274 register_infix_parser(parse_select_expression, '.', 30);
6275 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6276 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6278 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6281 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6282 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6283 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6284 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6285 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6286 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6287 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6288 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6289 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6290 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6291 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6292 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6293 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6294 T_EXCLAMATIONMARKEQUAL, 13);
6295 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6296 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6297 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6298 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6299 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6300 register_infix_parser(parse_conditional_expression, '?', 7);
6301 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6302 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6303 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6304 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6305 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6306 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6307 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6308 T_LESSLESSEQUAL, 2);
6309 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6310 T_GREATERGREATEREQUAL, 2);
6311 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6313 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6315 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6318 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6320 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6321 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6322 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6323 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6324 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6325 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6326 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6328 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6330 register_expression_parser(parse_sizeof, T_sizeof, 25);
6331 register_expression_parser(parse_alignof, T___alignof__, 25);
6332 register_expression_parser(parse_extension, T___extension__, 25);
6333 register_expression_parser(parse_builtin_classify_type,
6334 T___builtin_classify_type, 25);
6338 * Parse a asm statement constraints specification.
6340 static asm_constraint_t *parse_asm_constraints(void)
6342 asm_constraint_t *result = NULL;
6343 asm_constraint_t *last = NULL;
6345 while(token.type == T_STRING_LITERAL || token.type == '[') {
6346 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6347 memset(constraint, 0, sizeof(constraint[0]));
6349 if(token.type == '[') {
6351 if(token.type != T_IDENTIFIER) {
6352 parse_error_expected("while parsing asm constraint",
6356 constraint->symbol = token.v.symbol;
6361 constraint->constraints = parse_string_literals();
6363 constraint->expression = parse_expression();
6367 last->next = constraint;
6369 result = constraint;
6373 if(token.type != ',')
6384 * Parse a asm statement clobber specification.
6386 static asm_clobber_t *parse_asm_clobbers(void)
6388 asm_clobber_t *result = NULL;
6389 asm_clobber_t *last = NULL;
6391 while(token.type == T_STRING_LITERAL) {
6392 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6393 clobber->clobber = parse_string_literals();
6396 last->next = clobber;
6402 if(token.type != ',')
6411 * Parse an asm statement.
6413 static statement_t *parse_asm_statement(void)
6417 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6418 statement->base.source_position = token.source_position;
6420 asm_statement_t *asm_statement = &statement->asms;
6422 if(token.type == T_volatile) {
6424 asm_statement->is_volatile = true;
6428 add_anchor_token(')');
6429 add_anchor_token(':');
6430 asm_statement->asm_text = parse_string_literals();
6432 if(token.type != ':') {
6433 rem_anchor_token(':');
6438 asm_statement->inputs = parse_asm_constraints();
6439 if(token.type != ':') {
6440 rem_anchor_token(':');
6445 asm_statement->outputs = parse_asm_constraints();
6446 if(token.type != ':') {
6447 rem_anchor_token(':');
6450 rem_anchor_token(':');
6453 asm_statement->clobbers = parse_asm_clobbers();
6456 rem_anchor_token(')');
6461 return create_invalid_statement();
6465 * Parse a case statement.
6467 static statement_t *parse_case_statement(void)
6471 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6473 statement->base.source_position = token.source_position;
6474 statement->case_label.expression = parse_expression();
6476 if (c_mode & _GNUC) {
6477 if (token.type == T_DOTDOTDOT) {
6479 statement->case_label.end_range = parse_expression();
6485 if (! is_constant_expression(statement->case_label.expression)) {
6486 errorf(statement->base.source_position,
6487 "case label does not reduce to an integer constant");
6489 /* TODO: check if the case label is already known */
6490 if (current_switch != NULL) {
6491 /* link all cases into the switch statement */
6492 if (current_switch->last_case == NULL) {
6493 current_switch->first_case =
6494 current_switch->last_case = &statement->case_label;
6496 current_switch->last_case->next = &statement->case_label;
6499 errorf(statement->base.source_position,
6500 "case label not within a switch statement");
6503 statement->case_label.statement = parse_statement();
6507 return create_invalid_statement();
6511 * Finds an existing default label of a switch statement.
6513 static case_label_statement_t *
6514 find_default_label(const switch_statement_t *statement)
6516 case_label_statement_t *label = statement->first_case;
6517 for ( ; label != NULL; label = label->next) {
6518 if (label->expression == NULL)
6525 * Parse a default statement.
6527 static statement_t *parse_default_statement(void)
6531 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6533 statement->base.source_position = token.source_position;
6536 if (current_switch != NULL) {
6537 const case_label_statement_t *def_label = find_default_label(current_switch);
6538 if (def_label != NULL) {
6539 errorf(HERE, "multiple default labels in one switch");
6540 errorf(def_label->base.source_position,
6541 "this is the first default label");
6543 /* link all cases into the switch statement */
6544 if (current_switch->last_case == NULL) {
6545 current_switch->first_case =
6546 current_switch->last_case = &statement->case_label;
6548 current_switch->last_case->next = &statement->case_label;
6552 errorf(statement->base.source_position,
6553 "'default' label not within a switch statement");
6555 statement->case_label.statement = parse_statement();
6559 return create_invalid_statement();
6563 * Return the declaration for a given label symbol or create a new one.
6565 static declaration_t *get_label(symbol_t *symbol)
6567 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6568 assert(current_function != NULL);
6569 /* if we found a label in the same function, then we already created the
6571 if(candidate != NULL
6572 && candidate->parent_scope == ¤t_function->scope) {
6576 /* otherwise we need to create a new one */
6577 declaration_t *const declaration = allocate_declaration_zero();
6578 declaration->namespc = NAMESPACE_LABEL;
6579 declaration->symbol = symbol;
6581 label_push(declaration);
6587 * Parse a label statement.
6589 static statement_t *parse_label_statement(void)
6591 assert(token.type == T_IDENTIFIER);
6592 symbol_t *symbol = token.v.symbol;
6595 declaration_t *label = get_label(symbol);
6597 /* if source position is already set then the label is defined twice,
6598 * otherwise it was just mentioned in a goto so far */
6599 if(label->source_position.input_name != NULL) {
6600 errorf(HERE, "duplicate label '%Y'", symbol);
6601 errorf(label->source_position, "previous definition of '%Y' was here",
6604 label->source_position = token.source_position;
6607 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6609 statement->base.source_position = token.source_position;
6610 statement->label.label = label;
6614 if(token.type == '}') {
6615 /* TODO only warn? */
6617 warningf(HERE, "label at end of compound statement");
6618 statement->label.statement = create_empty_statement();
6620 errorf(HERE, "label at end of compound statement");
6621 statement->label.statement = create_invalid_statement();
6625 if (token.type == ';') {
6626 /* eat an empty statement here, to avoid the warning about an empty
6627 * after a label. label:; is commonly used to have a label before
6629 statement->label.statement = create_empty_statement();
6632 statement->label.statement = parse_statement();
6636 /* remember the labels's in a list for later checking */
6637 if (label_last == NULL) {
6638 label_first = &statement->label;
6640 label_last->next = &statement->label;
6642 label_last = &statement->label;
6648 * Parse an if statement.
6650 static statement_t *parse_if(void)
6654 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6655 statement->base.source_position = token.source_position;
6658 add_anchor_token(')');
6659 statement->ifs.condition = parse_expression();
6660 rem_anchor_token(')');
6663 add_anchor_token(T_else);
6664 statement->ifs.true_statement = parse_statement();
6665 rem_anchor_token(T_else);
6667 if(token.type == T_else) {
6669 statement->ifs.false_statement = parse_statement();
6674 return create_invalid_statement();
6678 * Parse a switch statement.
6680 static statement_t *parse_switch(void)
6684 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6685 statement->base.source_position = token.source_position;
6688 expression_t *const expr = parse_expression();
6689 type_t * type = skip_typeref(expr->base.type);
6690 if (is_type_integer(type)) {
6691 type = promote_integer(type);
6692 } else if (is_type_valid(type)) {
6693 errorf(expr->base.source_position,
6694 "switch quantity is not an integer, but '%T'", type);
6695 type = type_error_type;
6697 statement->switchs.expression = create_implicit_cast(expr, type);
6700 switch_statement_t *rem = current_switch;
6701 current_switch = &statement->switchs;
6702 statement->switchs.body = parse_statement();
6703 current_switch = rem;
6705 if (warning.switch_default
6706 && find_default_label(&statement->switchs) == NULL) {
6707 warningf(statement->base.source_position, "switch has no default case");
6712 return create_invalid_statement();
6715 static statement_t *parse_loop_body(statement_t *const loop)
6717 statement_t *const rem = current_loop;
6718 current_loop = loop;
6720 statement_t *const body = parse_statement();
6727 * Parse a while statement.
6729 static statement_t *parse_while(void)
6733 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6734 statement->base.source_position = token.source_position;
6737 add_anchor_token(')');
6738 statement->whiles.condition = parse_expression();
6739 rem_anchor_token(')');
6742 statement->whiles.body = parse_loop_body(statement);
6746 return create_invalid_statement();
6750 * Parse a do statement.
6752 static statement_t *parse_do(void)
6756 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6758 statement->base.source_position = token.source_position;
6760 add_anchor_token(T_while);
6761 statement->do_while.body = parse_loop_body(statement);
6762 rem_anchor_token(T_while);
6766 add_anchor_token(')');
6767 statement->do_while.condition = parse_expression();
6768 rem_anchor_token(')');
6774 return create_invalid_statement();
6778 * Parse a for statement.
6780 static statement_t *parse_for(void)
6784 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6785 statement->base.source_position = token.source_position;
6787 int top = environment_top();
6788 scope_t *last_scope = scope;
6789 set_scope(&statement->fors.scope);
6792 add_anchor_token(')');
6794 if(token.type != ';') {
6795 if(is_declaration_specifier(&token, false)) {
6796 parse_declaration(record_declaration);
6798 expression_t *const init = parse_expression();
6799 statement->fors.initialisation = init;
6800 if (warning.unused_value && !expression_has_effect(init)) {
6801 warningf(init->base.source_position,
6802 "initialisation of 'for'-statement has no effect");
6810 if(token.type != ';') {
6811 statement->fors.condition = parse_expression();
6814 if(token.type != ')') {
6815 expression_t *const step = parse_expression();
6816 statement->fors.step = step;
6817 if (warning.unused_value && !expression_has_effect(step)) {
6818 warningf(step->base.source_position,
6819 "step of 'for'-statement has no effect");
6822 rem_anchor_token(')');
6824 statement->fors.body = parse_loop_body(statement);
6826 assert(scope == &statement->fors.scope);
6827 set_scope(last_scope);
6828 environment_pop_to(top);
6833 rem_anchor_token(')');
6834 assert(scope == &statement->fors.scope);
6835 set_scope(last_scope);
6836 environment_pop_to(top);
6838 return create_invalid_statement();
6842 * Parse a goto statement.
6844 static statement_t *parse_goto(void)
6848 if(token.type != T_IDENTIFIER) {
6849 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6853 symbol_t *symbol = token.v.symbol;
6856 declaration_t *label = get_label(symbol);
6858 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6859 statement->base.source_position = token.source_position;
6861 statement->gotos.label = label;
6863 /* remember the goto's in a list for later checking */
6864 if (goto_last == NULL) {
6865 goto_first = &statement->gotos;
6867 goto_last->next = &statement->gotos;
6869 goto_last = &statement->gotos;
6875 return create_invalid_statement();
6879 * Parse a continue statement.
6881 static statement_t *parse_continue(void)
6883 statement_t *statement;
6884 if (current_loop == NULL) {
6885 errorf(HERE, "continue statement not within loop");
6888 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6890 statement->base.source_position = token.source_position;
6898 return create_invalid_statement();
6902 * Parse a break statement.
6904 static statement_t *parse_break(void)
6906 statement_t *statement;
6907 if (current_switch == NULL && current_loop == NULL) {
6908 errorf(HERE, "break statement not within loop or switch");
6911 statement = allocate_statement_zero(STATEMENT_BREAK);
6913 statement->base.source_position = token.source_position;
6921 return create_invalid_statement();
6925 * Check if a given declaration represents a local variable.
6927 static bool is_local_var_declaration(const declaration_t *declaration) {
6928 switch ((storage_class_tag_t) declaration->storage_class) {
6929 case STORAGE_CLASS_AUTO:
6930 case STORAGE_CLASS_REGISTER: {
6931 const type_t *type = skip_typeref(declaration->type);
6932 if(is_type_function(type)) {
6944 * Check if a given declaration represents a variable.
6946 static bool is_var_declaration(const declaration_t *declaration) {
6947 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6950 const type_t *type = skip_typeref(declaration->type);
6951 return !is_type_function(type);
6955 * Check if a given expression represents a local variable.
6957 static bool is_local_variable(const expression_t *expression)
6959 if (expression->base.kind != EXPR_REFERENCE) {
6962 const declaration_t *declaration = expression->reference.declaration;
6963 return is_local_var_declaration(declaration);
6967 * Check if a given expression represents a local variable and
6968 * return its declaration then, else return NULL.
6970 declaration_t *expr_is_variable(const expression_t *expression)
6972 if (expression->base.kind != EXPR_REFERENCE) {
6975 declaration_t *declaration = expression->reference.declaration;
6976 if (is_var_declaration(declaration))
6982 * Parse a return statement.
6984 static statement_t *parse_return(void)
6988 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6989 statement->base.source_position = token.source_position;
6991 expression_t *return_value = NULL;
6992 if(token.type != ';') {
6993 return_value = parse_expression();
6997 const type_t *const func_type = current_function->type;
6998 assert(is_type_function(func_type));
6999 type_t *const return_type = skip_typeref(func_type->function.return_type);
7001 if(return_value != NULL) {
7002 type_t *return_value_type = skip_typeref(return_value->base.type);
7004 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
7005 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
7006 warningf(statement->base.source_position,
7007 "'return' with a value, in function returning void");
7008 return_value = NULL;
7010 type_t *const res_type = semantic_assign(return_type,
7011 return_value, "'return'");
7012 if (res_type == NULL) {
7013 errorf(statement->base.source_position,
7014 "cannot return something of type '%T' in function returning '%T'",
7015 return_value->base.type, return_type);
7017 return_value = create_implicit_cast(return_value, res_type);
7020 /* check for returning address of a local var */
7021 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
7022 const expression_t *expression = return_value->unary.value;
7023 if (is_local_variable(expression)) {
7024 warningf(statement->base.source_position,
7025 "function returns address of local variable");
7029 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
7030 warningf(statement->base.source_position,
7031 "'return' without value, in function returning non-void");
7034 statement->returns.value = return_value;
7038 return create_invalid_statement();
7042 * Parse a declaration statement.
7044 static statement_t *parse_declaration_statement(void)
7046 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
7048 statement->base.source_position = token.source_position;
7050 declaration_t *before = last_declaration;
7051 parse_declaration(record_declaration);
7053 if(before == NULL) {
7054 statement->declaration.declarations_begin = scope->declarations;
7056 statement->declaration.declarations_begin = before->next;
7058 statement->declaration.declarations_end = last_declaration;
7064 * Parse an expression statement, ie. expr ';'.
7066 static statement_t *parse_expression_statement(void)
7068 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
7070 statement->base.source_position = token.source_position;
7071 expression_t *const expr = parse_expression();
7072 statement->expression.expression = expr;
7074 if (warning.unused_value && !expression_has_effect(expr)) {
7075 warningf(expr->base.source_position, "statement has no effect");
7082 return create_invalid_statement();
7086 * Parse a statement.
7088 static statement_t *parse_statement(void)
7090 statement_t *statement = NULL;
7092 /* declaration or statement */
7093 add_anchor_token(';');
7094 switch(token.type) {
7096 statement = parse_asm_statement();
7100 statement = parse_case_statement();
7104 statement = parse_default_statement();
7108 statement = parse_compound_statement();
7112 statement = parse_if();
7116 statement = parse_switch();
7120 statement = parse_while();
7124 statement = parse_do();
7128 statement = parse_for();
7132 statement = parse_goto();
7136 statement = parse_continue();
7140 statement = parse_break();
7144 statement = parse_return();
7148 if(warning.empty_statement) {
7149 warningf(HERE, "statement is empty");
7151 statement = create_empty_statement();
7156 if(look_ahead(1)->type == ':') {
7157 statement = parse_label_statement();
7161 if(is_typedef_symbol(token.v.symbol)) {
7162 statement = parse_declaration_statement();
7166 statement = parse_expression_statement();
7169 case T___extension__:
7170 /* this can be a prefix to a declaration or an expression statement */
7171 /* we simply eat it now and parse the rest with tail recursion */
7174 } while(token.type == T___extension__);
7175 statement = parse_statement();
7179 statement = parse_declaration_statement();
7183 statement = parse_expression_statement();
7186 rem_anchor_token(';');
7188 assert(statement != NULL
7189 && statement->base.source_position.input_name != NULL);
7195 * Parse a compound statement.
7197 static statement_t *parse_compound_statement(void)
7199 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7201 statement->base.source_position = token.source_position;
7204 add_anchor_token('}');
7206 int top = environment_top();
7207 scope_t *last_scope = scope;
7208 set_scope(&statement->compound.scope);
7210 statement_t *last_statement = NULL;
7212 while(token.type != '}' && token.type != T_EOF) {
7213 statement_t *sub_statement = parse_statement();
7214 if(is_invalid_statement(sub_statement)) {
7215 /* an error occurred. if we are at an anchor, return */
7221 if(last_statement != NULL) {
7222 last_statement->base.next = sub_statement;
7224 statement->compound.statements = sub_statement;
7227 while(sub_statement->base.next != NULL)
7228 sub_statement = sub_statement->base.next;
7230 last_statement = sub_statement;
7233 if(token.type == '}') {
7236 errorf(statement->base.source_position,
7237 "end of file while looking for closing '}'");
7241 rem_anchor_token('}');
7242 assert(scope == &statement->compound.scope);
7243 set_scope(last_scope);
7244 environment_pop_to(top);
7250 * Initialize builtin types.
7252 static void initialize_builtin_types(void)
7254 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7255 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7256 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7257 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7258 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7259 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7260 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7261 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7263 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7264 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7265 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7266 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7270 * Check for unused global static functions and variables
7272 static void check_unused_globals(void)
7274 if (!warning.unused_function && !warning.unused_variable)
7277 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7278 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7281 type_t *const type = decl->type;
7283 if (is_type_function(skip_typeref(type))) {
7284 if (!warning.unused_function || decl->is_inline)
7287 s = (decl->init.statement != NULL ? "defined" : "declared");
7289 if (!warning.unused_variable)
7295 warningf(decl->source_position, "'%#T' %s but not used",
7296 type, decl->symbol, s);
7301 * Parse a translation unit.
7303 static translation_unit_t *parse_translation_unit(void)
7305 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7307 assert(global_scope == NULL);
7308 global_scope = &unit->scope;
7310 assert(scope == NULL);
7311 set_scope(&unit->scope);
7313 initialize_builtin_types();
7315 while(token.type != T_EOF) {
7316 if (token.type == ';') {
7317 /* TODO error in strict mode */
7318 warningf(HERE, "stray ';' outside of function");
7321 parse_external_declaration();
7325 assert(scope == &unit->scope);
7327 last_declaration = NULL;
7329 assert(global_scope == &unit->scope);
7330 check_unused_globals();
7331 global_scope = NULL;
7339 * @return the translation unit or NULL if errors occurred.
7341 translation_unit_t *parse(void)
7343 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7344 label_stack = NEW_ARR_F(stack_entry_t, 0);
7345 diagnostic_count = 0;
7349 type_set_output(stderr);
7350 ast_set_output(stderr);
7352 lookahead_bufpos = 0;
7353 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7356 translation_unit_t *unit = parse_translation_unit();
7358 DEL_ARR_F(environment_stack);
7359 DEL_ARR_F(label_stack);
7365 * Initialize the parser.
7367 void init_parser(void)
7370 /* add predefined symbols for extended-decl-modifier */
7371 sym_align = symbol_table_insert("align");
7372 sym_allocate = symbol_table_insert("allocate");
7373 sym_dllimport = symbol_table_insert("dllimport");
7374 sym_dllexport = symbol_table_insert("dllexport");
7375 sym_naked = symbol_table_insert("naked");
7376 sym_noinline = symbol_table_insert("noinline");
7377 sym_noreturn = symbol_table_insert("noreturn");
7378 sym_nothrow = symbol_table_insert("nothrow");
7379 sym_novtable = symbol_table_insert("novtable");
7380 sym_property = symbol_table_insert("property");
7381 sym_get = symbol_table_insert("get");
7382 sym_put = symbol_table_insert("put");
7383 sym_selectany = symbol_table_insert("selectany");
7384 sym_thread = symbol_table_insert("thread");
7385 sym_uuid = symbol_table_insert("uuid");
7386 sym_deprecated = symbol_table_insert("deprecated");
7387 sym_restrict = symbol_table_insert("restrict");
7388 sym_noalias = symbol_table_insert("noalias");
7390 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7392 init_expression_parsers();
7393 obstack_init(&temp_obst);
7395 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7396 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7400 * Terminate the parser.
7402 void exit_parser(void)
7404 obstack_free(&temp_obst, NULL);