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);
943 * Parse one GNU attribute.
945 static void parse_gnu_attribute(void)
947 eat(T___attribute__);
951 if(token.type != T_IDENTIFIER)
953 symbol_t *sym = token.v.symbol;
954 if(sym == sym_deprecated) {
957 if(token.type == '(')
958 eat_until_matching_token('(');
959 if(token.type != ',')
970 * Parse GNU attributes.
972 static void parse_attributes(void)
976 case T___attribute__: {
977 parse_gnu_attribute();
983 if(token.type != T_STRING_LITERAL) {
984 parse_error_expected("while parsing assembler attribute",
986 eat_until_matching_token('(');
989 parse_string_literals();
994 goto attributes_finished;
1003 static designator_t *parse_designation(void)
1005 designator_t *result = NULL;
1006 designator_t *last = NULL;
1009 designator_t *designator;
1010 switch(token.type) {
1012 designator = allocate_ast_zero(sizeof(designator[0]));
1013 designator->source_position = token.source_position;
1015 add_anchor_token(']');
1016 designator->array_index = parse_constant_expression();
1017 rem_anchor_token(']');
1021 designator = allocate_ast_zero(sizeof(designator[0]));
1022 designator->source_position = token.source_position;
1024 if(token.type != T_IDENTIFIER) {
1025 parse_error_expected("while parsing designator",
1029 designator->symbol = token.v.symbol;
1037 assert(designator != NULL);
1039 last->next = designator;
1041 result = designator;
1049 static initializer_t *initializer_from_string(array_type_t *type,
1050 const string_t *const string)
1052 /* TODO: check len vs. size of array type */
1055 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1056 initializer->string.string = *string;
1061 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1062 wide_string_t *const string)
1064 /* TODO: check len vs. size of array type */
1067 initializer_t *const initializer =
1068 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1069 initializer->wide_string.string = *string;
1075 * Build an initializer from a given expression.
1077 static initializer_t *initializer_from_expression(type_t *orig_type,
1078 expression_t *expression)
1080 /* TODO check that expression is a constant expression */
1082 /* § 6.7.8.14/15 char array may be initialized by string literals */
1083 type_t *type = skip_typeref(orig_type);
1084 type_t *expr_type_orig = expression->base.type;
1085 type_t *expr_type = skip_typeref(expr_type_orig);
1086 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1087 array_type_t *const array_type = &type->array;
1088 type_t *const element_type = skip_typeref(array_type->element_type);
1090 if (element_type->kind == TYPE_ATOMIC) {
1091 atomic_type_kind_t akind = element_type->atomic.akind;
1092 switch (expression->kind) {
1093 case EXPR_STRING_LITERAL:
1094 if (akind == ATOMIC_TYPE_CHAR
1095 || akind == ATOMIC_TYPE_SCHAR
1096 || akind == ATOMIC_TYPE_UCHAR) {
1097 return initializer_from_string(array_type,
1098 &expression->string.value);
1101 case EXPR_WIDE_STRING_LITERAL: {
1102 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1103 if (get_unqualified_type(element_type) == bare_wchar_type) {
1104 return initializer_from_wide_string(array_type,
1105 &expression->wide_string.value);
1115 type_t *const res_type = semantic_assign(type, expression, "initializer");
1116 if (res_type == NULL)
1119 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1120 result->value.value = create_implicit_cast(expression, res_type);
1126 * Checks if a given expression can be used as an constant initializer.
1128 static bool is_initializer_constant(const expression_t *expression)
1130 return is_constant_expression(expression)
1131 || is_address_constant(expression);
1135 * Parses an scalar initializer.
1137 * § 6.7.8.11; eat {} without warning
1139 static initializer_t *parse_scalar_initializer(type_t *type,
1140 bool must_be_constant)
1142 /* there might be extra {} hierarchies */
1144 while(token.type == '{') {
1147 warningf(HERE, "extra curly braces around scalar initializer");
1152 expression_t *expression = parse_assignment_expression();
1153 if(must_be_constant && !is_initializer_constant(expression)) {
1154 errorf(expression->base.source_position,
1155 "Initialisation expression '%E' is not constant\n",
1159 initializer_t *initializer = initializer_from_expression(type, expression);
1161 if(initializer == NULL) {
1162 errorf(expression->base.source_position,
1163 "expression '%E' doesn't match expected type '%T'",
1169 bool additional_warning_displayed = false;
1171 if(token.type == ',') {
1174 if(token.type != '}') {
1175 if(!additional_warning_displayed) {
1176 warningf(HERE, "additional elements in scalar initializer");
1177 additional_warning_displayed = true;
1188 * An entry in the type path.
1190 typedef struct type_path_entry_t type_path_entry_t;
1191 struct type_path_entry_t {
1192 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1194 size_t index; /**< For array types: the current index. */
1195 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1200 * A type path expression a position inside compound or array types.
1202 typedef struct type_path_t type_path_t;
1203 struct type_path_t {
1204 type_path_entry_t *path; /**< An flexible array containing the current path. */
1205 type_t *top_type; /**< type of the element the path points */
1206 size_t max_index; /**< largest index in outermost array */
1210 * Prints a type path for debugging.
1212 static __attribute__((unused)) void debug_print_type_path(
1213 const type_path_t *path)
1215 size_t len = ARR_LEN(path->path);
1217 for(size_t i = 0; i < len; ++i) {
1218 const type_path_entry_t *entry = & path->path[i];
1220 type_t *type = skip_typeref(entry->type);
1221 if(is_type_compound(type)) {
1222 /* in gcc mode structs can have no members */
1223 if(entry->v.compound_entry == NULL) {
1227 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1228 } else if(is_type_array(type)) {
1229 fprintf(stderr, "[%zd]", entry->v.index);
1231 fprintf(stderr, "-INVALID-");
1234 if(path->top_type != NULL) {
1235 fprintf(stderr, " (");
1236 print_type(path->top_type);
1237 fprintf(stderr, ")");
1242 * Return the top type path entry, ie. in a path
1243 * (type).a.b returns the b.
1245 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1247 size_t len = ARR_LEN(path->path);
1249 return &path->path[len-1];
1253 * Enlarge the type path by an (empty) element.
1255 static type_path_entry_t *append_to_type_path(type_path_t *path)
1257 size_t len = ARR_LEN(path->path);
1258 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1260 type_path_entry_t *result = & path->path[len];
1261 memset(result, 0, sizeof(result[0]));
1266 * Descending into a sub-type. Enter the scope of the current
1269 static void descend_into_subtype(type_path_t *path)
1271 type_t *orig_top_type = path->top_type;
1272 type_t *top_type = skip_typeref(orig_top_type);
1274 assert(is_type_compound(top_type) || is_type_array(top_type));
1276 type_path_entry_t *top = append_to_type_path(path);
1277 top->type = top_type;
1279 if(is_type_compound(top_type)) {
1280 declaration_t *declaration = top_type->compound.declaration;
1281 declaration_t *entry = declaration->scope.declarations;
1282 top->v.compound_entry = entry;
1285 path->top_type = entry->type;
1287 path->top_type = NULL;
1290 assert(is_type_array(top_type));
1293 path->top_type = top_type->array.element_type;
1298 * Pop an entry from the given type path, ie. returning from
1299 * (type).a.b to (type).a
1301 static void ascend_from_subtype(type_path_t *path)
1303 type_path_entry_t *top = get_type_path_top(path);
1305 path->top_type = top->type;
1307 size_t len = ARR_LEN(path->path);
1308 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1312 * Pop entries from the given type path until the given
1313 * path level is reached.
1315 static void ascend_to(type_path_t *path, size_t top_path_level)
1317 size_t len = ARR_LEN(path->path);
1319 while(len > top_path_level) {
1320 ascend_from_subtype(path);
1321 len = ARR_LEN(path->path);
1325 static bool walk_designator(type_path_t *path, const designator_t *designator,
1326 bool used_in_offsetof)
1328 for( ; designator != NULL; designator = designator->next) {
1329 type_path_entry_t *top = get_type_path_top(path);
1330 type_t *orig_type = top->type;
1332 type_t *type = skip_typeref(orig_type);
1334 if(designator->symbol != NULL) {
1335 symbol_t *symbol = designator->symbol;
1336 if(!is_type_compound(type)) {
1337 if(is_type_valid(type)) {
1338 errorf(designator->source_position,
1339 "'.%Y' designator used for non-compound type '%T'",
1345 declaration_t *declaration = type->compound.declaration;
1346 declaration_t *iter = declaration->scope.declarations;
1347 for( ; iter != NULL; iter = iter->next) {
1348 if(iter->symbol == symbol) {
1353 errorf(designator->source_position,
1354 "'%T' has no member named '%Y'", orig_type, symbol);
1357 if(used_in_offsetof) {
1358 type_t *real_type = skip_typeref(iter->type);
1359 if(real_type->kind == TYPE_BITFIELD) {
1360 errorf(designator->source_position,
1361 "offsetof designator '%Y' may not specify bitfield",
1367 top->type = orig_type;
1368 top->v.compound_entry = iter;
1369 orig_type = iter->type;
1371 expression_t *array_index = designator->array_index;
1372 assert(designator->array_index != NULL);
1374 if(!is_type_array(type)) {
1375 if(is_type_valid(type)) {
1376 errorf(designator->source_position,
1377 "[%E] designator used for non-array type '%T'",
1378 array_index, orig_type);
1382 if(!is_type_valid(array_index->base.type)) {
1386 long index = fold_constant(array_index);
1387 if(!used_in_offsetof) {
1389 errorf(designator->source_position,
1390 "array index [%E] must be positive", array_index);
1393 if(type->array.size_constant == true) {
1394 long array_size = type->array.size;
1395 if(index >= array_size) {
1396 errorf(designator->source_position,
1397 "designator [%E] (%d) exceeds array size %d",
1398 array_index, index, array_size);
1404 top->type = orig_type;
1405 top->v.index = (size_t) index;
1406 orig_type = type->array.element_type;
1408 path->top_type = orig_type;
1410 if(designator->next != NULL) {
1411 descend_into_subtype(path);
1420 static void advance_current_object(type_path_t *path, size_t top_path_level)
1422 type_path_entry_t *top = get_type_path_top(path);
1424 type_t *type = skip_typeref(top->type);
1425 if(is_type_union(type)) {
1426 /* in unions only the first element is initialized */
1427 top->v.compound_entry = NULL;
1428 } else if(is_type_struct(type)) {
1429 declaration_t *entry = top->v.compound_entry;
1431 entry = entry->next;
1432 top->v.compound_entry = entry;
1434 path->top_type = entry->type;
1438 assert(is_type_array(type));
1442 if(!type->array.size_constant || top->v.index < type->array.size) {
1447 /* we're past the last member of the current sub-aggregate, try if we
1448 * can ascend in the type hierarchy and continue with another subobject */
1449 size_t len = ARR_LEN(path->path);
1451 if(len > top_path_level) {
1452 ascend_from_subtype(path);
1453 advance_current_object(path, top_path_level);
1455 path->top_type = NULL;
1460 * skip until token is found.
1462 static void skip_until(int type) {
1463 while(token.type != type) {
1464 if(token.type == T_EOF)
1471 * skip any {...} blocks until a closing braket is reached.
1473 static void skip_initializers(void)
1475 if(token.type == '{')
1478 while(token.type != '}') {
1479 if(token.type == T_EOF)
1481 if(token.type == '{') {
1489 static initializer_t *create_empty_initializer(void)
1491 static initializer_t empty_initializer
1492 = { .list = { { INITIALIZER_LIST }, 0 } };
1493 return &empty_initializer;
1497 * Parse a part of an initialiser for a struct or union,
1499 static initializer_t *parse_sub_initializer(type_path_t *path,
1500 type_t *outer_type, size_t top_path_level,
1501 parse_initializer_env_t *env)
1503 if(token.type == '}') {
1504 /* empty initializer */
1505 return create_empty_initializer();
1508 type_t *orig_type = path->top_type;
1509 type_t *type = NULL;
1511 if (orig_type == NULL) {
1512 /* We are initializing an empty compound. */
1514 type = skip_typeref(orig_type);
1516 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1517 * initializers in this case. */
1518 if(!is_type_valid(type)) {
1519 skip_initializers();
1520 return create_empty_initializer();
1524 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1527 designator_t *designator = NULL;
1528 if(token.type == '.' || token.type == '[') {
1529 designator = parse_designation();
1531 /* reset path to toplevel, evaluate designator from there */
1532 ascend_to(path, top_path_level);
1533 if(!walk_designator(path, designator, false)) {
1534 /* can't continue after designation error */
1538 initializer_t *designator_initializer
1539 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1540 designator_initializer->designator.designator = designator;
1541 ARR_APP1(initializer_t*, initializers, designator_initializer);
1546 if(token.type == '{') {
1547 if(type != NULL && is_type_scalar(type)) {
1548 sub = parse_scalar_initializer(type, env->must_be_constant);
1552 if (env->declaration != NULL)
1553 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1554 env->declaration->symbol);
1556 errorf(HERE, "extra brace group at end of initializer");
1558 descend_into_subtype(path);
1560 add_anchor_token('}');
1561 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1563 rem_anchor_token('}');
1566 ascend_from_subtype(path);
1570 goto error_parse_next;
1574 /* must be an expression */
1575 expression_t *expression = parse_assignment_expression();
1577 if(env->must_be_constant && !is_initializer_constant(expression)) {
1578 errorf(expression->base.source_position,
1579 "Initialisation expression '%E' is not constant\n",
1584 /* we are already outside, ... */
1588 /* handle { "string" } special case */
1589 if((expression->kind == EXPR_STRING_LITERAL
1590 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1591 && outer_type != NULL) {
1592 sub = initializer_from_expression(outer_type, expression);
1594 if(token.type == ',') {
1597 if(token.type != '}') {
1598 warningf(HERE, "excessive elements in initializer for type '%T'",
1601 /* TODO: eat , ... */
1606 /* descend into subtypes until expression matches type */
1608 orig_type = path->top_type;
1609 type = skip_typeref(orig_type);
1611 sub = initializer_from_expression(orig_type, expression);
1615 if(!is_type_valid(type)) {
1618 if(is_type_scalar(type)) {
1619 errorf(expression->base.source_position,
1620 "expression '%E' doesn't match expected type '%T'",
1621 expression, orig_type);
1625 descend_into_subtype(path);
1629 /* update largest index of top array */
1630 const type_path_entry_t *first = &path->path[0];
1631 type_t *first_type = first->type;
1632 first_type = skip_typeref(first_type);
1633 if(is_type_array(first_type)) {
1634 size_t index = first->v.index;
1635 if(index > path->max_index)
1636 path->max_index = index;
1640 /* append to initializers list */
1641 ARR_APP1(initializer_t*, initializers, sub);
1644 if(env->declaration != NULL)
1645 warningf(HERE, "excess elements in struct initializer for '%Y'",
1646 env->declaration->symbol);
1648 warningf(HERE, "excess elements in struct initializer");
1652 if(token.type == '}') {
1656 if(token.type == '}') {
1661 /* advance to the next declaration if we are not at the end */
1662 advance_current_object(path, top_path_level);
1663 orig_type = path->top_type;
1664 if(orig_type != NULL)
1665 type = skip_typeref(orig_type);
1671 size_t len = ARR_LEN(initializers);
1672 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1673 initializer_t *result = allocate_ast_zero(size);
1674 result->kind = INITIALIZER_LIST;
1675 result->list.len = len;
1676 memcpy(&result->list.initializers, initializers,
1677 len * sizeof(initializers[0]));
1679 DEL_ARR_F(initializers);
1680 ascend_to(path, top_path_level);
1685 skip_initializers();
1686 DEL_ARR_F(initializers);
1687 ascend_to(path, top_path_level);
1692 * Parses an initializer. Parsers either a compound literal
1693 * (env->declaration == NULL) or an initializer of a declaration.
1695 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1697 type_t *type = skip_typeref(env->type);
1698 initializer_t *result = NULL;
1701 if(is_type_scalar(type)) {
1702 result = parse_scalar_initializer(type, env->must_be_constant);
1703 } else if(token.type == '{') {
1707 memset(&path, 0, sizeof(path));
1708 path.top_type = env->type;
1709 path.path = NEW_ARR_F(type_path_entry_t, 0);
1711 descend_into_subtype(&path);
1713 add_anchor_token('}');
1714 result = parse_sub_initializer(&path, env->type, 1, env);
1715 rem_anchor_token('}');
1717 max_index = path.max_index;
1718 DEL_ARR_F(path.path);
1722 /* parse_scalar_initializer() also works in this case: we simply
1723 * have an expression without {} around it */
1724 result = parse_scalar_initializer(type, env->must_be_constant);
1727 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1728 * the array type size */
1729 if(is_type_array(type) && type->array.size_expression == NULL
1730 && result != NULL) {
1732 switch (result->kind) {
1733 case INITIALIZER_LIST:
1734 size = max_index + 1;
1737 case INITIALIZER_STRING:
1738 size = result->string.string.size;
1741 case INITIALIZER_WIDE_STRING:
1742 size = result->wide_string.string.size;
1746 internal_errorf(HERE, "invalid initializer type");
1749 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1750 cnst->base.type = type_size_t;
1751 cnst->conste.v.int_value = size;
1753 type_t *new_type = duplicate_type(type);
1755 new_type->array.size_expression = cnst;
1756 new_type->array.size_constant = true;
1757 new_type->array.size = size;
1758 env->type = new_type;
1766 static declaration_t *append_declaration(declaration_t *declaration);
1768 static declaration_t *parse_compound_type_specifier(bool is_struct)
1776 symbol_t *symbol = NULL;
1777 declaration_t *declaration = NULL;
1779 if (token.type == T___attribute__) {
1784 if(token.type == T_IDENTIFIER) {
1785 symbol = token.v.symbol;
1789 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1791 declaration = get_declaration(symbol, NAMESPACE_UNION);
1793 } else if(token.type != '{') {
1795 parse_error_expected("while parsing struct type specifier",
1796 T_IDENTIFIER, '{', 0);
1798 parse_error_expected("while parsing union type specifier",
1799 T_IDENTIFIER, '{', 0);
1805 if(declaration == NULL) {
1806 declaration = allocate_declaration_zero();
1807 declaration->namespc =
1808 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1809 declaration->source_position = token.source_position;
1810 declaration->symbol = symbol;
1811 declaration->parent_scope = scope;
1812 if (symbol != NULL) {
1813 environment_push(declaration);
1815 append_declaration(declaration);
1818 if(token.type == '{') {
1819 if(declaration->init.is_defined) {
1820 assert(symbol != NULL);
1821 errorf(HERE, "multiple definitions of '%s %Y'",
1822 is_struct ? "struct" : "union", symbol);
1823 declaration->scope.declarations = NULL;
1825 declaration->init.is_defined = true;
1827 parse_compound_type_entries(declaration);
1834 static void parse_enum_entries(type_t *const enum_type)
1838 if(token.type == '}') {
1840 errorf(HERE, "empty enum not allowed");
1844 add_anchor_token('}');
1846 if(token.type != T_IDENTIFIER) {
1847 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1849 rem_anchor_token('}');
1853 declaration_t *const entry = allocate_declaration_zero();
1854 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1855 entry->type = enum_type;
1856 entry->symbol = token.v.symbol;
1857 entry->source_position = token.source_position;
1860 if(token.type == '=') {
1862 expression_t *value = parse_constant_expression();
1864 value = create_implicit_cast(value, enum_type);
1865 entry->init.enum_value = value;
1870 record_declaration(entry);
1872 if(token.type != ',')
1875 } while(token.type != '}');
1876 rem_anchor_token('}');
1884 static type_t *parse_enum_specifier(void)
1888 declaration_t *declaration;
1891 if(token.type == T_IDENTIFIER) {
1892 symbol = token.v.symbol;
1895 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1896 } else if(token.type != '{') {
1897 parse_error_expected("while parsing enum type specifier",
1898 T_IDENTIFIER, '{', 0);
1905 if(declaration == NULL) {
1906 declaration = allocate_declaration_zero();
1907 declaration->namespc = NAMESPACE_ENUM;
1908 declaration->source_position = token.source_position;
1909 declaration->symbol = symbol;
1910 declaration->parent_scope = scope;
1913 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1914 type->enumt.declaration = declaration;
1916 if(token.type == '{') {
1917 if(declaration->init.is_defined) {
1918 errorf(HERE, "multiple definitions of enum %Y", symbol);
1920 if (symbol != NULL) {
1921 environment_push(declaration);
1923 append_declaration(declaration);
1924 declaration->init.is_defined = 1;
1926 parse_enum_entries(type);
1934 * if a symbol is a typedef to another type, return true
1936 static bool is_typedef_symbol(symbol_t *symbol)
1938 const declaration_t *const declaration =
1939 get_declaration(symbol, NAMESPACE_NORMAL);
1941 declaration != NULL &&
1942 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1945 static type_t *parse_typeof(void)
1952 add_anchor_token(')');
1954 expression_t *expression = NULL;
1957 switch(token.type) {
1958 case T___extension__:
1959 /* this can be a prefix to a typename or an expression */
1960 /* we simply eat it now. */
1963 } while(token.type == T___extension__);
1967 if(is_typedef_symbol(token.v.symbol)) {
1968 type = parse_typename();
1970 expression = parse_expression();
1971 type = expression->base.type;
1976 type = parse_typename();
1980 expression = parse_expression();
1981 type = expression->base.type;
1985 rem_anchor_token(')');
1988 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1989 typeof_type->typeoft.expression = expression;
1990 typeof_type->typeoft.typeof_type = type;
1998 SPECIFIER_SIGNED = 1 << 0,
1999 SPECIFIER_UNSIGNED = 1 << 1,
2000 SPECIFIER_LONG = 1 << 2,
2001 SPECIFIER_INT = 1 << 3,
2002 SPECIFIER_DOUBLE = 1 << 4,
2003 SPECIFIER_CHAR = 1 << 5,
2004 SPECIFIER_SHORT = 1 << 6,
2005 SPECIFIER_LONG_LONG = 1 << 7,
2006 SPECIFIER_FLOAT = 1 << 8,
2007 SPECIFIER_BOOL = 1 << 9,
2008 SPECIFIER_VOID = 1 << 10,
2009 SPECIFIER_INT8 = 1 << 11,
2010 SPECIFIER_INT16 = 1 << 12,
2011 SPECIFIER_INT32 = 1 << 13,
2012 SPECIFIER_INT64 = 1 << 14,
2013 SPECIFIER_INT128 = 1 << 15,
2014 #ifdef PROVIDE_COMPLEX
2015 SPECIFIER_COMPLEX = 1 << 16,
2016 SPECIFIER_IMAGINARY = 1 << 17,
2020 static type_t *create_builtin_type(symbol_t *const symbol,
2021 type_t *const real_type)
2023 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2024 type->builtin.symbol = symbol;
2025 type->builtin.real_type = real_type;
2027 type_t *result = typehash_insert(type);
2028 if (type != result) {
2035 static type_t *get_typedef_type(symbol_t *symbol)
2037 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2038 if(declaration == NULL
2039 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2042 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2043 type->typedeft.declaration = declaration;
2049 * check for the allowed MS alignment values.
2051 static bool check_elignment_value(long long intvalue) {
2052 if(intvalue < 1 || intvalue > 8192) {
2053 errorf(HERE, "illegal alignment value");
2056 unsigned v = (unsigned)intvalue;
2057 for(unsigned i = 1; i <= 8192; i += i) {
2061 errorf(HERE, "alignment must be power of two");
2065 #define DET_MOD(name, tag) do { \
2066 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2067 *modifiers |= tag; \
2070 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2072 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2075 if(token.type == T_restrict) {
2077 DET_MOD(restrict, DM_RESTRICT);
2079 } else if(token.type != T_IDENTIFIER)
2081 symbol_t *symbol = token.v.symbol;
2082 if(symbol == sym_align) {
2085 if(token.type != T_INTEGER)
2087 if(check_elignment_value(token.v.intvalue)) {
2088 if(specifiers->alignment != 0)
2089 warningf(HERE, "align used more than once");
2090 specifiers->alignment = (unsigned char)token.v.intvalue;
2094 } else if(symbol == sym_allocate) {
2097 if(token.type != T_IDENTIFIER)
2099 (void)token.v.symbol;
2101 } else if(symbol == sym_dllimport) {
2103 DET_MOD(dllimport, DM_DLLIMPORT);
2104 } else if(symbol == sym_dllexport) {
2106 DET_MOD(dllexport, DM_DLLEXPORT);
2107 } else if(symbol == sym_thread) {
2109 DET_MOD(thread, DM_THREAD);
2110 } else if(symbol == sym_naked) {
2112 DET_MOD(naked, DM_NAKED);
2113 } else if(symbol == sym_noinline) {
2115 DET_MOD(noinline, DM_NOINLINE);
2116 } else if(symbol == sym_noreturn) {
2118 DET_MOD(noreturn, DM_NORETURN);
2119 } else if(symbol == sym_nothrow) {
2121 DET_MOD(nothrow, DM_NOTHROW);
2122 } else if(symbol == sym_novtable) {
2124 DET_MOD(novtable, DM_NOVTABLE);
2125 } else if(symbol == sym_property) {
2129 bool is_get = false;
2130 if(token.type != T_IDENTIFIER)
2132 if(token.v.symbol == sym_get) {
2134 } else if(token.v.symbol == sym_put) {
2136 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2141 if(token.type != T_IDENTIFIER)
2144 if(specifiers->get_property_sym != NULL) {
2145 errorf(HERE, "get property name already specified");
2147 specifiers->get_property_sym = token.v.symbol;
2150 if(specifiers->put_property_sym != NULL) {
2151 errorf(HERE, "put property name already specified");
2153 specifiers->put_property_sym = token.v.symbol;
2157 if(token.type == ',') {
2164 } else if(symbol == sym_selectany) {
2166 DET_MOD(selectany, DM_SELECTANY);
2167 } else if(symbol == sym_uuid) {
2170 if(token.type != T_STRING_LITERAL)
2174 } else if(symbol == sym_deprecated) {
2176 if(specifiers->deprecated != 0)
2177 warningf(HERE, "deprecated used more than once");
2178 specifiers->deprecated = 1;
2179 if(token.type == '(') {
2181 if(token.type == T_STRING_LITERAL) {
2182 specifiers->deprecated_string = token.v.string.begin;
2185 errorf(HERE, "string literal expected");
2189 } else if(symbol == sym_noalias) {
2191 DET_MOD(noalias, DM_NOALIAS);
2193 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2195 if(token.type == '(')
2199 if (token.type == ',')
2206 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2208 type_t *type = NULL;
2209 unsigned type_qualifiers = 0;
2210 unsigned type_specifiers = 0;
2213 specifiers->source_position = token.source_position;
2216 switch(token.type) {
2219 #define MATCH_STORAGE_CLASS(token, class) \
2221 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2222 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2224 specifiers->declared_storage_class = class; \
2228 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2229 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2230 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2231 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2232 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2237 add_anchor_token(')');
2238 parse_microsoft_extended_decl_modifier(specifiers);
2239 rem_anchor_token(')');
2244 switch (specifiers->declared_storage_class) {
2245 case STORAGE_CLASS_NONE:
2246 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2249 case STORAGE_CLASS_EXTERN:
2250 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2253 case STORAGE_CLASS_STATIC:
2254 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2258 errorf(HERE, "multiple storage classes in declaration specifiers");
2264 /* type qualifiers */
2265 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2267 type_qualifiers |= qualifier; \
2271 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2272 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2273 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2274 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2275 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2276 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2277 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2278 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2280 case T___extension__:
2285 /* type specifiers */
2286 #define MATCH_SPECIFIER(token, specifier, name) \
2289 if(type_specifiers & specifier) { \
2290 errorf(HERE, "multiple " name " type specifiers given"); \
2292 type_specifiers |= specifier; \
2296 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2297 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2298 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2299 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2300 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2301 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2302 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2303 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2304 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2305 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2306 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2307 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2308 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2309 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2310 #ifdef PROVIDE_COMPLEX
2311 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2312 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2314 case T__forceinline:
2315 /* only in microsoft mode */
2316 specifiers->decl_modifiers |= DM_FORCEINLINE;
2320 specifiers->is_inline = true;
2325 if(type_specifiers & SPECIFIER_LONG_LONG) {
2326 errorf(HERE, "multiple type specifiers given");
2327 } else if(type_specifiers & SPECIFIER_LONG) {
2328 type_specifiers |= SPECIFIER_LONG_LONG;
2330 type_specifiers |= SPECIFIER_LONG;
2335 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2337 type->compound.declaration = parse_compound_type_specifier(true);
2341 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2343 type->compound.declaration = parse_compound_type_specifier(false);
2347 type = parse_enum_specifier();
2350 type = parse_typeof();
2352 case T___builtin_va_list:
2353 type = duplicate_type(type_valist);
2357 case T___attribute__:
2361 case T_IDENTIFIER: {
2362 /* only parse identifier if we haven't found a type yet */
2363 if(type != NULL || type_specifiers != 0)
2364 goto finish_specifiers;
2366 type_t *typedef_type = get_typedef_type(token.v.symbol);
2368 if(typedef_type == NULL)
2369 goto finish_specifiers;
2372 type = typedef_type;
2376 /* function specifier */
2378 goto finish_specifiers;
2385 atomic_type_kind_t atomic_type;
2387 /* match valid basic types */
2388 switch(type_specifiers) {
2389 case SPECIFIER_VOID:
2390 atomic_type = ATOMIC_TYPE_VOID;
2392 case SPECIFIER_CHAR:
2393 atomic_type = ATOMIC_TYPE_CHAR;
2395 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2396 atomic_type = ATOMIC_TYPE_SCHAR;
2398 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2399 atomic_type = ATOMIC_TYPE_UCHAR;
2401 case SPECIFIER_SHORT:
2402 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2403 case SPECIFIER_SHORT | SPECIFIER_INT:
2404 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2405 atomic_type = ATOMIC_TYPE_SHORT;
2407 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2408 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2409 atomic_type = ATOMIC_TYPE_USHORT;
2412 case SPECIFIER_SIGNED:
2413 case SPECIFIER_SIGNED | SPECIFIER_INT:
2414 atomic_type = ATOMIC_TYPE_INT;
2416 case SPECIFIER_UNSIGNED:
2417 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2418 atomic_type = ATOMIC_TYPE_UINT;
2420 case SPECIFIER_LONG:
2421 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2422 case SPECIFIER_LONG | SPECIFIER_INT:
2423 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2424 atomic_type = ATOMIC_TYPE_LONG;
2426 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2427 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2428 atomic_type = ATOMIC_TYPE_ULONG;
2430 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2431 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2432 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2433 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2435 atomic_type = ATOMIC_TYPE_LONGLONG;
2437 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2438 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2440 atomic_type = ATOMIC_TYPE_ULONGLONG;
2443 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2444 atomic_type = unsigned_int8_type_kind;
2447 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2448 atomic_type = unsigned_int16_type_kind;
2451 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2452 atomic_type = unsigned_int32_type_kind;
2455 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2456 atomic_type = unsigned_int64_type_kind;
2459 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2460 atomic_type = unsigned_int128_type_kind;
2463 case SPECIFIER_INT8:
2464 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2465 atomic_type = int8_type_kind;
2468 case SPECIFIER_INT16:
2469 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2470 atomic_type = int16_type_kind;
2473 case SPECIFIER_INT32:
2474 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2475 atomic_type = int32_type_kind;
2478 case SPECIFIER_INT64:
2479 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2480 atomic_type = int64_type_kind;
2483 case SPECIFIER_INT128:
2484 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2485 atomic_type = int128_type_kind;
2488 case SPECIFIER_FLOAT:
2489 atomic_type = ATOMIC_TYPE_FLOAT;
2491 case SPECIFIER_DOUBLE:
2492 atomic_type = ATOMIC_TYPE_DOUBLE;
2494 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2495 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2497 case SPECIFIER_BOOL:
2498 atomic_type = ATOMIC_TYPE_BOOL;
2500 #ifdef PROVIDE_COMPLEX
2501 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2502 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2504 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2505 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2507 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2508 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2510 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2511 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2513 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2514 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2516 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2517 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2521 /* invalid specifier combination, give an error message */
2522 if(type_specifiers == 0) {
2523 if (! strict_mode) {
2524 if (warning.implicit_int) {
2525 warningf(HERE, "no type specifiers in declaration, using 'int'");
2527 atomic_type = ATOMIC_TYPE_INT;
2530 errorf(HERE, "no type specifiers given in declaration");
2532 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2533 (type_specifiers & SPECIFIER_UNSIGNED)) {
2534 errorf(HERE, "signed and unsigned specifiers gives");
2535 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2536 errorf(HERE, "only integer types can be signed or unsigned");
2538 errorf(HERE, "multiple datatypes in declaration");
2540 atomic_type = ATOMIC_TYPE_INVALID;
2543 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2544 type->atomic.akind = atomic_type;
2547 if(type_specifiers != 0) {
2548 errorf(HERE, "multiple datatypes in declaration");
2552 type->base.qualifiers = type_qualifiers;
2553 /* FIXME: check type qualifiers here */
2555 type_t *result = typehash_insert(type);
2556 if(newtype && result != type) {
2560 specifiers->type = result;
2565 static type_qualifiers_t parse_type_qualifiers(void)
2567 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2570 switch(token.type) {
2571 /* type qualifiers */
2572 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2573 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2574 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2575 /* microsoft extended type modifiers */
2576 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2577 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2578 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2579 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2580 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2583 return type_qualifiers;
2588 static declaration_t *parse_identifier_list(void)
2590 declaration_t *declarations = NULL;
2591 declaration_t *last_declaration = NULL;
2593 declaration_t *const declaration = allocate_declaration_zero();
2594 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2595 declaration->source_position = token.source_position;
2596 declaration->symbol = token.v.symbol;
2599 if(last_declaration != NULL) {
2600 last_declaration->next = declaration;
2602 declarations = declaration;
2604 last_declaration = declaration;
2606 if(token.type != ',')
2609 } while(token.type == T_IDENTIFIER);
2611 return declarations;
2614 static void semantic_parameter(declaration_t *declaration)
2616 /* TODO: improve error messages */
2618 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2619 errorf(HERE, "typedef not allowed in parameter list");
2620 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2621 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2622 errorf(HERE, "parameter may only have none or register storage class");
2625 type_t *const orig_type = declaration->type;
2626 type_t * type = skip_typeref(orig_type);
2628 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2629 * into a pointer. § 6.7.5.3 (7) */
2630 if (is_type_array(type)) {
2631 type_t *const element_type = type->array.element_type;
2633 type = make_pointer_type(element_type, type->base.qualifiers);
2635 declaration->type = type;
2638 if(is_type_incomplete(type)) {
2639 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2640 orig_type, declaration->symbol);
2644 static declaration_t *parse_parameter(void)
2646 declaration_specifiers_t specifiers;
2647 memset(&specifiers, 0, sizeof(specifiers));
2649 parse_declaration_specifiers(&specifiers);
2651 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2653 semantic_parameter(declaration);
2658 static declaration_t *parse_parameters(function_type_t *type)
2660 if(token.type == T_IDENTIFIER) {
2661 symbol_t *symbol = token.v.symbol;
2662 if(!is_typedef_symbol(symbol)) {
2663 type->kr_style_parameters = true;
2664 return parse_identifier_list();
2668 if(token.type == ')') {
2669 type->unspecified_parameters = 1;
2672 if(token.type == T_void && look_ahead(1)->type == ')') {
2677 declaration_t *declarations = NULL;
2678 declaration_t *declaration;
2679 declaration_t *last_declaration = NULL;
2680 function_parameter_t *parameter;
2681 function_parameter_t *last_parameter = NULL;
2684 switch(token.type) {
2688 return declarations;
2691 case T___extension__:
2693 declaration = parse_parameter();
2695 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2696 memset(parameter, 0, sizeof(parameter[0]));
2697 parameter->type = declaration->type;
2699 if(last_parameter != NULL) {
2700 last_declaration->next = declaration;
2701 last_parameter->next = parameter;
2703 type->parameters = parameter;
2704 declarations = declaration;
2706 last_parameter = parameter;
2707 last_declaration = declaration;
2711 return declarations;
2713 if(token.type != ',')
2714 return declarations;
2724 } construct_type_kind_t;
2726 typedef struct construct_type_t construct_type_t;
2727 struct construct_type_t {
2728 construct_type_kind_t kind;
2729 construct_type_t *next;
2732 typedef struct parsed_pointer_t parsed_pointer_t;
2733 struct parsed_pointer_t {
2734 construct_type_t construct_type;
2735 type_qualifiers_t type_qualifiers;
2738 typedef struct construct_function_type_t construct_function_type_t;
2739 struct construct_function_type_t {
2740 construct_type_t construct_type;
2741 type_t *function_type;
2744 typedef struct parsed_array_t parsed_array_t;
2745 struct parsed_array_t {
2746 construct_type_t construct_type;
2747 type_qualifiers_t type_qualifiers;
2753 typedef struct construct_base_type_t construct_base_type_t;
2754 struct construct_base_type_t {
2755 construct_type_t construct_type;
2759 static construct_type_t *parse_pointer_declarator(void)
2763 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2764 memset(pointer, 0, sizeof(pointer[0]));
2765 pointer->construct_type.kind = CONSTRUCT_POINTER;
2766 pointer->type_qualifiers = parse_type_qualifiers();
2768 return (construct_type_t*) pointer;
2771 static construct_type_t *parse_array_declarator(void)
2774 add_anchor_token(']');
2776 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2777 memset(array, 0, sizeof(array[0]));
2778 array->construct_type.kind = CONSTRUCT_ARRAY;
2780 if(token.type == T_static) {
2781 array->is_static = true;
2785 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2786 if(type_qualifiers != 0) {
2787 if(token.type == T_static) {
2788 array->is_static = true;
2792 array->type_qualifiers = type_qualifiers;
2794 if(token.type == '*' && look_ahead(1)->type == ']') {
2795 array->is_variable = true;
2797 } else if(token.type != ']') {
2798 array->size = parse_assignment_expression();
2801 rem_anchor_token(']');
2804 return (construct_type_t*) array;
2809 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2812 add_anchor_token(')');
2815 if(declaration != NULL) {
2816 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2818 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2821 declaration_t *parameters = parse_parameters(&type->function);
2822 if(declaration != NULL) {
2823 declaration->scope.declarations = parameters;
2826 construct_function_type_t *construct_function_type =
2827 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2828 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2829 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2830 construct_function_type->function_type = type;
2832 rem_anchor_token(')');
2836 return (construct_type_t*) construct_function_type;
2839 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2840 bool may_be_abstract)
2842 /* construct a single linked list of construct_type_t's which describe
2843 * how to construct the final declarator type */
2844 construct_type_t *first = NULL;
2845 construct_type_t *last = NULL;
2848 while(token.type == '*') {
2849 construct_type_t *type = parse_pointer_declarator();
2860 /* TODO: find out if this is correct */
2863 construct_type_t *inner_types = NULL;
2865 switch(token.type) {
2867 if(declaration == NULL) {
2868 errorf(HERE, "no identifier expected in typename");
2870 declaration->symbol = token.v.symbol;
2871 declaration->source_position = token.source_position;
2877 add_anchor_token(')');
2878 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2879 rem_anchor_token(')');
2885 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2886 /* avoid a loop in the outermost scope, because eat_statement doesn't
2888 if(token.type == '}' && current_function == NULL) {
2896 construct_type_t *p = last;
2899 construct_type_t *type;
2900 switch(token.type) {
2902 type = parse_function_declarator(declaration);
2905 type = parse_array_declarator();
2908 goto declarator_finished;
2911 /* insert in the middle of the list (behind p) */
2913 type->next = p->next;
2924 declarator_finished:
2927 /* append inner_types at the end of the list, we don't to set last anymore
2928 * as it's not needed anymore */
2930 assert(first == NULL);
2931 first = inner_types;
2933 last->next = inner_types;
2941 static type_t *construct_declarator_type(construct_type_t *construct_list,
2944 construct_type_t *iter = construct_list;
2945 for( ; iter != NULL; iter = iter->next) {
2946 switch(iter->kind) {
2947 case CONSTRUCT_INVALID:
2948 internal_errorf(HERE, "invalid type construction found");
2949 case CONSTRUCT_FUNCTION: {
2950 construct_function_type_t *construct_function_type
2951 = (construct_function_type_t*) iter;
2953 type_t *function_type = construct_function_type->function_type;
2955 function_type->function.return_type = type;
2957 type_t *skipped_return_type = skip_typeref(type);
2958 if (is_type_function(skipped_return_type)) {
2959 errorf(HERE, "function returning function is not allowed");
2960 type = type_error_type;
2961 } else if (is_type_array(skipped_return_type)) {
2962 errorf(HERE, "function returning array is not allowed");
2963 type = type_error_type;
2965 type = function_type;
2970 case CONSTRUCT_POINTER: {
2971 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2972 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2973 pointer_type->pointer.points_to = type;
2974 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2976 type = pointer_type;
2980 case CONSTRUCT_ARRAY: {
2981 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2982 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2984 expression_t *size_expression = parsed_array->size;
2985 if(size_expression != NULL) {
2987 = create_implicit_cast(size_expression, type_size_t);
2990 array_type->base.qualifiers = parsed_array->type_qualifiers;
2991 array_type->array.element_type = type;
2992 array_type->array.is_static = parsed_array->is_static;
2993 array_type->array.is_variable = parsed_array->is_variable;
2994 array_type->array.size_expression = size_expression;
2996 if(size_expression != NULL) {
2997 if(is_constant_expression(size_expression)) {
2998 array_type->array.size_constant = true;
2999 array_type->array.size
3000 = fold_constant(size_expression);
3002 array_type->array.is_vla = true;
3006 type_t *skipped_type = skip_typeref(type);
3007 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3008 errorf(HERE, "array of void is not allowed");
3009 type = type_error_type;
3017 type_t *hashed_type = typehash_insert(type);
3018 if(hashed_type != type) {
3019 /* the function type was constructed earlier freeing it here will
3020 * destroy other types... */
3021 if(iter->kind != CONSTRUCT_FUNCTION) {
3031 static declaration_t *parse_declarator(
3032 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3034 declaration_t *const declaration = allocate_declaration_zero();
3035 declaration->declared_storage_class = specifiers->declared_storage_class;
3036 declaration->modifiers = specifiers->decl_modifiers;
3037 declaration->deprecated = specifiers->deprecated;
3038 declaration->deprecated_string = specifiers->deprecated_string;
3039 declaration->get_property_sym = specifiers->get_property_sym;
3040 declaration->put_property_sym = specifiers->put_property_sym;
3041 declaration->is_inline = specifiers->is_inline;
3043 declaration->storage_class = specifiers->declared_storage_class;
3044 if(declaration->storage_class == STORAGE_CLASS_NONE
3045 && scope != global_scope) {
3046 declaration->storage_class = STORAGE_CLASS_AUTO;
3049 if(specifiers->alignment != 0) {
3050 /* TODO: add checks here */
3051 declaration->alignment = specifiers->alignment;
3054 construct_type_t *construct_type
3055 = parse_inner_declarator(declaration, may_be_abstract);
3056 type_t *const type = specifiers->type;
3057 declaration->type = construct_declarator_type(construct_type, type);
3059 if(construct_type != NULL) {
3060 obstack_free(&temp_obst, construct_type);
3066 static type_t *parse_abstract_declarator(type_t *base_type)
3068 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3070 type_t *result = construct_declarator_type(construct_type, base_type);
3071 if(construct_type != NULL) {
3072 obstack_free(&temp_obst, construct_type);
3078 static declaration_t *append_declaration(declaration_t* const declaration)
3080 if (last_declaration != NULL) {
3081 last_declaration->next = declaration;
3083 scope->declarations = declaration;
3085 last_declaration = declaration;
3090 * Check if the declaration of main is suspicious. main should be a
3091 * function with external linkage, returning int, taking either zero
3092 * arguments, two, or three arguments of appropriate types, ie.
3094 * int main([ int argc, char **argv [, char **env ] ]).
3096 * @param decl the declaration to check
3097 * @param type the function type of the declaration
3099 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3101 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3102 warningf(decl->source_position, "'main' is normally a non-static function");
3104 if (skip_typeref(func_type->return_type) != type_int) {
3105 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3107 const function_parameter_t *parm = func_type->parameters;
3109 type_t *const first_type = parm->type;
3110 if (!types_compatible(skip_typeref(first_type), type_int)) {
3111 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3115 type_t *const second_type = parm->type;
3116 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3117 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3121 type_t *const third_type = parm->type;
3122 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3123 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3127 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3131 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3137 * Check if a symbol is the equal to "main".
3139 static bool is_sym_main(const symbol_t *const sym)
3141 return strcmp(sym->string, "main") == 0;
3144 static declaration_t *internal_record_declaration(
3145 declaration_t *const declaration,
3146 const bool is_function_definition)
3148 const symbol_t *const symbol = declaration->symbol;
3149 const namespace_t namespc = (namespace_t)declaration->namespc;
3151 type_t *const orig_type = declaration->type;
3152 type_t *const type = skip_typeref(orig_type);
3153 if (is_type_function(type) &&
3154 type->function.unspecified_parameters &&
3155 warning.strict_prototypes) {
3156 warningf(declaration->source_position,
3157 "function declaration '%#T' is not a prototype",
3158 orig_type, declaration->symbol);
3161 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3162 check_type_of_main(declaration, &type->function);
3165 assert(declaration->symbol != NULL);
3166 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3168 assert(declaration != previous_declaration);
3169 if (previous_declaration != NULL) {
3170 if (previous_declaration->parent_scope == scope) {
3171 /* can happen for K&R style declarations */
3172 if(previous_declaration->type == NULL) {
3173 previous_declaration->type = declaration->type;
3176 const type_t *prev_type = skip_typeref(previous_declaration->type);
3177 if (!types_compatible(type, prev_type)) {
3178 errorf(declaration->source_position,
3179 "declaration '%#T' is incompatible with "
3180 "previous declaration '%#T'",
3181 orig_type, symbol, previous_declaration->type, symbol);
3182 errorf(previous_declaration->source_position,
3183 "previous declaration of '%Y' was here", symbol);
3185 unsigned old_storage_class = previous_declaration->storage_class;
3186 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3187 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3188 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3189 return previous_declaration;
3192 unsigned new_storage_class = declaration->storage_class;
3194 if(is_type_incomplete(prev_type)) {
3195 previous_declaration->type = type;
3199 /* pretend no storage class means extern for function
3200 * declarations (except if the previous declaration is neither
3201 * none nor extern) */
3202 if (is_type_function(type)) {
3203 switch (old_storage_class) {
3204 case STORAGE_CLASS_NONE:
3205 old_storage_class = STORAGE_CLASS_EXTERN;
3207 case STORAGE_CLASS_EXTERN:
3208 if (is_function_definition) {
3209 if (warning.missing_prototypes &&
3210 prev_type->function.unspecified_parameters &&
3211 !is_sym_main(symbol)) {
3212 warningf(declaration->source_position,
3213 "no previous prototype for '%#T'",
3216 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3217 new_storage_class = STORAGE_CLASS_EXTERN;
3225 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3226 new_storage_class == STORAGE_CLASS_EXTERN) {
3227 warn_redundant_declaration:
3228 if (warning.redundant_decls) {
3229 warningf(declaration->source_position,
3230 "redundant declaration for '%Y'", symbol);
3231 warningf(previous_declaration->source_position,
3232 "previous declaration of '%Y' was here",
3235 } else if (current_function == NULL) {
3236 if (old_storage_class != STORAGE_CLASS_STATIC &&
3237 new_storage_class == STORAGE_CLASS_STATIC) {
3238 errorf(declaration->source_position,
3239 "static declaration of '%Y' follows non-static declaration",
3241 errorf(previous_declaration->source_position,
3242 "previous declaration of '%Y' was here", symbol);
3244 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3245 goto warn_redundant_declaration;
3247 if (new_storage_class == STORAGE_CLASS_NONE) {
3248 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3249 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3253 if (old_storage_class == new_storage_class) {
3254 errorf(declaration->source_position,
3255 "redeclaration of '%Y'", symbol);
3257 errorf(declaration->source_position,
3258 "redeclaration of '%Y' with different linkage",
3261 errorf(previous_declaration->source_position,
3262 "previous declaration of '%Y' was here", symbol);
3265 return previous_declaration;
3267 } else if (is_function_definition) {
3268 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3269 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3270 warningf(declaration->source_position,
3271 "no previous prototype for '%#T'", orig_type, symbol);
3272 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3273 warningf(declaration->source_position,
3274 "no previous declaration for '%#T'", orig_type,
3278 } else if (warning.missing_declarations &&
3279 scope == global_scope &&
3280 !is_type_function(type) && (
3281 declaration->storage_class == STORAGE_CLASS_NONE ||
3282 declaration->storage_class == STORAGE_CLASS_THREAD
3284 warningf(declaration->source_position,
3285 "no previous declaration for '%#T'", orig_type, symbol);
3288 assert(declaration->parent_scope == NULL);
3289 assert(scope != NULL);
3291 declaration->parent_scope = scope;
3293 environment_push(declaration);
3294 return append_declaration(declaration);
3297 static declaration_t *record_declaration(declaration_t *declaration)
3299 return internal_record_declaration(declaration, false);
3302 static declaration_t *record_function_definition(declaration_t *declaration)
3304 return internal_record_declaration(declaration, true);
3307 static void parser_error_multiple_definition(declaration_t *declaration,
3308 const source_position_t source_position)
3310 errorf(source_position, "multiple definition of symbol '%Y'",
3311 declaration->symbol);
3312 errorf(declaration->source_position,
3313 "this is the location of the previous definition.");
3316 static bool is_declaration_specifier(const token_t *token,
3317 bool only_type_specifiers)
3319 switch(token->type) {
3323 return is_typedef_symbol(token->v.symbol);
3325 case T___extension__:
3328 return !only_type_specifiers;
3335 static void parse_init_declarator_rest(declaration_t *declaration)
3339 type_t *orig_type = declaration->type;
3340 type_t *type = skip_typeref(orig_type);
3342 if(declaration->init.initializer != NULL) {
3343 parser_error_multiple_definition(declaration, token.source_position);
3346 bool must_be_constant = false;
3347 if(declaration->storage_class == STORAGE_CLASS_STATIC
3348 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3349 || declaration->parent_scope == global_scope) {
3350 must_be_constant = true;
3353 parse_initializer_env_t env;
3354 env.type = orig_type;
3355 env.must_be_constant = must_be_constant;
3356 env.declaration = declaration;
3358 initializer_t *initializer = parse_initializer(&env);
3360 if(env.type != orig_type) {
3361 orig_type = env.type;
3362 type = skip_typeref(orig_type);
3363 declaration->type = env.type;
3366 if(is_type_function(type)) {
3367 errorf(declaration->source_position,
3368 "initializers not allowed for function types at declator '%Y' (type '%T')",
3369 declaration->symbol, orig_type);
3371 declaration->init.initializer = initializer;
3375 /* parse rest of a declaration without any declarator */
3376 static void parse_anonymous_declaration_rest(
3377 const declaration_specifiers_t *specifiers,
3378 parsed_declaration_func finished_declaration)
3382 declaration_t *const declaration = allocate_declaration_zero();
3383 declaration->type = specifiers->type;
3384 declaration->declared_storage_class = specifiers->declared_storage_class;
3385 declaration->source_position = specifiers->source_position;
3386 declaration->modifiers = specifiers->decl_modifiers;
3388 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3389 warningf(declaration->source_position, "useless storage class in empty declaration");
3391 declaration->storage_class = STORAGE_CLASS_NONE;
3393 type_t *type = declaration->type;
3394 switch (type->kind) {
3395 case TYPE_COMPOUND_STRUCT:
3396 case TYPE_COMPOUND_UNION: {
3397 if (type->compound.declaration->symbol == NULL) {
3398 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3407 warningf(declaration->source_position, "empty declaration");
3411 finished_declaration(declaration);
3414 static void parse_declaration_rest(declaration_t *ndeclaration,
3415 const declaration_specifiers_t *specifiers,
3416 parsed_declaration_func finished_declaration)
3418 add_anchor_token(';');
3419 add_anchor_token('=');
3420 add_anchor_token(',');
3422 declaration_t *declaration = finished_declaration(ndeclaration);
3424 type_t *orig_type = declaration->type;
3425 type_t *type = skip_typeref(orig_type);
3427 if (type->kind != TYPE_FUNCTION &&
3428 declaration->is_inline &&
3429 is_type_valid(type)) {
3430 warningf(declaration->source_position,
3431 "variable '%Y' declared 'inline'\n", declaration->symbol);
3434 if(token.type == '=') {
3435 parse_init_declarator_rest(declaration);
3438 if(token.type != ',')
3442 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3447 rem_anchor_token(';');
3448 rem_anchor_token('=');
3449 rem_anchor_token(',');
3452 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3454 symbol_t *symbol = declaration->symbol;
3455 if(symbol == NULL) {
3456 errorf(HERE, "anonymous declaration not valid as function parameter");
3459 namespace_t namespc = (namespace_t) declaration->namespc;
3460 if(namespc != NAMESPACE_NORMAL) {
3461 return record_declaration(declaration);
3464 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3465 if(previous_declaration == NULL ||
3466 previous_declaration->parent_scope != scope) {
3467 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3472 if(previous_declaration->type == NULL) {
3473 previous_declaration->type = declaration->type;
3474 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3475 previous_declaration->storage_class = declaration->storage_class;
3476 previous_declaration->parent_scope = scope;
3477 return previous_declaration;
3479 return record_declaration(declaration);
3483 static void parse_declaration(parsed_declaration_func finished_declaration)
3485 declaration_specifiers_t specifiers;
3486 memset(&specifiers, 0, sizeof(specifiers));
3487 parse_declaration_specifiers(&specifiers);
3489 if(token.type == ';') {
3490 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3492 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3493 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3497 static void parse_kr_declaration_list(declaration_t *declaration)
3499 type_t *type = skip_typeref(declaration->type);
3500 if(!is_type_function(type))
3503 if(!type->function.kr_style_parameters)
3506 /* push function parameters */
3507 int top = environment_top();
3508 scope_t *last_scope = scope;
3509 set_scope(&declaration->scope);
3511 declaration_t *parameter = declaration->scope.declarations;
3512 for( ; parameter != NULL; parameter = parameter->next) {
3513 assert(parameter->parent_scope == NULL);
3514 parameter->parent_scope = scope;
3515 environment_push(parameter);
3518 /* parse declaration list */
3519 while(is_declaration_specifier(&token, false)) {
3520 parse_declaration(finished_kr_declaration);
3523 /* pop function parameters */
3524 assert(scope == &declaration->scope);
3525 set_scope(last_scope);
3526 environment_pop_to(top);
3528 /* update function type */
3529 type_t *new_type = duplicate_type(type);
3530 new_type->function.kr_style_parameters = false;
3532 function_parameter_t *parameters = NULL;
3533 function_parameter_t *last_parameter = NULL;
3535 declaration_t *parameter_declaration = declaration->scope.declarations;
3536 for( ; parameter_declaration != NULL;
3537 parameter_declaration = parameter_declaration->next) {
3538 type_t *parameter_type = parameter_declaration->type;
3539 if(parameter_type == NULL) {
3541 errorf(HERE, "no type specified for function parameter '%Y'",
3542 parameter_declaration->symbol);
3544 if (warning.implicit_int) {
3545 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3546 parameter_declaration->symbol);
3548 parameter_type = type_int;
3549 parameter_declaration->type = parameter_type;
3553 semantic_parameter(parameter_declaration);
3554 parameter_type = parameter_declaration->type;
3556 function_parameter_t *function_parameter
3557 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3558 memset(function_parameter, 0, sizeof(function_parameter[0]));
3560 function_parameter->type = parameter_type;
3561 if(last_parameter != NULL) {
3562 last_parameter->next = function_parameter;
3564 parameters = function_parameter;
3566 last_parameter = function_parameter;
3568 new_type->function.parameters = parameters;
3570 type = typehash_insert(new_type);
3571 if(type != new_type) {
3572 obstack_free(type_obst, new_type);
3575 declaration->type = type;
3578 static bool first_err = true;
3581 * When called with first_err set, prints the name of the current function,
3584 static void print_in_function(void) {
3587 diagnosticf("%s: In function '%Y':\n",
3588 current_function->source_position.input_name,
3589 current_function->symbol);
3594 * Check if all labels are defined in the current function.
3595 * Check if all labels are used in the current function.
3597 static void check_labels(void)
3599 for (const goto_statement_t *goto_statement = goto_first;
3600 goto_statement != NULL;
3601 goto_statement = goto_statement->next) {
3602 declaration_t *label = goto_statement->label;
3605 if (label->source_position.input_name == NULL) {
3606 print_in_function();
3607 errorf(goto_statement->base.source_position,
3608 "label '%Y' used but not defined", label->symbol);
3611 goto_first = goto_last = NULL;
3613 if (warning.unused_label) {
3614 for (const label_statement_t *label_statement = label_first;
3615 label_statement != NULL;
3616 label_statement = label_statement->next) {
3617 const declaration_t *label = label_statement->label;
3619 if (! label->used) {
3620 print_in_function();
3621 warningf(label_statement->base.source_position,
3622 "label '%Y' defined but not used", label->symbol);
3626 label_first = label_last = NULL;
3630 * Check declarations of current_function for unused entities.
3632 static void check_declarations(void)
3634 if (warning.unused_parameter) {
3635 const scope_t *scope = ¤t_function->scope;
3637 const declaration_t *parameter = scope->declarations;
3638 for (; parameter != NULL; parameter = parameter->next) {
3639 if (! parameter->used) {
3640 print_in_function();
3641 warningf(parameter->source_position,
3642 "unused parameter '%Y'", parameter->symbol);
3646 if (warning.unused_variable) {
3650 static void parse_external_declaration(void)
3652 /* function-definitions and declarations both start with declaration
3654 declaration_specifiers_t specifiers;
3655 memset(&specifiers, 0, sizeof(specifiers));
3657 add_anchor_token(';');
3658 parse_declaration_specifiers(&specifiers);
3659 rem_anchor_token(';');
3661 /* must be a declaration */
3662 if(token.type == ';') {
3663 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3667 add_anchor_token(',');
3668 add_anchor_token('=');
3669 rem_anchor_token(';');
3671 /* declarator is common to both function-definitions and declarations */
3672 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3674 rem_anchor_token(',');
3675 rem_anchor_token('=');
3676 rem_anchor_token(';');
3678 /* must be a declaration */
3679 if(token.type == ',' || token.type == '=' || token.type == ';') {
3680 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3684 /* must be a function definition */
3685 parse_kr_declaration_list(ndeclaration);
3687 if(token.type != '{') {
3688 parse_error_expected("while parsing function definition", '{', 0);
3689 eat_until_matching_token(';');
3693 type_t *type = ndeclaration->type;
3695 /* note that we don't skip typerefs: the standard doesn't allow them here
3696 * (so we can't use is_type_function here) */
3697 if(type->kind != TYPE_FUNCTION) {
3698 if (is_type_valid(type)) {
3699 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3700 type, ndeclaration->symbol);
3706 /* § 6.7.5.3 (14) a function definition with () means no
3707 * parameters (and not unspecified parameters) */
3708 if(type->function.unspecified_parameters) {
3709 type_t *duplicate = duplicate_type(type);
3710 duplicate->function.unspecified_parameters = false;
3712 type = typehash_insert(duplicate);
3713 if(type != duplicate) {
3714 obstack_free(type_obst, duplicate);
3716 ndeclaration->type = type;
3719 declaration_t *const declaration = record_function_definition(ndeclaration);
3720 if(ndeclaration != declaration) {
3721 declaration->scope = ndeclaration->scope;
3723 type = skip_typeref(declaration->type);
3725 /* push function parameters and switch scope */
3726 int top = environment_top();
3727 scope_t *last_scope = scope;
3728 set_scope(&declaration->scope);
3730 declaration_t *parameter = declaration->scope.declarations;
3731 for( ; parameter != NULL; parameter = parameter->next) {
3732 if(parameter->parent_scope == &ndeclaration->scope) {
3733 parameter->parent_scope = scope;
3735 assert(parameter->parent_scope == NULL
3736 || parameter->parent_scope == scope);
3737 parameter->parent_scope = scope;
3738 environment_push(parameter);
3741 if(declaration->init.statement != NULL) {
3742 parser_error_multiple_definition(declaration, token.source_position);
3744 goto end_of_parse_external_declaration;
3746 /* parse function body */
3747 int label_stack_top = label_top();
3748 declaration_t *old_current_function = current_function;
3749 current_function = declaration;
3751 declaration->init.statement = parse_compound_statement();
3754 check_declarations();
3756 assert(current_function == declaration);
3757 current_function = old_current_function;
3758 label_pop_to(label_stack_top);
3761 end_of_parse_external_declaration:
3762 assert(scope == &declaration->scope);
3763 set_scope(last_scope);
3764 environment_pop_to(top);
3767 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3768 source_position_t source_position)
3770 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3771 type->bitfield.base = base;
3772 type->bitfield.size = size;
3777 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3780 declaration_t *iter = compound_declaration->scope.declarations;
3781 for( ; iter != NULL; iter = iter->next) {
3782 if(iter->namespc != NAMESPACE_NORMAL)
3785 if(iter->symbol == NULL) {
3786 type_t *type = skip_typeref(iter->type);
3787 if(is_type_compound(type)) {
3788 declaration_t *result
3789 = find_compound_entry(type->compound.declaration, symbol);
3796 if(iter->symbol == symbol) {
3804 static void parse_compound_declarators(declaration_t *struct_declaration,
3805 const declaration_specifiers_t *specifiers)
3807 declaration_t *last_declaration = struct_declaration->scope.declarations;
3808 if(last_declaration != NULL) {
3809 while(last_declaration->next != NULL) {
3810 last_declaration = last_declaration->next;
3815 declaration_t *declaration;
3817 if(token.type == ':') {
3818 source_position_t source_position = HERE;
3821 type_t *base_type = specifiers->type;
3822 expression_t *size = parse_constant_expression();
3824 if(!is_type_integer(skip_typeref(base_type))) {
3825 errorf(HERE, "bitfield base type '%T' is not an integer type",
3829 type_t *type = make_bitfield_type(base_type, size, source_position);
3831 declaration = allocate_declaration_zero();
3832 declaration->namespc = NAMESPACE_NORMAL;
3833 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3834 declaration->storage_class = STORAGE_CLASS_NONE;
3835 declaration->source_position = source_position;
3836 declaration->modifiers = specifiers->decl_modifiers;
3837 declaration->type = type;
3839 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3841 type_t *orig_type = declaration->type;
3842 type_t *type = skip_typeref(orig_type);
3844 if(token.type == ':') {
3845 source_position_t source_position = HERE;
3847 expression_t *size = parse_constant_expression();
3849 if(!is_type_integer(type)) {
3850 errorf(HERE, "bitfield base type '%T' is not an "
3851 "integer type", orig_type);
3854 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3855 declaration->type = bitfield_type;
3857 /* TODO we ignore arrays for now... what is missing is a check
3858 * that they're at the end of the struct */
3859 if(is_type_incomplete(type) && !is_type_array(type)) {
3861 "compound member '%Y' has incomplete type '%T'",
3862 declaration->symbol, orig_type);
3863 } else if(is_type_function(type)) {
3864 errorf(HERE, "compound member '%Y' must not have function "
3865 "type '%T'", declaration->symbol, orig_type);
3870 /* make sure we don't define a symbol multiple times */
3871 symbol_t *symbol = declaration->symbol;
3872 if(symbol != NULL) {
3873 declaration_t *prev_decl
3874 = find_compound_entry(struct_declaration, symbol);
3876 if(prev_decl != NULL) {
3877 assert(prev_decl->symbol == symbol);
3878 errorf(declaration->source_position,
3879 "multiple declarations of symbol '%Y'", symbol);
3880 errorf(prev_decl->source_position,
3881 "previous declaration of '%Y' was here", symbol);
3885 /* append declaration */
3886 if(last_declaration != NULL) {
3887 last_declaration->next = declaration;
3889 struct_declaration->scope.declarations = declaration;
3891 last_declaration = declaration;
3893 if(token.type != ',')
3903 static void parse_compound_type_entries(declaration_t *compound_declaration)
3906 add_anchor_token('}');
3908 while(token.type != '}' && token.type != T_EOF) {
3909 declaration_specifiers_t specifiers;
3910 memset(&specifiers, 0, sizeof(specifiers));
3911 parse_declaration_specifiers(&specifiers);
3913 parse_compound_declarators(compound_declaration, &specifiers);
3915 rem_anchor_token('}');
3917 if(token.type == T_EOF) {
3918 errorf(HERE, "EOF while parsing struct");
3923 static type_t *parse_typename(void)
3925 declaration_specifiers_t specifiers;
3926 memset(&specifiers, 0, sizeof(specifiers));
3927 parse_declaration_specifiers(&specifiers);
3928 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3929 /* TODO: improve error message, user does probably not know what a
3930 * storage class is...
3932 errorf(HERE, "typename may not have a storage class");
3935 type_t *result = parse_abstract_declarator(specifiers.type);
3943 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3944 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3945 expression_t *left);
3947 typedef struct expression_parser_function_t expression_parser_function_t;
3948 struct expression_parser_function_t {
3949 unsigned precedence;
3950 parse_expression_function parser;
3951 unsigned infix_precedence;
3952 parse_expression_infix_function infix_parser;
3955 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3958 * Creates a new invalid expression.
3960 static expression_t *create_invalid_expression(void)
3962 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3963 expression->base.source_position = token.source_position;
3968 * Prints an error message if an expression was expected but not read
3970 static expression_t *expected_expression_error(void)
3972 /* skip the error message if the error token was read */
3973 if (token.type != T_ERROR) {
3974 errorf(HERE, "expected expression, got token '%K'", &token);
3978 return create_invalid_expression();
3982 * Parse a string constant.
3984 static expression_t *parse_string_const(void)
3987 if (token.type == T_STRING_LITERAL) {
3988 string_t res = token.v.string;
3990 while (token.type == T_STRING_LITERAL) {
3991 res = concat_strings(&res, &token.v.string);
3994 if (token.type != T_WIDE_STRING_LITERAL) {
3995 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3996 /* note: that we use type_char_ptr here, which is already the
3997 * automatic converted type. revert_automatic_type_conversion
3998 * will construct the array type */
3999 cnst->base.type = type_char_ptr;
4000 cnst->string.value = res;
4004 wres = concat_string_wide_string(&res, &token.v.wide_string);
4006 wres = token.v.wide_string;
4011 switch (token.type) {
4012 case T_WIDE_STRING_LITERAL:
4013 wres = concat_wide_strings(&wres, &token.v.wide_string);
4016 case T_STRING_LITERAL:
4017 wres = concat_wide_string_string(&wres, &token.v.string);
4021 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4022 cnst->base.type = type_wchar_t_ptr;
4023 cnst->wide_string.value = wres;
4032 * Parse an integer constant.
4034 static expression_t *parse_int_const(void)
4036 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4037 cnst->base.source_position = HERE;
4038 cnst->base.type = token.datatype;
4039 cnst->conste.v.int_value = token.v.intvalue;
4047 * Parse a character constant.
4049 static expression_t *parse_character_constant(void)
4051 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4053 cnst->base.source_position = HERE;
4054 cnst->base.type = token.datatype;
4055 cnst->conste.v.character = token.v.string;
4057 if (cnst->conste.v.character.size != 1) {
4058 if (warning.multichar && (c_mode & _GNUC)) {
4060 warningf(HERE, "multi-character character constant");
4062 errorf(HERE, "more than 1 characters in character constant");
4071 * Parse a wide character constant.
4073 static expression_t *parse_wide_character_constant(void)
4075 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4077 cnst->base.source_position = HERE;
4078 cnst->base.type = token.datatype;
4079 cnst->conste.v.wide_character = token.v.wide_string;
4081 if (cnst->conste.v.wide_character.size != 1) {
4082 if (warning.multichar && (c_mode & _GNUC)) {
4084 warningf(HERE, "multi-character character constant");
4086 errorf(HERE, "more than 1 characters in character constant");
4095 * Parse a float constant.
4097 static expression_t *parse_float_const(void)
4099 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4100 cnst->base.type = token.datatype;
4101 cnst->conste.v.float_value = token.v.floatvalue;
4108 static declaration_t *create_implicit_function(symbol_t *symbol,
4109 const source_position_t source_position)
4111 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4112 ntype->function.return_type = type_int;
4113 ntype->function.unspecified_parameters = true;
4115 type_t *type = typehash_insert(ntype);
4120 declaration_t *const declaration = allocate_declaration_zero();
4121 declaration->storage_class = STORAGE_CLASS_EXTERN;
4122 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4123 declaration->type = type;
4124 declaration->symbol = symbol;
4125 declaration->source_position = source_position;
4126 declaration->parent_scope = global_scope;
4128 scope_t *old_scope = scope;
4129 set_scope(global_scope);
4131 environment_push(declaration);
4132 /* prepends the declaration to the global declarations list */
4133 declaration->next = scope->declarations;
4134 scope->declarations = declaration;
4136 assert(scope == global_scope);
4137 set_scope(old_scope);
4143 * Creates a return_type (func)(argument_type) function type if not
4146 * @param return_type the return type
4147 * @param argument_type the argument type
4149 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4151 function_parameter_t *parameter
4152 = obstack_alloc(type_obst, sizeof(parameter[0]));
4153 memset(parameter, 0, sizeof(parameter[0]));
4154 parameter->type = argument_type;
4156 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4157 type->function.return_type = return_type;
4158 type->function.parameters = parameter;
4160 type_t *result = typehash_insert(type);
4161 if(result != type) {
4169 * Creates a function type for some function like builtins.
4171 * @param symbol the symbol describing the builtin
4173 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4175 switch(symbol->ID) {
4176 case T___builtin_alloca:
4177 return make_function_1_type(type_void_ptr, type_size_t);
4178 case T___builtin_nan:
4179 return make_function_1_type(type_double, type_char_ptr);
4180 case T___builtin_nanf:
4181 return make_function_1_type(type_float, type_char_ptr);
4182 case T___builtin_nand:
4183 return make_function_1_type(type_long_double, type_char_ptr);
4184 case T___builtin_va_end:
4185 return make_function_1_type(type_void, type_valist);
4187 internal_errorf(HERE, "not implemented builtin symbol found");
4192 * Performs automatic type cast as described in § 6.3.2.1.
4194 * @param orig_type the original type
4196 static type_t *automatic_type_conversion(type_t *orig_type)
4198 type_t *type = skip_typeref(orig_type);
4199 if(is_type_array(type)) {
4200 array_type_t *array_type = &type->array;
4201 type_t *element_type = array_type->element_type;
4202 unsigned qualifiers = array_type->type.qualifiers;
4204 return make_pointer_type(element_type, qualifiers);
4207 if(is_type_function(type)) {
4208 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4215 * reverts the automatic casts of array to pointer types and function
4216 * to function-pointer types as defined § 6.3.2.1
4218 type_t *revert_automatic_type_conversion(const expression_t *expression)
4220 switch (expression->kind) {
4221 case EXPR_REFERENCE: return expression->reference.declaration->type;
4222 case EXPR_SELECT: return expression->select.compound_entry->type;
4224 case EXPR_UNARY_DEREFERENCE: {
4225 const expression_t *const value = expression->unary.value;
4226 type_t *const type = skip_typeref(value->base.type);
4227 assert(is_type_pointer(type));
4228 return type->pointer.points_to;
4231 case EXPR_BUILTIN_SYMBOL:
4232 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4234 case EXPR_ARRAY_ACCESS: {
4235 const expression_t *array_ref = expression->array_access.array_ref;
4236 type_t *type_left = skip_typeref(array_ref->base.type);
4237 if (!is_type_valid(type_left))
4239 assert(is_type_pointer(type_left));
4240 return type_left->pointer.points_to;
4243 case EXPR_STRING_LITERAL: {
4244 size_t size = expression->string.value.size;
4245 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4248 case EXPR_WIDE_STRING_LITERAL: {
4249 size_t size = expression->wide_string.value.size;
4250 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4253 case EXPR_COMPOUND_LITERAL:
4254 return expression->compound_literal.type;
4259 return expression->base.type;
4262 static expression_t *parse_reference(void)
4264 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4266 reference_expression_t *ref = &expression->reference;
4267 ref->symbol = token.v.symbol;
4269 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4271 source_position_t source_position = token.source_position;
4274 if(declaration == NULL) {
4275 if (! strict_mode && token.type == '(') {
4276 /* an implicitly defined function */
4277 if (warning.implicit_function_declaration) {
4278 warningf(HERE, "implicit declaration of function '%Y'",
4282 declaration = create_implicit_function(ref->symbol,
4285 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4286 return create_invalid_expression();
4290 type_t *type = declaration->type;
4292 /* we always do the auto-type conversions; the & and sizeof parser contains
4293 * code to revert this! */
4294 type = automatic_type_conversion(type);
4296 ref->declaration = declaration;
4297 ref->base.type = type;
4299 /* this declaration is used */
4300 declaration->used = true;
4302 /* check for deprecated functions */
4303 if(declaration->deprecated != 0) {
4304 const char *prefix = "";
4305 if (is_type_function(declaration->type))
4306 prefix = "function ";
4308 if (declaration->deprecated_string != NULL) {
4309 warningf(source_position,
4310 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4311 declaration->deprecated_string);
4313 warningf(source_position,
4314 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4321 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4325 /* TODO check if explicit cast is allowed and issue warnings/errors */
4328 static expression_t *parse_compound_literal(type_t *type)
4330 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4332 parse_initializer_env_t env;
4334 env.declaration = NULL;
4335 env.must_be_constant = false;
4336 initializer_t *initializer = parse_initializer(&env);
4339 expression->compound_literal.initializer = initializer;
4340 expression->compound_literal.type = type;
4341 expression->base.type = automatic_type_conversion(type);
4347 * Parse a cast expression.
4349 static expression_t *parse_cast(void)
4351 source_position_t source_position = token.source_position;
4353 type_t *type = parse_typename();
4355 /* matching add_anchor_token() is at call site */
4356 rem_anchor_token(')');
4359 if(token.type == '{') {
4360 return parse_compound_literal(type);
4363 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4364 cast->base.source_position = source_position;
4366 expression_t *value = parse_sub_expression(20);
4368 check_cast_allowed(value, type);
4370 cast->base.type = type;
4371 cast->unary.value = value;
4375 return create_invalid_expression();
4379 * Parse a statement expression.
4381 static expression_t *parse_statement_expression(void)
4383 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4385 statement_t *statement = parse_compound_statement();
4386 expression->statement.statement = statement;
4387 expression->base.source_position = statement->base.source_position;
4389 /* find last statement and use its type */
4390 type_t *type = type_void;
4391 const statement_t *stmt = statement->compound.statements;
4393 while (stmt->base.next != NULL)
4394 stmt = stmt->base.next;
4396 if (stmt->kind == STATEMENT_EXPRESSION) {
4397 type = stmt->expression.expression->base.type;
4400 warningf(expression->base.source_position, "empty statement expression ({})");
4402 expression->base.type = type;
4408 return create_invalid_expression();
4412 * Parse a braced expression.
4414 static expression_t *parse_brace_expression(void)
4417 add_anchor_token(')');
4419 switch(token.type) {
4421 /* gcc extension: a statement expression */
4422 return parse_statement_expression();
4426 return parse_cast();
4428 if(is_typedef_symbol(token.v.symbol)) {
4429 return parse_cast();
4433 expression_t *result = parse_expression();
4434 rem_anchor_token(')');
4439 return create_invalid_expression();
4442 static expression_t *parse_function_keyword(void)
4447 if (current_function == NULL) {
4448 errorf(HERE, "'__func__' used outside of a function");
4451 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4452 expression->base.type = type_char_ptr;
4453 expression->funcname.kind = FUNCNAME_FUNCTION;
4458 static expression_t *parse_pretty_function_keyword(void)
4460 eat(T___PRETTY_FUNCTION__);
4462 if (current_function == NULL) {
4463 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4466 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4467 expression->base.type = type_char_ptr;
4468 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
4473 static expression_t *parse_funcsig_keyword(void)
4477 if (current_function == NULL) {
4478 errorf(HERE, "'__FUNCSIG__' used outside of a function");
4481 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4482 expression->base.type = type_char_ptr;
4483 expression->funcname.kind = FUNCNAME_FUNCSIG;
4488 static expression_t *parse_funcdname_keyword(void)
4490 eat(T___FUNCDNAME__);
4492 if (current_function == NULL) {
4493 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
4496 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
4497 expression->base.type = type_char_ptr;
4498 expression->funcname.kind = FUNCNAME_FUNCDNAME;
4503 static designator_t *parse_designator(void)
4505 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4506 result->source_position = HERE;
4508 if(token.type != T_IDENTIFIER) {
4509 parse_error_expected("while parsing member designator",
4513 result->symbol = token.v.symbol;
4516 designator_t *last_designator = result;
4518 if(token.type == '.') {
4520 if(token.type != T_IDENTIFIER) {
4521 parse_error_expected("while parsing member designator",
4525 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4526 designator->source_position = HERE;
4527 designator->symbol = token.v.symbol;
4530 last_designator->next = designator;
4531 last_designator = designator;
4534 if(token.type == '[') {
4536 add_anchor_token(']');
4537 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4538 designator->source_position = HERE;
4539 designator->array_index = parse_expression();
4540 rem_anchor_token(']');
4542 if(designator->array_index == NULL) {
4546 last_designator->next = designator;
4547 last_designator = designator;
4559 * Parse the __builtin_offsetof() expression.
4561 static expression_t *parse_offsetof(void)
4563 eat(T___builtin_offsetof);
4565 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4566 expression->base.type = type_size_t;
4569 add_anchor_token(',');
4570 type_t *type = parse_typename();
4571 rem_anchor_token(',');
4573 add_anchor_token(')');
4574 designator_t *designator = parse_designator();
4575 rem_anchor_token(')');
4578 expression->offsetofe.type = type;
4579 expression->offsetofe.designator = designator;
4582 memset(&path, 0, sizeof(path));
4583 path.top_type = type;
4584 path.path = NEW_ARR_F(type_path_entry_t, 0);
4586 descend_into_subtype(&path);
4588 if(!walk_designator(&path, designator, true)) {
4589 return create_invalid_expression();
4592 DEL_ARR_F(path.path);
4596 return create_invalid_expression();
4600 * Parses a _builtin_va_start() expression.
4602 static expression_t *parse_va_start(void)
4604 eat(T___builtin_va_start);
4606 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4609 add_anchor_token(',');
4610 expression->va_starte.ap = parse_assignment_expression();
4611 rem_anchor_token(',');
4613 expression_t *const expr = parse_assignment_expression();
4614 if (expr->kind == EXPR_REFERENCE) {
4615 declaration_t *const decl = expr->reference.declaration;
4617 return create_invalid_expression();
4618 if (decl->parent_scope == ¤t_function->scope &&
4619 decl->next == NULL) {
4620 expression->va_starte.parameter = decl;
4625 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4627 return create_invalid_expression();
4631 * Parses a _builtin_va_arg() expression.
4633 static expression_t *parse_va_arg(void)
4635 eat(T___builtin_va_arg);
4637 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4640 expression->va_arge.ap = parse_assignment_expression();
4642 expression->base.type = parse_typename();
4647 return create_invalid_expression();
4650 static expression_t *parse_builtin_symbol(void)
4652 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4654 symbol_t *symbol = token.v.symbol;
4656 expression->builtin_symbol.symbol = symbol;
4659 type_t *type = get_builtin_symbol_type(symbol);
4660 type = automatic_type_conversion(type);
4662 expression->base.type = type;
4667 * Parses a __builtin_constant() expression.
4669 static expression_t *parse_builtin_constant(void)
4671 eat(T___builtin_constant_p);
4673 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4676 add_anchor_token(')');
4677 expression->builtin_constant.value = parse_assignment_expression();
4678 rem_anchor_token(')');
4680 expression->base.type = type_int;
4684 return create_invalid_expression();
4688 * Parses a __builtin_prefetch() expression.
4690 static expression_t *parse_builtin_prefetch(void)
4692 eat(T___builtin_prefetch);
4694 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4697 add_anchor_token(')');
4698 expression->builtin_prefetch.adr = parse_assignment_expression();
4699 if (token.type == ',') {
4701 expression->builtin_prefetch.rw = parse_assignment_expression();
4703 if (token.type == ',') {
4705 expression->builtin_prefetch.locality = parse_assignment_expression();
4707 rem_anchor_token(')');
4709 expression->base.type = type_void;
4713 return create_invalid_expression();
4717 * Parses a __builtin_is_*() compare expression.
4719 static expression_t *parse_compare_builtin(void)
4721 expression_t *expression;
4723 switch(token.type) {
4724 case T___builtin_isgreater:
4725 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4727 case T___builtin_isgreaterequal:
4728 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4730 case T___builtin_isless:
4731 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4733 case T___builtin_islessequal:
4734 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4736 case T___builtin_islessgreater:
4737 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4739 case T___builtin_isunordered:
4740 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4743 internal_errorf(HERE, "invalid compare builtin found");
4746 expression->base.source_position = HERE;
4750 expression->binary.left = parse_assignment_expression();
4752 expression->binary.right = parse_assignment_expression();
4755 type_t *const orig_type_left = expression->binary.left->base.type;
4756 type_t *const orig_type_right = expression->binary.right->base.type;
4758 type_t *const type_left = skip_typeref(orig_type_left);
4759 type_t *const type_right = skip_typeref(orig_type_right);
4760 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4761 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4762 type_error_incompatible("invalid operands in comparison",
4763 expression->base.source_position, orig_type_left, orig_type_right);
4766 semantic_comparison(&expression->binary);
4771 return create_invalid_expression();
4775 * Parses a __builtin_expect() expression.
4777 static expression_t *parse_builtin_expect(void)
4779 eat(T___builtin_expect);
4781 expression_t *expression
4782 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4785 expression->binary.left = parse_assignment_expression();
4787 expression->binary.right = parse_constant_expression();
4790 expression->base.type = expression->binary.left->base.type;
4794 return create_invalid_expression();
4798 * Parses a MS assume() expression.
4800 static expression_t *parse_assume(void) {
4803 expression_t *expression
4804 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4807 add_anchor_token(')');
4808 expression->unary.value = parse_assignment_expression();
4809 rem_anchor_token(')');
4812 expression->base.type = type_void;
4815 return create_invalid_expression();
4819 * Parse a microsoft __noop expression.
4821 static expression_t *parse_noop_expression(void) {
4822 source_position_t source_position = HERE;
4825 if (token.type == '(') {
4826 /* parse arguments */
4828 add_anchor_token(')');
4829 add_anchor_token(',');
4831 if(token.type != ')') {
4833 (void)parse_assignment_expression();
4834 if(token.type != ',')
4840 rem_anchor_token(',');
4841 rem_anchor_token(')');
4844 /* the result is a (int)0 */
4845 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4846 cnst->base.source_position = source_position;
4847 cnst->base.type = type_int;
4848 cnst->conste.v.int_value = 0;
4849 cnst->conste.is_ms_noop = true;
4854 return create_invalid_expression();
4858 * Parses a primary expression.
4860 static expression_t *parse_primary_expression(void)
4862 switch (token.type) {
4863 case T_INTEGER: return parse_int_const();
4864 case T_CHARACTER_CONSTANT: return parse_character_constant();
4865 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4866 case T_FLOATINGPOINT: return parse_float_const();
4867 case T_STRING_LITERAL:
4868 case T_WIDE_STRING_LITERAL: return parse_string_const();
4869 case T_IDENTIFIER: return parse_reference();
4870 case T___FUNCTION__:
4871 case T___func__: return parse_function_keyword();
4872 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4873 case T___FUNCSIG__: return parse_funcsig_keyword();
4874 case T___FUNCDNAME__: return parse_funcdname_keyword();
4875 case T___builtin_offsetof: return parse_offsetof();
4876 case T___builtin_va_start: return parse_va_start();
4877 case T___builtin_va_arg: return parse_va_arg();
4878 case T___builtin_expect: return parse_builtin_expect();
4879 case T___builtin_alloca:
4880 case T___builtin_nan:
4881 case T___builtin_nand:
4882 case T___builtin_nanf:
4883 case T___builtin_va_end: return parse_builtin_symbol();
4884 case T___builtin_isgreater:
4885 case T___builtin_isgreaterequal:
4886 case T___builtin_isless:
4887 case T___builtin_islessequal:
4888 case T___builtin_islessgreater:
4889 case T___builtin_isunordered: return parse_compare_builtin();
4890 case T___builtin_constant_p: return parse_builtin_constant();
4891 case T___builtin_prefetch: return parse_builtin_prefetch();
4892 case T__assume: return parse_assume();
4894 case '(': return parse_brace_expression();
4895 case T___noop: return parse_noop_expression();
4898 errorf(HERE, "unexpected token %K, expected an expression", &token);
4899 return create_invalid_expression();
4903 * Check if the expression has the character type and issue a warning then.
4905 static void check_for_char_index_type(const expression_t *expression) {
4906 type_t *const type = expression->base.type;
4907 const type_t *const base_type = skip_typeref(type);
4909 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4910 warning.char_subscripts) {
4911 warningf(expression->base.source_position,
4912 "array subscript has type '%T'", type);
4916 static expression_t *parse_array_expression(unsigned precedence,
4922 add_anchor_token(']');
4924 expression_t *inside = parse_expression();
4926 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4928 array_access_expression_t *array_access = &expression->array_access;
4930 type_t *const orig_type_left = left->base.type;
4931 type_t *const orig_type_inside = inside->base.type;
4933 type_t *const type_left = skip_typeref(orig_type_left);
4934 type_t *const type_inside = skip_typeref(orig_type_inside);
4936 type_t *return_type;
4937 if (is_type_pointer(type_left)) {
4938 return_type = type_left->pointer.points_to;
4939 array_access->array_ref = left;
4940 array_access->index = inside;
4941 check_for_char_index_type(inside);
4942 } else if (is_type_pointer(type_inside)) {
4943 return_type = type_inside->pointer.points_to;
4944 array_access->array_ref = inside;
4945 array_access->index = left;
4946 array_access->flipped = true;
4947 check_for_char_index_type(left);
4949 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4951 "array access on object with non-pointer types '%T', '%T'",
4952 orig_type_left, orig_type_inside);
4954 return_type = type_error_type;
4955 array_access->array_ref = create_invalid_expression();
4958 rem_anchor_token(']');
4959 if(token.type != ']') {
4960 parse_error_expected("Problem while parsing array access", ']', 0);
4965 return_type = automatic_type_conversion(return_type);
4966 expression->base.type = return_type;
4971 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4973 expression_t *tp_expression = allocate_expression_zero(kind);
4974 tp_expression->base.type = type_size_t;
4976 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4978 add_anchor_token(')');
4979 tp_expression->typeprop.type = parse_typename();
4980 rem_anchor_token(')');
4983 expression_t *expression = parse_sub_expression(precedence);
4984 expression->base.type = revert_automatic_type_conversion(expression);
4986 tp_expression->typeprop.type = expression->base.type;
4987 tp_expression->typeprop.tp_expression = expression;
4990 return tp_expression;
4992 return create_invalid_expression();
4995 static expression_t *parse_sizeof(unsigned precedence)
4998 return parse_typeprop(EXPR_SIZEOF, precedence);
5001 static expression_t *parse_alignof(unsigned precedence)
5004 return parse_typeprop(EXPR_SIZEOF, precedence);
5007 static expression_t *parse_select_expression(unsigned precedence,
5008 expression_t *compound)
5011 assert(token.type == '.' || token.type == T_MINUSGREATER);
5013 bool is_pointer = (token.type == T_MINUSGREATER);
5016 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5017 select->select.compound = compound;
5019 if(token.type != T_IDENTIFIER) {
5020 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
5023 symbol_t *symbol = token.v.symbol;
5024 select->select.symbol = symbol;
5027 type_t *const orig_type = compound->base.type;
5028 type_t *const type = skip_typeref(orig_type);
5030 type_t *type_left = type;
5032 if (!is_type_pointer(type)) {
5033 if (is_type_valid(type)) {
5034 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5036 return create_invalid_expression();
5038 type_left = type->pointer.points_to;
5040 type_left = skip_typeref(type_left);
5042 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5043 type_left->kind != TYPE_COMPOUND_UNION) {
5044 if (is_type_valid(type_left)) {
5045 errorf(HERE, "request for member '%Y' in something not a struct or "
5046 "union, but '%T'", symbol, type_left);
5048 return create_invalid_expression();
5051 declaration_t *const declaration = type_left->compound.declaration;
5053 if(!declaration->init.is_defined) {
5054 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
5056 return create_invalid_expression();
5059 declaration_t *iter = find_compound_entry(declaration, symbol);
5061 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
5062 return create_invalid_expression();
5065 /* we always do the auto-type conversions; the & and sizeof parser contains
5066 * code to revert this! */
5067 type_t *expression_type = automatic_type_conversion(iter->type);
5069 select->select.compound_entry = iter;
5070 select->base.type = expression_type;
5072 if(expression_type->kind == TYPE_BITFIELD) {
5073 expression_t *extract
5074 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5075 extract->unary.value = select;
5076 extract->base.type = expression_type->bitfield.base;
5085 * Parse a call expression, ie. expression '( ... )'.
5087 * @param expression the function address
5089 static expression_t *parse_call_expression(unsigned precedence,
5090 expression_t *expression)
5093 expression_t *result = allocate_expression_zero(EXPR_CALL);
5094 result->base.source_position = expression->base.source_position;
5096 call_expression_t *call = &result->call;
5097 call->function = expression;
5099 type_t *const orig_type = expression->base.type;
5100 type_t *const type = skip_typeref(orig_type);
5102 function_type_t *function_type = NULL;
5103 if (is_type_pointer(type)) {
5104 type_t *const to_type = skip_typeref(type->pointer.points_to);
5106 if (is_type_function(to_type)) {
5107 function_type = &to_type->function;
5108 call->base.type = function_type->return_type;
5112 if (function_type == NULL && is_type_valid(type)) {
5113 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5116 /* parse arguments */
5118 add_anchor_token(')');
5119 add_anchor_token(',');
5121 if(token.type != ')') {
5122 call_argument_t *last_argument = NULL;
5125 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5127 argument->expression = parse_assignment_expression();
5128 if(last_argument == NULL) {
5129 call->arguments = argument;
5131 last_argument->next = argument;
5133 last_argument = argument;
5135 if(token.type != ',')
5140 rem_anchor_token(',');
5141 rem_anchor_token(')');
5144 if(function_type != NULL) {
5145 function_parameter_t *parameter = function_type->parameters;
5146 call_argument_t *argument = call->arguments;
5147 for( ; parameter != NULL && argument != NULL;
5148 parameter = parameter->next, argument = argument->next) {
5149 type_t *expected_type = parameter->type;
5150 /* TODO report scope in error messages */
5151 expression_t *const arg_expr = argument->expression;
5152 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
5153 if (res_type == NULL) {
5154 /* TODO improve error message */
5155 errorf(arg_expr->base.source_position,
5156 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5157 arg_expr, arg_expr->base.type, expected_type);
5159 argument->expression = create_implicit_cast(argument->expression, expected_type);
5162 /* too few parameters */
5163 if(parameter != NULL) {
5164 errorf(HERE, "too few arguments to function '%E'", expression);
5165 } else if(argument != NULL) {
5166 /* too many parameters */
5167 if(!function_type->variadic
5168 && !function_type->unspecified_parameters) {
5169 errorf(HERE, "too many arguments to function '%E'", expression);
5171 /* do default promotion */
5172 for( ; argument != NULL; argument = argument->next) {
5173 type_t *type = argument->expression->base.type;
5175 type = skip_typeref(type);
5176 if(is_type_integer(type)) {
5177 type = promote_integer(type);
5178 } else if(type == type_float) {
5182 argument->expression
5183 = create_implicit_cast(argument->expression, type);
5186 check_format(&result->call);
5189 check_format(&result->call);
5195 return create_invalid_expression();
5198 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5200 static bool same_compound_type(const type_t *type1, const type_t *type2)
5203 is_type_compound(type1) &&
5204 type1->kind == type2->kind &&
5205 type1->compound.declaration == type2->compound.declaration;
5209 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5211 * @param expression the conditional expression
5213 static expression_t *parse_conditional_expression(unsigned precedence,
5214 expression_t *expression)
5217 add_anchor_token(':');
5219 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5221 conditional_expression_t *conditional = &result->conditional;
5222 conditional->condition = expression;
5225 type_t *const condition_type_orig = expression->base.type;
5226 type_t *const condition_type = skip_typeref(condition_type_orig);
5227 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5228 type_error("expected a scalar type in conditional condition",
5229 expression->base.source_position, condition_type_orig);
5232 expression_t *true_expression = parse_expression();
5233 rem_anchor_token(':');
5235 expression_t *false_expression = parse_sub_expression(precedence);
5237 type_t *const orig_true_type = true_expression->base.type;
5238 type_t *const orig_false_type = false_expression->base.type;
5239 type_t *const true_type = skip_typeref(orig_true_type);
5240 type_t *const false_type = skip_typeref(orig_false_type);
5243 type_t *result_type;
5244 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
5245 result_type = semantic_arithmetic(true_type, false_type);
5247 true_expression = create_implicit_cast(true_expression, result_type);
5248 false_expression = create_implicit_cast(false_expression, result_type);
5250 conditional->true_expression = true_expression;
5251 conditional->false_expression = false_expression;
5252 conditional->base.type = result_type;
5253 } else if (same_compound_type(true_type, false_type) || (
5254 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
5255 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
5257 /* just take 1 of the 2 types */
5258 result_type = true_type;
5259 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
5260 && pointers_compatible(true_type, false_type)) {
5262 result_type = true_type;
5263 } else if (is_type_pointer(true_type)
5264 && is_null_pointer_constant(false_expression)) {
5265 result_type = true_type;
5266 } else if (is_type_pointer(false_type)
5267 && is_null_pointer_constant(true_expression)) {
5268 result_type = false_type;
5270 /* TODO: one pointer to void*, other some pointer */
5272 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5273 type_error_incompatible("while parsing conditional",
5274 expression->base.source_position, true_type,
5277 result_type = type_error_type;
5280 conditional->true_expression
5281 = create_implicit_cast(true_expression, result_type);
5282 conditional->false_expression
5283 = create_implicit_cast(false_expression, result_type);
5284 conditional->base.type = result_type;
5287 return create_invalid_expression();
5291 * Parse an extension expression.
5293 static expression_t *parse_extension(unsigned precedence)
5295 eat(T___extension__);
5297 /* TODO enable extensions */
5298 expression_t *expression = parse_sub_expression(precedence);
5299 /* TODO disable extensions */
5304 * Parse a __builtin_classify_type() expression.
5306 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5308 eat(T___builtin_classify_type);
5310 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5311 result->base.type = type_int;
5314 add_anchor_token(')');
5315 expression_t *expression = parse_sub_expression(precedence);
5316 rem_anchor_token(')');
5318 result->classify_type.type_expression = expression;
5322 return create_invalid_expression();
5325 static void semantic_incdec(unary_expression_t *expression)
5327 type_t *const orig_type = expression->value->base.type;
5328 type_t *const type = skip_typeref(orig_type);
5329 /* TODO !is_type_real && !is_type_pointer */
5330 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5331 if (is_type_valid(type)) {
5332 /* TODO: improve error message */
5333 errorf(HERE, "operation needs an arithmetic or pointer type");
5338 expression->base.type = orig_type;
5341 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5343 type_t *const orig_type = expression->value->base.type;
5344 type_t *const type = skip_typeref(orig_type);
5345 if(!is_type_arithmetic(type)) {
5346 if (is_type_valid(type)) {
5347 /* TODO: improve error message */
5348 errorf(HERE, "operation needs an arithmetic type");
5353 expression->base.type = orig_type;
5356 static void semantic_unexpr_scalar(unary_expression_t *expression)
5358 type_t *const orig_type = expression->value->base.type;
5359 type_t *const type = skip_typeref(orig_type);
5360 if (!is_type_scalar(type)) {
5361 if (is_type_valid(type)) {
5362 errorf(HERE, "operand of ! must be of scalar type");
5367 expression->base.type = orig_type;
5370 static void semantic_unexpr_integer(unary_expression_t *expression)
5372 type_t *const orig_type = expression->value->base.type;
5373 type_t *const type = skip_typeref(orig_type);
5374 if (!is_type_integer(type)) {
5375 if (is_type_valid(type)) {
5376 errorf(HERE, "operand of ~ must be of integer type");
5381 expression->base.type = orig_type;
5384 static void semantic_dereference(unary_expression_t *expression)
5386 type_t *const orig_type = expression->value->base.type;
5387 type_t *const type = skip_typeref(orig_type);
5388 if(!is_type_pointer(type)) {
5389 if (is_type_valid(type)) {
5390 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5395 type_t *result_type = type->pointer.points_to;
5396 result_type = automatic_type_conversion(result_type);
5397 expression->base.type = result_type;
5401 * Check the semantic of the address taken expression.
5403 static void semantic_take_addr(unary_expression_t *expression)
5405 expression_t *value = expression->value;
5406 value->base.type = revert_automatic_type_conversion(value);
5408 type_t *orig_type = value->base.type;
5409 if(!is_type_valid(orig_type))
5412 if(value->kind == EXPR_REFERENCE) {
5413 declaration_t *const declaration = value->reference.declaration;
5414 if(declaration != NULL) {
5415 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5416 errorf(expression->base.source_position,
5417 "address of register variable '%Y' requested",
5418 declaration->symbol);
5420 declaration->address_taken = 1;
5424 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5427 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5428 static expression_t *parse_##unexpression_type(unsigned precedence) \
5432 expression_t *unary_expression \
5433 = allocate_expression_zero(unexpression_type); \
5434 unary_expression->base.source_position = HERE; \
5435 unary_expression->unary.value = parse_sub_expression(precedence); \
5437 sfunc(&unary_expression->unary); \
5439 return unary_expression; \
5442 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5443 semantic_unexpr_arithmetic)
5444 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5445 semantic_unexpr_arithmetic)
5446 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5447 semantic_unexpr_scalar)
5448 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5449 semantic_dereference)
5450 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5452 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5453 semantic_unexpr_integer)
5454 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5456 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5459 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5461 static expression_t *parse_##unexpression_type(unsigned precedence, \
5462 expression_t *left) \
5464 (void) precedence; \
5467 expression_t *unary_expression \
5468 = allocate_expression_zero(unexpression_type); \
5469 unary_expression->unary.value = left; \
5471 sfunc(&unary_expression->unary); \
5473 return unary_expression; \
5476 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5477 EXPR_UNARY_POSTFIX_INCREMENT,
5479 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5480 EXPR_UNARY_POSTFIX_DECREMENT,
5483 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5485 /* TODO: handle complex + imaginary types */
5487 /* § 6.3.1.8 Usual arithmetic conversions */
5488 if(type_left == type_long_double || type_right == type_long_double) {
5489 return type_long_double;
5490 } else if(type_left == type_double || type_right == type_double) {
5492 } else if(type_left == type_float || type_right == type_float) {
5496 type_right = promote_integer(type_right);
5497 type_left = promote_integer(type_left);
5499 if(type_left == type_right)
5502 bool signed_left = is_type_signed(type_left);
5503 bool signed_right = is_type_signed(type_right);
5504 int rank_left = get_rank(type_left);
5505 int rank_right = get_rank(type_right);
5506 if(rank_left < rank_right) {
5507 if(signed_left == signed_right || !signed_right) {
5513 if(signed_left == signed_right || !signed_left) {
5522 * Check the semantic restrictions for a binary expression.
5524 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5526 expression_t *const left = expression->left;
5527 expression_t *const right = expression->right;
5528 type_t *const orig_type_left = left->base.type;
5529 type_t *const orig_type_right = right->base.type;
5530 type_t *const type_left = skip_typeref(orig_type_left);
5531 type_t *const type_right = skip_typeref(orig_type_right);
5533 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5534 /* TODO: improve error message */
5535 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5536 errorf(HERE, "operation needs arithmetic types");
5541 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5542 expression->left = create_implicit_cast(left, arithmetic_type);
5543 expression->right = create_implicit_cast(right, arithmetic_type);
5544 expression->base.type = arithmetic_type;
5547 static void semantic_shift_op(binary_expression_t *expression)
5549 expression_t *const left = expression->left;
5550 expression_t *const right = expression->right;
5551 type_t *const orig_type_left = left->base.type;
5552 type_t *const orig_type_right = right->base.type;
5553 type_t * type_left = skip_typeref(orig_type_left);
5554 type_t * type_right = skip_typeref(orig_type_right);
5556 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5557 /* TODO: improve error message */
5558 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5559 errorf(HERE, "operation needs integer types");
5564 type_left = promote_integer(type_left);
5565 type_right = promote_integer(type_right);
5567 expression->left = create_implicit_cast(left, type_left);
5568 expression->right = create_implicit_cast(right, type_right);
5569 expression->base.type = type_left;
5572 static void semantic_add(binary_expression_t *expression)
5574 expression_t *const left = expression->left;
5575 expression_t *const right = expression->right;
5576 type_t *const orig_type_left = left->base.type;
5577 type_t *const orig_type_right = right->base.type;
5578 type_t *const type_left = skip_typeref(orig_type_left);
5579 type_t *const type_right = skip_typeref(orig_type_right);
5582 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5583 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5584 expression->left = create_implicit_cast(left, arithmetic_type);
5585 expression->right = create_implicit_cast(right, arithmetic_type);
5586 expression->base.type = arithmetic_type;
5588 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5589 expression->base.type = type_left;
5590 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5591 expression->base.type = type_right;
5592 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5593 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5597 static void semantic_sub(binary_expression_t *expression)
5599 expression_t *const left = expression->left;
5600 expression_t *const right = expression->right;
5601 type_t *const orig_type_left = left->base.type;
5602 type_t *const orig_type_right = right->base.type;
5603 type_t *const type_left = skip_typeref(orig_type_left);
5604 type_t *const type_right = skip_typeref(orig_type_right);
5607 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5608 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5609 expression->left = create_implicit_cast(left, arithmetic_type);
5610 expression->right = create_implicit_cast(right, arithmetic_type);
5611 expression->base.type = arithmetic_type;
5613 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5614 expression->base.type = type_left;
5615 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5616 if(!pointers_compatible(type_left, type_right)) {
5618 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5619 orig_type_left, orig_type_right);
5621 expression->base.type = type_ptrdiff_t;
5623 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5624 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5625 orig_type_left, orig_type_right);
5630 * Check the semantics of comparison expressions.
5632 * @param expression The expression to check.
5634 static void semantic_comparison(binary_expression_t *expression)
5636 expression_t *left = expression->left;
5637 expression_t *right = expression->right;
5638 type_t *orig_type_left = left->base.type;
5639 type_t *orig_type_right = right->base.type;
5641 type_t *type_left = skip_typeref(orig_type_left);
5642 type_t *type_right = skip_typeref(orig_type_right);
5644 /* TODO non-arithmetic types */
5645 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5646 if (warning.sign_compare &&
5647 (expression->base.kind != EXPR_BINARY_EQUAL &&
5648 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5649 (is_type_signed(type_left) != is_type_signed(type_right))) {
5650 warningf(expression->base.source_position,
5651 "comparison between signed and unsigned");
5653 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5654 expression->left = create_implicit_cast(left, arithmetic_type);
5655 expression->right = create_implicit_cast(right, arithmetic_type);
5656 expression->base.type = arithmetic_type;
5657 if (warning.float_equal &&
5658 (expression->base.kind == EXPR_BINARY_EQUAL ||
5659 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5660 is_type_float(arithmetic_type)) {
5661 warningf(expression->base.source_position,
5662 "comparing floating point with == or != is unsafe");
5664 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5665 /* TODO check compatibility */
5666 } else if (is_type_pointer(type_left)) {
5667 expression->right = create_implicit_cast(right, type_left);
5668 } else if (is_type_pointer(type_right)) {
5669 expression->left = create_implicit_cast(left, type_right);
5670 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5671 type_error_incompatible("invalid operands in comparison",
5672 expression->base.source_position,
5673 type_left, type_right);
5675 expression->base.type = type_int;
5678 static void semantic_arithmetic_assign(binary_expression_t *expression)
5680 expression_t *left = expression->left;
5681 expression_t *right = expression->right;
5682 type_t *orig_type_left = left->base.type;
5683 type_t *orig_type_right = right->base.type;
5685 type_t *type_left = skip_typeref(orig_type_left);
5686 type_t *type_right = skip_typeref(orig_type_right);
5688 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5689 /* TODO: improve error message */
5690 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5691 errorf(HERE, "operation needs arithmetic types");
5696 /* combined instructions are tricky. We can't create an implicit cast on
5697 * the left side, because we need the uncasted form for the store.
5698 * The ast2firm pass has to know that left_type must be right_type
5699 * for the arithmetic operation and create a cast by itself */
5700 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5701 expression->right = create_implicit_cast(right, arithmetic_type);
5702 expression->base.type = type_left;
5705 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5707 expression_t *const left = expression->left;
5708 expression_t *const right = expression->right;
5709 type_t *const orig_type_left = left->base.type;
5710 type_t *const orig_type_right = right->base.type;
5711 type_t *const type_left = skip_typeref(orig_type_left);
5712 type_t *const type_right = skip_typeref(orig_type_right);
5714 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5715 /* combined instructions are tricky. We can't create an implicit cast on
5716 * the left side, because we need the uncasted form for the store.
5717 * The ast2firm pass has to know that left_type must be right_type
5718 * for the arithmetic operation and create a cast by itself */
5719 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5720 expression->right = create_implicit_cast(right, arithmetic_type);
5721 expression->base.type = type_left;
5722 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5723 expression->base.type = type_left;
5724 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5725 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5730 * Check the semantic restrictions of a logical expression.
5732 static void semantic_logical_op(binary_expression_t *expression)
5734 expression_t *const left = expression->left;
5735 expression_t *const right = expression->right;
5736 type_t *const orig_type_left = left->base.type;
5737 type_t *const orig_type_right = right->base.type;
5738 type_t *const type_left = skip_typeref(orig_type_left);
5739 type_t *const type_right = skip_typeref(orig_type_right);
5741 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5742 /* TODO: improve error message */
5743 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5744 errorf(HERE, "operation needs scalar types");
5749 expression->base.type = type_int;
5753 * Checks if a compound type has constant fields.
5755 static bool has_const_fields(const compound_type_t *type)
5757 const scope_t *scope = &type->declaration->scope;
5758 const declaration_t *declaration = scope->declarations;
5760 for (; declaration != NULL; declaration = declaration->next) {
5761 if (declaration->namespc != NAMESPACE_NORMAL)
5764 const type_t *decl_type = skip_typeref(declaration->type);
5765 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5773 * Check the semantic restrictions of a binary assign expression.
5775 static void semantic_binexpr_assign(binary_expression_t *expression)
5777 expression_t *left = expression->left;
5778 type_t *orig_type_left = left->base.type;
5780 type_t *type_left = revert_automatic_type_conversion(left);
5781 type_left = skip_typeref(orig_type_left);
5783 /* must be a modifiable lvalue */
5784 if (is_type_array(type_left)) {
5785 errorf(HERE, "cannot assign to arrays ('%E')", left);
5788 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5789 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5793 if(is_type_incomplete(type_left)) {
5795 "left-hand side of assignment '%E' has incomplete type '%T'",
5796 left, orig_type_left);
5799 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5800 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5801 left, orig_type_left);
5805 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5807 if (res_type == NULL) {
5808 errorf(expression->base.source_position,
5809 "cannot assign to '%T' from '%T'",
5810 orig_type_left, expression->right->base.type);
5812 expression->right = create_implicit_cast(expression->right, res_type);
5815 expression->base.type = orig_type_left;
5819 * Determine if the outermost operation (or parts thereof) of the given
5820 * expression has no effect in order to generate a warning about this fact.
5821 * Therefore in some cases this only examines some of the operands of the
5822 * expression (see comments in the function and examples below).
5824 * f() + 23; // warning, because + has no effect
5825 * x || f(); // no warning, because x controls execution of f()
5826 * x ? y : f(); // warning, because y has no effect
5827 * (void)x; // no warning to be able to suppress the warning
5828 * This function can NOT be used for an "expression has definitely no effect"-
5830 static bool expression_has_effect(const expression_t *const expr)
5832 switch (expr->kind) {
5833 case EXPR_UNKNOWN: break;
5834 case EXPR_INVALID: return true; /* do NOT warn */
5835 case EXPR_REFERENCE: return false;
5836 /* suppress the warning for microsoft __noop operations */
5837 case EXPR_CONST: return expr->conste.is_ms_noop;
5838 case EXPR_CHARACTER_CONSTANT: return false;
5839 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5840 case EXPR_STRING_LITERAL: return false;
5841 case EXPR_WIDE_STRING_LITERAL: return false;
5844 const call_expression_t *const call = &expr->call;
5845 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5848 switch (call->function->builtin_symbol.symbol->ID) {
5849 case T___builtin_va_end: return true;
5850 default: return false;
5854 /* Generate the warning if either the left or right hand side of a
5855 * conditional expression has no effect */
5856 case EXPR_CONDITIONAL: {
5857 const conditional_expression_t *const cond = &expr->conditional;
5859 expression_has_effect(cond->true_expression) &&
5860 expression_has_effect(cond->false_expression);
5863 case EXPR_SELECT: return false;
5864 case EXPR_ARRAY_ACCESS: return false;
5865 case EXPR_SIZEOF: return false;
5866 case EXPR_CLASSIFY_TYPE: return false;
5867 case EXPR_ALIGNOF: return false;
5869 case EXPR_FUNCNAME: return false;
5870 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5871 case EXPR_BUILTIN_CONSTANT_P: return false;
5872 case EXPR_BUILTIN_PREFETCH: return true;
5873 case EXPR_OFFSETOF: return false;
5874 case EXPR_VA_START: return true;
5875 case EXPR_VA_ARG: return true;
5876 case EXPR_STATEMENT: return true; // TODO
5877 case EXPR_COMPOUND_LITERAL: return false;
5879 case EXPR_UNARY_NEGATE: return false;
5880 case EXPR_UNARY_PLUS: return false;
5881 case EXPR_UNARY_BITWISE_NEGATE: return false;
5882 case EXPR_UNARY_NOT: return false;
5883 case EXPR_UNARY_DEREFERENCE: return false;
5884 case EXPR_UNARY_TAKE_ADDRESS: return false;
5885 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5886 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5887 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5888 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5890 /* Treat void casts as if they have an effect in order to being able to
5891 * suppress the warning */
5892 case EXPR_UNARY_CAST: {
5893 type_t *const type = skip_typeref(expr->base.type);
5894 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5897 case EXPR_UNARY_CAST_IMPLICIT: return true;
5898 case EXPR_UNARY_ASSUME: return true;
5899 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5901 case EXPR_BINARY_ADD: return false;
5902 case EXPR_BINARY_SUB: return false;
5903 case EXPR_BINARY_MUL: return false;
5904 case EXPR_BINARY_DIV: return false;
5905 case EXPR_BINARY_MOD: return false;
5906 case EXPR_BINARY_EQUAL: return false;
5907 case EXPR_BINARY_NOTEQUAL: return false;
5908 case EXPR_BINARY_LESS: return false;
5909 case EXPR_BINARY_LESSEQUAL: return false;
5910 case EXPR_BINARY_GREATER: return false;
5911 case EXPR_BINARY_GREATEREQUAL: return false;
5912 case EXPR_BINARY_BITWISE_AND: return false;
5913 case EXPR_BINARY_BITWISE_OR: return false;
5914 case EXPR_BINARY_BITWISE_XOR: return false;
5915 case EXPR_BINARY_SHIFTLEFT: return false;
5916 case EXPR_BINARY_SHIFTRIGHT: return false;
5917 case EXPR_BINARY_ASSIGN: return true;
5918 case EXPR_BINARY_MUL_ASSIGN: return true;
5919 case EXPR_BINARY_DIV_ASSIGN: return true;
5920 case EXPR_BINARY_MOD_ASSIGN: return true;
5921 case EXPR_BINARY_ADD_ASSIGN: return true;
5922 case EXPR_BINARY_SUB_ASSIGN: return true;
5923 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5924 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5925 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5926 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5927 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5929 /* Only examine the right hand side of && and ||, because the left hand
5930 * side already has the effect of controlling the execution of the right
5932 case EXPR_BINARY_LOGICAL_AND:
5933 case EXPR_BINARY_LOGICAL_OR:
5934 /* Only examine the right hand side of a comma expression, because the left
5935 * hand side has a separate warning */
5936 case EXPR_BINARY_COMMA:
5937 return expression_has_effect(expr->binary.right);
5939 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5940 case EXPR_BINARY_ISGREATER: return false;
5941 case EXPR_BINARY_ISGREATEREQUAL: return false;
5942 case EXPR_BINARY_ISLESS: return false;
5943 case EXPR_BINARY_ISLESSEQUAL: return false;
5944 case EXPR_BINARY_ISLESSGREATER: return false;
5945 case EXPR_BINARY_ISUNORDERED: return false;
5948 internal_errorf(HERE, "unexpected expression");
5951 static void semantic_comma(binary_expression_t *expression)
5953 if (warning.unused_value) {
5954 const expression_t *const left = expression->left;
5955 if (!expression_has_effect(left)) {
5956 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5959 expression->base.type = expression->right->base.type;
5962 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5963 static expression_t *parse_##binexpression_type(unsigned precedence, \
5964 expression_t *left) \
5967 source_position_t pos = HERE; \
5969 expression_t *right = parse_sub_expression(precedence + lr); \
5971 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5972 binexpr->base.source_position = pos; \
5973 binexpr->binary.left = left; \
5974 binexpr->binary.right = right; \
5975 sfunc(&binexpr->binary); \
5980 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5981 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5982 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5983 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5984 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5985 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5986 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5987 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5988 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5990 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5991 semantic_comparison, 1)
5992 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5993 semantic_comparison, 1)
5994 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5995 semantic_comparison, 1)
5996 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5997 semantic_comparison, 1)
5999 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
6000 semantic_binexpr_arithmetic, 1)
6001 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
6002 semantic_binexpr_arithmetic, 1)
6003 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
6004 semantic_binexpr_arithmetic, 1)
6005 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
6006 semantic_logical_op, 1)
6007 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
6008 semantic_logical_op, 1)
6009 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
6010 semantic_shift_op, 1)
6011 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
6012 semantic_shift_op, 1)
6013 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
6014 semantic_arithmetic_addsubb_assign, 0)
6015 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
6016 semantic_arithmetic_addsubb_assign, 0)
6017 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
6018 semantic_arithmetic_assign, 0)
6019 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
6020 semantic_arithmetic_assign, 0)
6021 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
6022 semantic_arithmetic_assign, 0)
6023 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
6024 semantic_arithmetic_assign, 0)
6025 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6026 semantic_arithmetic_assign, 0)
6027 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
6028 semantic_arithmetic_assign, 0)
6029 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
6030 semantic_arithmetic_assign, 0)
6031 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
6032 semantic_arithmetic_assign, 0)
6034 static expression_t *parse_sub_expression(unsigned precedence)
6036 if(token.type < 0) {
6037 return expected_expression_error();
6040 expression_parser_function_t *parser
6041 = &expression_parsers[token.type];
6042 source_position_t source_position = token.source_position;
6045 if(parser->parser != NULL) {
6046 left = parser->parser(parser->precedence);
6048 left = parse_primary_expression();
6050 assert(left != NULL);
6051 left->base.source_position = source_position;
6054 if(token.type < 0) {
6055 return expected_expression_error();
6058 parser = &expression_parsers[token.type];
6059 if(parser->infix_parser == NULL)
6061 if(parser->infix_precedence < precedence)
6064 left = parser->infix_parser(parser->infix_precedence, left);
6066 assert(left != NULL);
6067 assert(left->kind != EXPR_UNKNOWN);
6068 left->base.source_position = source_position;
6075 * Parse an expression.
6077 static expression_t *parse_expression(void)
6079 return parse_sub_expression(1);
6083 * Register a parser for a prefix-like operator with given precedence.
6085 * @param parser the parser function
6086 * @param token_type the token type of the prefix token
6087 * @param precedence the precedence of the operator
6089 static void register_expression_parser(parse_expression_function parser,
6090 int token_type, unsigned precedence)
6092 expression_parser_function_t *entry = &expression_parsers[token_type];
6094 if(entry->parser != NULL) {
6095 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6096 panic("trying to register multiple expression parsers for a token");
6098 entry->parser = parser;
6099 entry->precedence = precedence;
6103 * Register a parser for an infix operator with given precedence.
6105 * @param parser the parser function
6106 * @param token_type the token type of the infix operator
6107 * @param precedence the precedence of the operator
6109 static void register_infix_parser(parse_expression_infix_function parser,
6110 int token_type, unsigned precedence)
6112 expression_parser_function_t *entry = &expression_parsers[token_type];
6114 if(entry->infix_parser != NULL) {
6115 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6116 panic("trying to register multiple infix expression parsers for a "
6119 entry->infix_parser = parser;
6120 entry->infix_precedence = precedence;
6124 * Initialize the expression parsers.
6126 static void init_expression_parsers(void)
6128 memset(&expression_parsers, 0, sizeof(expression_parsers));
6130 register_infix_parser(parse_array_expression, '[', 30);
6131 register_infix_parser(parse_call_expression, '(', 30);
6132 register_infix_parser(parse_select_expression, '.', 30);
6133 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6134 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6136 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6139 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6140 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6141 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6142 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6143 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6144 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6145 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6146 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6147 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6148 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6149 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6150 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6151 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6152 T_EXCLAMATIONMARKEQUAL, 13);
6153 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6154 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6155 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6156 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6157 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6158 register_infix_parser(parse_conditional_expression, '?', 7);
6159 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6160 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6161 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6162 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6163 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6164 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6165 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6166 T_LESSLESSEQUAL, 2);
6167 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6168 T_GREATERGREATEREQUAL, 2);
6169 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6171 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6173 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6176 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6178 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6179 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6180 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6181 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6182 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6183 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6184 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6186 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6188 register_expression_parser(parse_sizeof, T_sizeof, 25);
6189 register_expression_parser(parse_alignof, T___alignof__, 25);
6190 register_expression_parser(parse_extension, T___extension__, 25);
6191 register_expression_parser(parse_builtin_classify_type,
6192 T___builtin_classify_type, 25);
6196 * Parse a asm statement constraints specification.
6198 static asm_constraint_t *parse_asm_constraints(void)
6200 asm_constraint_t *result = NULL;
6201 asm_constraint_t *last = NULL;
6203 while(token.type == T_STRING_LITERAL || token.type == '[') {
6204 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6205 memset(constraint, 0, sizeof(constraint[0]));
6207 if(token.type == '[') {
6209 if(token.type != T_IDENTIFIER) {
6210 parse_error_expected("while parsing asm constraint",
6214 constraint->symbol = token.v.symbol;
6219 constraint->constraints = parse_string_literals();
6221 constraint->expression = parse_expression();
6225 last->next = constraint;
6227 result = constraint;
6231 if(token.type != ',')
6242 * Parse a asm statement clobber specification.
6244 static asm_clobber_t *parse_asm_clobbers(void)
6246 asm_clobber_t *result = NULL;
6247 asm_clobber_t *last = NULL;
6249 while(token.type == T_STRING_LITERAL) {
6250 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6251 clobber->clobber = parse_string_literals();
6254 last->next = clobber;
6260 if(token.type != ',')
6269 * Parse an asm statement.
6271 static statement_t *parse_asm_statement(void)
6275 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6276 statement->base.source_position = token.source_position;
6278 asm_statement_t *asm_statement = &statement->asms;
6280 if(token.type == T_volatile) {
6282 asm_statement->is_volatile = true;
6286 add_anchor_token(')');
6287 add_anchor_token(':');
6288 asm_statement->asm_text = parse_string_literals();
6290 if(token.type != ':') {
6291 rem_anchor_token(':');
6296 asm_statement->inputs = parse_asm_constraints();
6297 if(token.type != ':') {
6298 rem_anchor_token(':');
6303 asm_statement->outputs = parse_asm_constraints();
6304 if(token.type != ':') {
6305 rem_anchor_token(':');
6308 rem_anchor_token(':');
6311 asm_statement->clobbers = parse_asm_clobbers();
6314 rem_anchor_token(')');
6319 return create_invalid_statement();
6323 * Parse a case statement.
6325 static statement_t *parse_case_statement(void)
6329 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6331 statement->base.source_position = token.source_position;
6332 statement->case_label.expression = parse_expression();
6334 if (c_mode & _GNUC) {
6335 if (token.type == T_DOTDOTDOT) {
6337 statement->case_label.end_range = parse_expression();
6343 if (! is_constant_expression(statement->case_label.expression)) {
6344 errorf(statement->base.source_position,
6345 "case label does not reduce to an integer constant");
6347 /* TODO: check if the case label is already known */
6348 if (current_switch != NULL) {
6349 /* link all cases into the switch statement */
6350 if (current_switch->last_case == NULL) {
6351 current_switch->first_case =
6352 current_switch->last_case = &statement->case_label;
6354 current_switch->last_case->next = &statement->case_label;
6357 errorf(statement->base.source_position,
6358 "case label not within a switch statement");
6361 statement->case_label.statement = parse_statement();
6365 return create_invalid_statement();
6369 * Finds an existing default label of a switch statement.
6371 static case_label_statement_t *
6372 find_default_label(const switch_statement_t *statement)
6374 case_label_statement_t *label = statement->first_case;
6375 for ( ; label != NULL; label = label->next) {
6376 if (label->expression == NULL)
6383 * Parse a default statement.
6385 static statement_t *parse_default_statement(void)
6389 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6391 statement->base.source_position = token.source_position;
6394 if (current_switch != NULL) {
6395 const case_label_statement_t *def_label = find_default_label(current_switch);
6396 if (def_label != NULL) {
6397 errorf(HERE, "multiple default labels in one switch");
6398 errorf(def_label->base.source_position,
6399 "this is the first default label");
6401 /* link all cases into the switch statement */
6402 if (current_switch->last_case == NULL) {
6403 current_switch->first_case =
6404 current_switch->last_case = &statement->case_label;
6406 current_switch->last_case->next = &statement->case_label;
6410 errorf(statement->base.source_position,
6411 "'default' label not within a switch statement");
6413 statement->case_label.statement = parse_statement();
6417 return create_invalid_statement();
6421 * Return the declaration for a given label symbol or create a new one.
6423 static declaration_t *get_label(symbol_t *symbol)
6425 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6426 assert(current_function != NULL);
6427 /* if we found a label in the same function, then we already created the
6429 if(candidate != NULL
6430 && candidate->parent_scope == ¤t_function->scope) {
6434 /* otherwise we need to create a new one */
6435 declaration_t *const declaration = allocate_declaration_zero();
6436 declaration->namespc = NAMESPACE_LABEL;
6437 declaration->symbol = symbol;
6439 label_push(declaration);
6445 * Parse a label statement.
6447 static statement_t *parse_label_statement(void)
6449 assert(token.type == T_IDENTIFIER);
6450 symbol_t *symbol = token.v.symbol;
6453 declaration_t *label = get_label(symbol);
6455 /* if source position is already set then the label is defined twice,
6456 * otherwise it was just mentioned in a goto so far */
6457 if(label->source_position.input_name != NULL) {
6458 errorf(HERE, "duplicate label '%Y'", symbol);
6459 errorf(label->source_position, "previous definition of '%Y' was here",
6462 label->source_position = token.source_position;
6465 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6467 statement->base.source_position = token.source_position;
6468 statement->label.label = label;
6472 if(token.type == '}') {
6473 /* TODO only warn? */
6475 warningf(HERE, "label at end of compound statement");
6476 statement->label.statement = create_empty_statement();
6478 errorf(HERE, "label at end of compound statement");
6479 statement->label.statement = create_invalid_statement();
6483 if (token.type == ';') {
6484 /* eat an empty statement here, to avoid the warning about an empty
6485 * after a label. label:; is commonly used to have a label before
6487 statement->label.statement = create_empty_statement();
6490 statement->label.statement = parse_statement();
6494 /* remember the labels's in a list for later checking */
6495 if (label_last == NULL) {
6496 label_first = &statement->label;
6498 label_last->next = &statement->label;
6500 label_last = &statement->label;
6506 * Parse an if statement.
6508 static statement_t *parse_if(void)
6512 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6513 statement->base.source_position = token.source_position;
6516 add_anchor_token(')');
6517 statement->ifs.condition = parse_expression();
6518 rem_anchor_token(')');
6521 add_anchor_token(T_else);
6522 statement->ifs.true_statement = parse_statement();
6523 rem_anchor_token(T_else);
6525 if(token.type == T_else) {
6527 statement->ifs.false_statement = parse_statement();
6532 return create_invalid_statement();
6536 * Parse a switch statement.
6538 static statement_t *parse_switch(void)
6542 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6543 statement->base.source_position = token.source_position;
6546 expression_t *const expr = parse_expression();
6547 type_t * type = skip_typeref(expr->base.type);
6548 if (is_type_integer(type)) {
6549 type = promote_integer(type);
6550 } else if (is_type_valid(type)) {
6551 errorf(expr->base.source_position,
6552 "switch quantity is not an integer, but '%T'", type);
6553 type = type_error_type;
6555 statement->switchs.expression = create_implicit_cast(expr, type);
6558 switch_statement_t *rem = current_switch;
6559 current_switch = &statement->switchs;
6560 statement->switchs.body = parse_statement();
6561 current_switch = rem;
6563 if (warning.switch_default
6564 && find_default_label(&statement->switchs) == NULL) {
6565 warningf(statement->base.source_position, "switch has no default case");
6570 return create_invalid_statement();
6573 static statement_t *parse_loop_body(statement_t *const loop)
6575 statement_t *const rem = current_loop;
6576 current_loop = loop;
6578 statement_t *const body = parse_statement();
6585 * Parse a while statement.
6587 static statement_t *parse_while(void)
6591 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6592 statement->base.source_position = token.source_position;
6595 add_anchor_token(')');
6596 statement->whiles.condition = parse_expression();
6597 rem_anchor_token(')');
6600 statement->whiles.body = parse_loop_body(statement);
6604 return create_invalid_statement();
6608 * Parse a do statement.
6610 static statement_t *parse_do(void)
6614 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6616 statement->base.source_position = token.source_position;
6618 add_anchor_token(T_while);
6619 statement->do_while.body = parse_loop_body(statement);
6620 rem_anchor_token(T_while);
6624 add_anchor_token(')');
6625 statement->do_while.condition = parse_expression();
6626 rem_anchor_token(')');
6632 return create_invalid_statement();
6636 * Parse a for statement.
6638 static statement_t *parse_for(void)
6642 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6643 statement->base.source_position = token.source_position;
6645 int top = environment_top();
6646 scope_t *last_scope = scope;
6647 set_scope(&statement->fors.scope);
6650 add_anchor_token(')');
6652 if(token.type != ';') {
6653 if(is_declaration_specifier(&token, false)) {
6654 parse_declaration(record_declaration);
6656 expression_t *const init = parse_expression();
6657 statement->fors.initialisation = init;
6658 if (warning.unused_value && !expression_has_effect(init)) {
6659 warningf(init->base.source_position,
6660 "initialisation of 'for'-statement has no effect");
6668 if(token.type != ';') {
6669 statement->fors.condition = parse_expression();
6672 if(token.type != ')') {
6673 expression_t *const step = parse_expression();
6674 statement->fors.step = step;
6675 if (warning.unused_value && !expression_has_effect(step)) {
6676 warningf(step->base.source_position,
6677 "step of 'for'-statement has no effect");
6680 rem_anchor_token(')');
6682 statement->fors.body = parse_loop_body(statement);
6684 assert(scope == &statement->fors.scope);
6685 set_scope(last_scope);
6686 environment_pop_to(top);
6691 rem_anchor_token(')');
6692 assert(scope == &statement->fors.scope);
6693 set_scope(last_scope);
6694 environment_pop_to(top);
6696 return create_invalid_statement();
6700 * Parse a goto statement.
6702 static statement_t *parse_goto(void)
6706 if(token.type != T_IDENTIFIER) {
6707 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6711 symbol_t *symbol = token.v.symbol;
6714 declaration_t *label = get_label(symbol);
6716 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6717 statement->base.source_position = token.source_position;
6719 statement->gotos.label = label;
6721 /* remember the goto's in a list for later checking */
6722 if (goto_last == NULL) {
6723 goto_first = &statement->gotos;
6725 goto_last->next = &statement->gotos;
6727 goto_last = &statement->gotos;
6733 return create_invalid_statement();
6737 * Parse a continue statement.
6739 static statement_t *parse_continue(void)
6741 statement_t *statement;
6742 if (current_loop == NULL) {
6743 errorf(HERE, "continue statement not within loop");
6746 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6748 statement->base.source_position = token.source_position;
6756 return create_invalid_statement();
6760 * Parse a break statement.
6762 static statement_t *parse_break(void)
6764 statement_t *statement;
6765 if (current_switch == NULL && current_loop == NULL) {
6766 errorf(HERE, "break statement not within loop or switch");
6769 statement = allocate_statement_zero(STATEMENT_BREAK);
6771 statement->base.source_position = token.source_position;
6779 return create_invalid_statement();
6783 * Check if a given declaration represents a local variable.
6785 static bool is_local_var_declaration(const declaration_t *declaration) {
6786 switch ((storage_class_tag_t) declaration->storage_class) {
6787 case STORAGE_CLASS_AUTO:
6788 case STORAGE_CLASS_REGISTER: {
6789 const type_t *type = skip_typeref(declaration->type);
6790 if(is_type_function(type)) {
6802 * Check if a given declaration represents a variable.
6804 static bool is_var_declaration(const declaration_t *declaration) {
6805 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6808 const type_t *type = skip_typeref(declaration->type);
6809 return !is_type_function(type);
6813 * Check if a given expression represents a local variable.
6815 static bool is_local_variable(const expression_t *expression)
6817 if (expression->base.kind != EXPR_REFERENCE) {
6820 const declaration_t *declaration = expression->reference.declaration;
6821 return is_local_var_declaration(declaration);
6825 * Check if a given expression represents a local variable and
6826 * return its declaration then, else return NULL.
6828 declaration_t *expr_is_variable(const expression_t *expression)
6830 if (expression->base.kind != EXPR_REFERENCE) {
6833 declaration_t *declaration = expression->reference.declaration;
6834 if (is_var_declaration(declaration))
6840 * Parse a return statement.
6842 static statement_t *parse_return(void)
6846 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6847 statement->base.source_position = token.source_position;
6849 expression_t *return_value = NULL;
6850 if(token.type != ';') {
6851 return_value = parse_expression();
6855 const type_t *const func_type = current_function->type;
6856 assert(is_type_function(func_type));
6857 type_t *const return_type = skip_typeref(func_type->function.return_type);
6859 if(return_value != NULL) {
6860 type_t *return_value_type = skip_typeref(return_value->base.type);
6862 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6863 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6864 warningf(statement->base.source_position,
6865 "'return' with a value, in function returning void");
6866 return_value = NULL;
6868 type_t *const res_type = semantic_assign(return_type,
6869 return_value, "'return'");
6870 if (res_type == NULL) {
6871 errorf(statement->base.source_position,
6872 "cannot return something of type '%T' in function returning '%T'",
6873 return_value->base.type, return_type);
6875 return_value = create_implicit_cast(return_value, res_type);
6878 /* check for returning address of a local var */
6879 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6880 const expression_t *expression = return_value->unary.value;
6881 if (is_local_variable(expression)) {
6882 warningf(statement->base.source_position,
6883 "function returns address of local variable");
6887 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6888 warningf(statement->base.source_position,
6889 "'return' without value, in function returning non-void");
6892 statement->returns.value = return_value;
6896 return create_invalid_statement();
6900 * Parse a declaration statement.
6902 static statement_t *parse_declaration_statement(void)
6904 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6906 statement->base.source_position = token.source_position;
6908 declaration_t *before = last_declaration;
6909 parse_declaration(record_declaration);
6911 if(before == NULL) {
6912 statement->declaration.declarations_begin = scope->declarations;
6914 statement->declaration.declarations_begin = before->next;
6916 statement->declaration.declarations_end = last_declaration;
6922 * Parse an expression statement, ie. expr ';'.
6924 static statement_t *parse_expression_statement(void)
6926 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6928 statement->base.source_position = token.source_position;
6929 expression_t *const expr = parse_expression();
6930 statement->expression.expression = expr;
6932 if (warning.unused_value && !expression_has_effect(expr)) {
6933 warningf(expr->base.source_position, "statement has no effect");
6940 return create_invalid_statement();
6944 * Parse a statement.
6946 static statement_t *parse_statement(void)
6948 statement_t *statement = NULL;
6950 /* declaration or statement */
6951 add_anchor_token(';');
6952 switch(token.type) {
6954 statement = parse_asm_statement();
6958 statement = parse_case_statement();
6962 statement = parse_default_statement();
6966 statement = parse_compound_statement();
6970 statement = parse_if();
6974 statement = parse_switch();
6978 statement = parse_while();
6982 statement = parse_do();
6986 statement = parse_for();
6990 statement = parse_goto();
6994 statement = parse_continue();
6998 statement = parse_break();
7002 statement = parse_return();
7006 if(warning.empty_statement) {
7007 warningf(HERE, "statement is empty");
7009 statement = create_empty_statement();
7014 if(look_ahead(1)->type == ':') {
7015 statement = parse_label_statement();
7019 if(is_typedef_symbol(token.v.symbol)) {
7020 statement = parse_declaration_statement();
7024 statement = parse_expression_statement();
7027 case T___extension__:
7028 /* this can be a prefix to a declaration or an expression statement */
7029 /* we simply eat it now and parse the rest with tail recursion */
7032 } while(token.type == T___extension__);
7033 statement = parse_statement();
7037 statement = parse_declaration_statement();
7041 statement = parse_expression_statement();
7044 rem_anchor_token(';');
7046 assert(statement != NULL
7047 && statement->base.source_position.input_name != NULL);
7053 * Parse a compound statement.
7055 static statement_t *parse_compound_statement(void)
7057 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
7059 statement->base.source_position = token.source_position;
7062 add_anchor_token('}');
7064 int top = environment_top();
7065 scope_t *last_scope = scope;
7066 set_scope(&statement->compound.scope);
7068 statement_t *last_statement = NULL;
7070 while(token.type != '}' && token.type != T_EOF) {
7071 statement_t *sub_statement = parse_statement();
7072 if(is_invalid_statement(sub_statement)) {
7073 /* an error occurred. if we are at an anchor, return */
7079 if(last_statement != NULL) {
7080 last_statement->base.next = sub_statement;
7082 statement->compound.statements = sub_statement;
7085 while(sub_statement->base.next != NULL)
7086 sub_statement = sub_statement->base.next;
7088 last_statement = sub_statement;
7091 if(token.type == '}') {
7094 errorf(statement->base.source_position,
7095 "end of file while looking for closing '}'");
7099 rem_anchor_token('}');
7100 assert(scope == &statement->compound.scope);
7101 set_scope(last_scope);
7102 environment_pop_to(top);
7108 * Initialize builtin types.
7110 static void initialize_builtin_types(void)
7112 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7113 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7114 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7115 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7116 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7117 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7118 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7119 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7121 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7122 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7123 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7124 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7128 * Check for unused global static functions and variables
7130 static void check_unused_globals(void)
7132 if (!warning.unused_function && !warning.unused_variable)
7135 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7136 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7139 type_t *const type = decl->type;
7141 if (is_type_function(skip_typeref(type))) {
7142 if (!warning.unused_function || decl->is_inline)
7145 s = (decl->init.statement != NULL ? "defined" : "declared");
7147 if (!warning.unused_variable)
7153 warningf(decl->source_position, "'%#T' %s but not used",
7154 type, decl->symbol, s);
7159 * Parse a translation unit.
7161 static translation_unit_t *parse_translation_unit(void)
7163 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7165 assert(global_scope == NULL);
7166 global_scope = &unit->scope;
7168 assert(scope == NULL);
7169 set_scope(&unit->scope);
7171 initialize_builtin_types();
7173 while(token.type != T_EOF) {
7174 if (token.type == ';') {
7175 /* TODO error in strict mode */
7176 warningf(HERE, "stray ';' outside of function");
7179 parse_external_declaration();
7183 assert(scope == &unit->scope);
7185 last_declaration = NULL;
7187 assert(global_scope == &unit->scope);
7188 check_unused_globals();
7189 global_scope = NULL;
7197 * @return the translation unit or NULL if errors occurred.
7199 translation_unit_t *parse(void)
7201 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7202 label_stack = NEW_ARR_F(stack_entry_t, 0);
7203 diagnostic_count = 0;
7207 type_set_output(stderr);
7208 ast_set_output(stderr);
7210 lookahead_bufpos = 0;
7211 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7214 translation_unit_t *unit = parse_translation_unit();
7216 DEL_ARR_F(environment_stack);
7217 DEL_ARR_F(label_stack);
7223 * Initialize the parser.
7225 void init_parser(void)
7228 /* add predefined symbols for extended-decl-modifier */
7229 sym_align = symbol_table_insert("align");
7230 sym_allocate = symbol_table_insert("allocate");
7231 sym_dllimport = symbol_table_insert("dllimport");
7232 sym_dllexport = symbol_table_insert("dllexport");
7233 sym_naked = symbol_table_insert("naked");
7234 sym_noinline = symbol_table_insert("noinline");
7235 sym_noreturn = symbol_table_insert("noreturn");
7236 sym_nothrow = symbol_table_insert("nothrow");
7237 sym_novtable = symbol_table_insert("novtable");
7238 sym_property = symbol_table_insert("property");
7239 sym_get = symbol_table_insert("get");
7240 sym_put = symbol_table_insert("put");
7241 sym_selectany = symbol_table_insert("selectany");
7242 sym_thread = symbol_table_insert("thread");
7243 sym_uuid = symbol_table_insert("uuid");
7244 sym_deprecated = symbol_table_insert("deprecated");
7245 sym_restrict = symbol_table_insert("restrict");
7246 sym_noalias = symbol_table_insert("noalias");
7248 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7250 init_expression_parsers();
7251 obstack_init(&temp_obst);
7253 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7254 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7258 * Terminate the parser.
7260 void exit_parser(void)
7262 obstack_free(&temp_obst, NULL);