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. */
57 decl_modifiers_t decl_modifiers; /**< MS __declspec extended modifier mask */
58 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
59 symbol_t *get_property_sym; /**< the name of the get property if set. */
60 symbol_t *put_property_sym; /**< the name of the put property if set. */
65 * An environment for parsing initializers (and compound literals).
67 typedef struct parse_initializer_env_t {
68 type_t *type; /**< the type of the initializer. In case of an
69 array type with unspecified size this gets
70 adjusted to the actual size. */
71 declaration_t *declaration; /**< the declaration that is initialized if any */
72 bool must_be_constant;
73 } parse_initializer_env_t;
75 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
78 static token_t lookahead_buffer[MAX_LOOKAHEAD];
79 static int lookahead_bufpos;
80 static stack_entry_t *environment_stack = NULL;
81 static stack_entry_t *label_stack = NULL;
82 static scope_t *global_scope = NULL;
83 static scope_t *scope = NULL;
84 static declaration_t *last_declaration = NULL;
85 static declaration_t *current_function = NULL;
86 static switch_statement_t *current_switch = NULL;
87 static statement_t *current_loop = NULL;
88 static goto_statement_t *goto_first = NULL;
89 static goto_statement_t *goto_last = NULL;
90 static label_statement_t *label_first = NULL;
91 static label_statement_t *label_last = NULL;
92 static struct obstack temp_obst;
94 /* symbols for Microsoft extended-decl-modifier */
95 static const symbol_t *sym_align = NULL;
96 static const symbol_t *sym_allocate = NULL;
97 static const symbol_t *sym_dllimport = NULL;
98 static const symbol_t *sym_dllexport = NULL;
99 static const symbol_t *sym_naked = NULL;
100 static const symbol_t *sym_noinline = NULL;
101 static const symbol_t *sym_noreturn = NULL;
102 static const symbol_t *sym_nothrow = NULL;
103 static const symbol_t *sym_novtable = NULL;
104 static const symbol_t *sym_property = NULL;
105 static const symbol_t *sym_get = NULL;
106 static const symbol_t *sym_put = NULL;
107 static const symbol_t *sym_selectany = NULL;
108 static const symbol_t *sym_thread = NULL;
109 static const symbol_t *sym_uuid = NULL;
110 static const symbol_t *sym_deprecated = NULL;
111 static const symbol_t *sym_restrict = NULL;
112 static const symbol_t *sym_noalias = NULL;
114 /** The token anchor set */
115 static unsigned char token_anchor_set[T_LAST_TOKEN];
117 /** The current source position. */
118 #define HERE token.source_position
120 static type_t *type_valist;
122 static statement_t *parse_compound_statement(void);
123 static statement_t *parse_statement(void);
125 static expression_t *parse_sub_expression(unsigned precedence);
126 static expression_t *parse_expression(void);
127 static type_t *parse_typename(void);
129 static void parse_compound_type_entries(declaration_t *compound_declaration);
130 static declaration_t *parse_declarator(
131 const declaration_specifiers_t *specifiers, bool may_be_abstract);
132 static declaration_t *record_declaration(declaration_t *declaration);
134 static void semantic_comparison(binary_expression_t *expression);
136 #define STORAGE_CLASSES \
143 #define TYPE_QUALIFIERS \
150 #ifdef PROVIDE_COMPLEX
151 #define COMPLEX_SPECIFIERS \
153 #define IMAGINARY_SPECIFIERS \
156 #define COMPLEX_SPECIFIERS
157 #define IMAGINARY_SPECIFIERS
160 #define TYPE_SPECIFIERS \
175 case T___builtin_va_list: \
179 #define DECLARATION_START \
184 #define TYPENAME_START \
189 * Allocate an AST node with given size and
190 * initialize all fields with zero.
192 static void *allocate_ast_zero(size_t size)
194 void *res = allocate_ast(size);
195 memset(res, 0, size);
199 static declaration_t *allocate_declaration_zero(void)
201 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
202 declaration->type = type_error_type;
203 declaration->alignment = 0;
208 * Returns the size of a statement node.
210 * @param kind the statement kind
212 static size_t get_statement_struct_size(statement_kind_t kind)
214 static const size_t sizes[] = {
215 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
216 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
217 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
218 [STATEMENT_RETURN] = sizeof(return_statement_t),
219 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
220 [STATEMENT_IF] = sizeof(if_statement_t),
221 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
222 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
223 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
224 [STATEMENT_BREAK] = sizeof(statement_base_t),
225 [STATEMENT_GOTO] = sizeof(goto_statement_t),
226 [STATEMENT_LABEL] = sizeof(label_statement_t),
227 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
228 [STATEMENT_WHILE] = sizeof(while_statement_t),
229 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
230 [STATEMENT_FOR] = sizeof(for_statement_t),
231 [STATEMENT_ASM] = sizeof(asm_statement_t)
233 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
234 assert(sizes[kind] != 0);
239 * Allocate a statement node of given kind and initialize all
242 static statement_t *allocate_statement_zero(statement_kind_t kind)
244 size_t size = get_statement_struct_size(kind);
245 statement_t *res = allocate_ast_zero(size);
247 res->base.kind = kind;
252 * Creates a new invalid statement.
254 static statement_t *create_invalid_statement(void)
256 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
257 statement->base.source_position = token.source_position;
262 * Allocate a new empty statement.
264 static statement_t *create_empty_statement(void)
266 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
267 statement->base.source_position = token.source_position;
272 * Returns the size of an expression node.
274 * @param kind the expression kind
276 static size_t get_expression_struct_size(expression_kind_t kind)
278 static const size_t sizes[] = {
279 [EXPR_INVALID] = sizeof(expression_base_t),
280 [EXPR_REFERENCE] = sizeof(reference_expression_t),
281 [EXPR_CONST] = sizeof(const_expression_t),
282 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
283 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
284 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
285 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
286 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
287 [EXPR_CALL] = sizeof(call_expression_t),
288 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
289 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
290 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
291 [EXPR_SELECT] = sizeof(select_expression_t),
292 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
293 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
294 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
295 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
296 [EXPR_FUNCTION] = sizeof(string_literal_expression_t),
297 [EXPR_PRETTY_FUNCTION] = sizeof(string_literal_expression_t),
298 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
299 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
300 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
301 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
302 [EXPR_VA_START] = sizeof(va_start_expression_t),
303 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
304 [EXPR_STATEMENT] = sizeof(statement_expression_t),
306 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
307 return sizes[EXPR_UNARY_FIRST];
309 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
310 return sizes[EXPR_BINARY_FIRST];
312 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
313 assert(sizes[kind] != 0);
318 * Allocate an expression node of given kind and initialize all
321 static expression_t *allocate_expression_zero(expression_kind_t kind)
323 size_t size = get_expression_struct_size(kind);
324 expression_t *res = allocate_ast_zero(size);
326 res->base.kind = kind;
327 res->base.type = type_error_type;
332 * Returns the size of a type node.
334 * @param kind the type kind
336 static size_t get_type_struct_size(type_kind_t kind)
338 static const size_t sizes[] = {
339 [TYPE_ATOMIC] = sizeof(atomic_type_t),
340 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
341 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
342 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
343 [TYPE_ENUM] = sizeof(enum_type_t),
344 [TYPE_FUNCTION] = sizeof(function_type_t),
345 [TYPE_POINTER] = sizeof(pointer_type_t),
346 [TYPE_ARRAY] = sizeof(array_type_t),
347 [TYPE_BUILTIN] = sizeof(builtin_type_t),
348 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
349 [TYPE_TYPEOF] = sizeof(typeof_type_t),
351 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
352 assert(kind <= TYPE_TYPEOF);
353 assert(sizes[kind] != 0);
358 * Allocate a type node of given kind and initialize all
361 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
363 size_t size = get_type_struct_size(kind);
364 type_t *res = obstack_alloc(type_obst, size);
365 memset(res, 0, size);
367 res->base.kind = kind;
368 res->base.source_position = source_position;
373 * Returns the size of an initializer node.
375 * @param kind the initializer kind
377 static size_t get_initializer_size(initializer_kind_t kind)
379 static const size_t sizes[] = {
380 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
381 [INITIALIZER_STRING] = sizeof(initializer_string_t),
382 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
383 [INITIALIZER_LIST] = sizeof(initializer_list_t),
384 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
386 assert(kind < sizeof(sizes) / sizeof(*sizes));
387 assert(sizes[kind] != 0);
392 * Allocate an initializer node of given kind and initialize all
395 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
397 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
404 * Free a type from the type obstack.
406 static void free_type(void *type)
408 obstack_free(type_obst, type);
412 * Returns the index of the top element of the environment stack.
414 static size_t environment_top(void)
416 return ARR_LEN(environment_stack);
420 * Returns the index of the top element of the label stack.
422 static size_t label_top(void)
424 return ARR_LEN(label_stack);
428 * Return the next token.
430 static inline void next_token(void)
432 token = lookahead_buffer[lookahead_bufpos];
433 lookahead_buffer[lookahead_bufpos] = lexer_token;
436 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
439 print_token(stderr, &token);
440 fprintf(stderr, "\n");
445 * Return the next token with a given lookahead.
447 static inline const token_t *look_ahead(int num)
449 assert(num > 0 && num <= MAX_LOOKAHEAD);
450 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
451 return &lookahead_buffer[pos];
455 * Adds a token to the token anchor set (a multi-set).
457 static void add_anchor_token(int token_type) {
458 assert(0 <= token_type && token_type < T_LAST_TOKEN);
459 ++token_anchor_set[token_type];
463 * Remove a token from the token anchor set (a multi-set).
465 static void rem_anchor_token(int token_type) {
466 assert(0 <= token_type && token_type < T_LAST_TOKEN);
467 --token_anchor_set[token_type];
470 static bool at_anchor(void) {
473 return token_anchor_set[token.type];
477 * Eat tokens until a matching token is found.
479 static void eat_until_matching_token(int type) {
480 unsigned parenthesis_count = 0;
481 unsigned brace_count = 0;
482 unsigned bracket_count = 0;
483 int end_token = type;
492 while(token.type != end_token ||
493 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
497 case '(': ++parenthesis_count; break;
498 case '{': ++brace_count; break;
499 case '[': ++bracket_count; break;
501 if(parenthesis_count > 0)
509 if(bracket_count > 0)
520 * Eat input tokens until an anchor is found.
522 static void eat_until_anchor(void) {
523 if(token.type == T_EOF)
525 while(token_anchor_set[token.type] == 0) {
526 if(token.type == '(' || token.type == '{' || token.type == '[')
527 eat_until_matching_token(token.type);
528 if(token.type == T_EOF)
534 static void eat_block(void) {
535 eat_until_matching_token('{');
536 if(token.type == '}')
541 * eat all token until a ';' is reached
542 * or a stop token is found.
544 static void eat_statement(void) {
545 eat_until_matching_token(';');
546 if(token.type == ';')
550 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
553 * Report a parse error because an expected token was not found.
555 static void parse_error_expected(const char *message, ...)
557 if(message != NULL) {
558 errorf(HERE, "%s", message);
561 va_start(ap, message);
562 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
567 * Report a type error.
569 static void type_error(const char *msg, const source_position_t source_position,
572 errorf(source_position, "%s, but found type '%T'", msg, type);
576 * Report an incompatible type.
578 static void type_error_incompatible(const char *msg,
579 const source_position_t source_position, type_t *type1, type_t *type2)
581 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
585 * Expect the the current token is the expected token.
586 * If not, generate an error, eat the current statement,
587 * and goto the end_error label.
589 #define expect(expected) \
591 if(UNLIKELY(token.type != (expected))) { \
592 parse_error_expected(NULL, (expected), 0); \
593 add_anchor_token(expected); \
594 eat_until_anchor(); \
595 rem_anchor_token(expected); \
601 static void set_scope(scope_t *new_scope)
604 scope->last_declaration = last_declaration;
608 last_declaration = new_scope->last_declaration;
612 * Search a symbol in a given namespace and returns its declaration or
613 * NULL if this symbol was not found.
615 static declaration_t *get_declaration(const symbol_t *const symbol,
616 const namespace_t namespc)
618 declaration_t *declaration = symbol->declaration;
619 for( ; declaration != NULL; declaration = declaration->symbol_next) {
620 if(declaration->namespc == namespc)
628 * pushs an environment_entry on the environment stack and links the
629 * corresponding symbol to the new entry
631 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
633 symbol_t *symbol = declaration->symbol;
634 namespace_t namespc = (namespace_t) declaration->namespc;
636 /* replace/add declaration into declaration list of the symbol */
637 declaration_t *iter = symbol->declaration;
639 symbol->declaration = declaration;
641 declaration_t *iter_last = NULL;
642 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
643 /* replace an entry? */
644 if(iter->namespc == namespc) {
645 if(iter_last == NULL) {
646 symbol->declaration = declaration;
648 iter_last->symbol_next = declaration;
650 declaration->symbol_next = iter->symbol_next;
655 assert(iter_last->symbol_next == NULL);
656 iter_last->symbol_next = declaration;
660 /* remember old declaration */
662 entry.symbol = symbol;
663 entry.old_declaration = iter;
664 entry.namespc = (unsigned short) namespc;
665 ARR_APP1(stack_entry_t, *stack_ptr, entry);
668 static void environment_push(declaration_t *declaration)
670 assert(declaration->source_position.input_name != NULL);
671 assert(declaration->parent_scope != NULL);
672 stack_push(&environment_stack, declaration);
675 static void label_push(declaration_t *declaration)
677 declaration->parent_scope = ¤t_function->scope;
678 stack_push(&label_stack, declaration);
682 * pops symbols from the environment stack until @p new_top is the top element
684 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
686 stack_entry_t *stack = *stack_ptr;
687 size_t top = ARR_LEN(stack);
690 assert(new_top <= top);
694 for(i = top; i > new_top; --i) {
695 stack_entry_t *entry = &stack[i - 1];
697 declaration_t *old_declaration = entry->old_declaration;
698 symbol_t *symbol = entry->symbol;
699 namespace_t namespc = (namespace_t)entry->namespc;
701 /* replace/remove declaration */
702 declaration_t *declaration = symbol->declaration;
703 assert(declaration != NULL);
704 if(declaration->namespc == namespc) {
705 if(old_declaration == NULL) {
706 symbol->declaration = declaration->symbol_next;
708 symbol->declaration = old_declaration;
711 declaration_t *iter_last = declaration;
712 declaration_t *iter = declaration->symbol_next;
713 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
714 /* replace an entry? */
715 if(iter->namespc == namespc) {
716 assert(iter_last != NULL);
717 iter_last->symbol_next = old_declaration;
718 if(old_declaration != NULL) {
719 old_declaration->symbol_next = iter->symbol_next;
724 assert(iter != NULL);
728 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
731 static void environment_pop_to(size_t new_top)
733 stack_pop_to(&environment_stack, new_top);
736 static void label_pop_to(size_t new_top)
738 stack_pop_to(&label_stack, new_top);
742 static int get_rank(const type_t *type)
744 assert(!is_typeref(type));
745 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
746 * and esp. footnote 108). However we can't fold constants (yet), so we
747 * can't decide whether unsigned int is possible, while int always works.
748 * (unsigned int would be preferable when possible... for stuff like
749 * struct { enum { ... } bla : 4; } ) */
750 if(type->kind == TYPE_ENUM)
751 return ATOMIC_TYPE_INT;
753 assert(type->kind == TYPE_ATOMIC);
754 return type->atomic.akind;
757 static type_t *promote_integer(type_t *type)
759 if(type->kind == TYPE_BITFIELD)
760 type = type->bitfield.base;
762 if(get_rank(type) < ATOMIC_TYPE_INT)
769 * Create a cast expression.
771 * @param expression the expression to cast
772 * @param dest_type the destination type
774 static expression_t *create_cast_expression(expression_t *expression,
777 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
779 cast->unary.value = expression;
780 cast->base.type = dest_type;
786 * Check if a given expression represents the 0 pointer constant.
788 static bool is_null_pointer_constant(const expression_t *expression)
790 /* skip void* cast */
791 if(expression->kind == EXPR_UNARY_CAST
792 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
793 expression = expression->unary.value;
796 /* TODO: not correct yet, should be any constant integer expression
797 * which evaluates to 0 */
798 if (expression->kind != EXPR_CONST)
801 type_t *const type = skip_typeref(expression->base.type);
802 if (!is_type_integer(type))
805 return expression->conste.v.int_value == 0;
809 * Create an implicit cast expression.
811 * @param expression the expression to cast
812 * @param dest_type the destination type
814 static expression_t *create_implicit_cast(expression_t *expression,
817 type_t *const source_type = expression->base.type;
819 if (source_type == dest_type)
822 return create_cast_expression(expression, dest_type);
825 /** Implements the rules from § 6.5.16.1 */
826 static type_t *semantic_assign(type_t *orig_type_left,
827 const expression_t *const right,
830 type_t *const orig_type_right = right->base.type;
831 type_t *const type_left = skip_typeref(orig_type_left);
832 type_t *const type_right = skip_typeref(orig_type_right);
834 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
835 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
836 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
837 && is_type_pointer(type_right))) {
838 return orig_type_left;
841 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
842 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
843 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
845 /* the left type has all qualifiers from the right type */
846 unsigned missing_qualifiers
847 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
848 if(missing_qualifiers != 0) {
849 errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
850 return orig_type_left;
853 points_to_left = get_unqualified_type(points_to_left);
854 points_to_right = get_unqualified_type(points_to_right);
856 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
857 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
858 return orig_type_left;
861 if (!types_compatible(points_to_left, points_to_right)) {
862 warningf(right->base.source_position,
863 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
864 orig_type_left, context, right, orig_type_right);
867 return orig_type_left;
870 if ((is_type_compound(type_left) && is_type_compound(type_right))
871 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
872 type_t *const unqual_type_left = get_unqualified_type(type_left);
873 type_t *const unqual_type_right = get_unqualified_type(type_right);
874 if (types_compatible(unqual_type_left, unqual_type_right)) {
875 return orig_type_left;
879 if (!is_type_valid(type_left))
882 if (!is_type_valid(type_right))
883 return orig_type_right;
888 static expression_t *parse_constant_expression(void)
890 /* start parsing at precedence 7 (conditional expression) */
891 expression_t *result = parse_sub_expression(7);
893 if(!is_constant_expression(result)) {
894 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
900 static expression_t *parse_assignment_expression(void)
902 /* start parsing at precedence 2 (assignment expression) */
903 return parse_sub_expression(2);
906 static type_t *make_global_typedef(const char *name, type_t *type)
908 symbol_t *const symbol = symbol_table_insert(name);
910 declaration_t *const declaration = allocate_declaration_zero();
911 declaration->namespc = NAMESPACE_NORMAL;
912 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
913 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
914 declaration->type = type;
915 declaration->symbol = symbol;
916 declaration->source_position = builtin_source_position;
918 record_declaration(declaration);
920 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
921 typedef_type->typedeft.declaration = declaration;
926 static string_t parse_string_literals(void)
928 assert(token.type == T_STRING_LITERAL);
929 string_t result = token.v.string;
933 while (token.type == T_STRING_LITERAL) {
934 result = concat_strings(&result, &token.v.string);
941 static void parse_attributes(void)
945 case T___attribute__: {
953 errorf(HERE, "EOF while parsing attribute");
972 if(token.type != T_STRING_LITERAL) {
973 parse_error_expected("while parsing assembler attribute",
975 eat_until_matching_token('(');
978 parse_string_literals();
983 goto attributes_finished;
992 static designator_t *parse_designation(void)
994 designator_t *result = NULL;
995 designator_t *last = NULL;
998 designator_t *designator;
1001 designator = allocate_ast_zero(sizeof(designator[0]));
1002 designator->source_position = token.source_position;
1004 add_anchor_token(']');
1005 designator->array_index = parse_constant_expression();
1006 rem_anchor_token(']');
1010 designator = allocate_ast_zero(sizeof(designator[0]));
1011 designator->source_position = token.source_position;
1013 if(token.type != T_IDENTIFIER) {
1014 parse_error_expected("while parsing designator",
1018 designator->symbol = token.v.symbol;
1026 assert(designator != NULL);
1028 last->next = designator;
1030 result = designator;
1038 static initializer_t *initializer_from_string(array_type_t *type,
1039 const string_t *const string)
1041 /* TODO: check len vs. size of array type */
1044 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1045 initializer->string.string = *string;
1050 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1051 wide_string_t *const string)
1053 /* TODO: check len vs. size of array type */
1056 initializer_t *const initializer =
1057 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1058 initializer->wide_string.string = *string;
1064 * Build an initializer from a given expression.
1066 static initializer_t *initializer_from_expression(type_t *orig_type,
1067 expression_t *expression)
1069 /* TODO check that expression is a constant expression */
1071 /* § 6.7.8.14/15 char array may be initialized by string literals */
1072 type_t *type = skip_typeref(orig_type);
1073 type_t *expr_type_orig = expression->base.type;
1074 type_t *expr_type = skip_typeref(expr_type_orig);
1075 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1076 array_type_t *const array_type = &type->array;
1077 type_t *const element_type = skip_typeref(array_type->element_type);
1079 if (element_type->kind == TYPE_ATOMIC) {
1080 atomic_type_kind_t akind = element_type->atomic.akind;
1081 switch (expression->kind) {
1082 case EXPR_STRING_LITERAL:
1083 if (akind == ATOMIC_TYPE_CHAR
1084 || akind == ATOMIC_TYPE_SCHAR
1085 || akind == ATOMIC_TYPE_UCHAR) {
1086 return initializer_from_string(array_type,
1087 &expression->string.value);
1090 case EXPR_WIDE_STRING_LITERAL: {
1091 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1092 if (get_unqualified_type(element_type) == bare_wchar_type) {
1093 return initializer_from_wide_string(array_type,
1094 &expression->wide_string.value);
1104 type_t *const res_type = semantic_assign(type, expression, "initializer");
1105 if (res_type == NULL)
1108 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1109 result->value.value = create_implicit_cast(expression, res_type);
1115 * Checks if a given expression can be used as an constant initializer.
1117 static bool is_initializer_constant(const expression_t *expression)
1119 return is_constant_expression(expression)
1120 || is_address_constant(expression);
1124 * Parses an scalar initializer.
1126 * § 6.7.8.11; eat {} without warning
1128 static initializer_t *parse_scalar_initializer(type_t *type,
1129 bool must_be_constant)
1131 /* there might be extra {} hierarchies */
1133 while(token.type == '{') {
1136 warningf(HERE, "extra curly braces around scalar initializer");
1141 expression_t *expression = parse_assignment_expression();
1142 if(must_be_constant && !is_initializer_constant(expression)) {
1143 errorf(expression->base.source_position,
1144 "Initialisation expression '%E' is not constant\n",
1148 initializer_t *initializer = initializer_from_expression(type, expression);
1150 if(initializer == NULL) {
1151 errorf(expression->base.source_position,
1152 "expression '%E' doesn't match expected type '%T'",
1158 bool additional_warning_displayed = false;
1160 if(token.type == ',') {
1163 if(token.type != '}') {
1164 if(!additional_warning_displayed) {
1165 warningf(HERE, "additional elements in scalar initializer");
1166 additional_warning_displayed = true;
1177 * An entry in the type path.
1179 typedef struct type_path_entry_t type_path_entry_t;
1180 struct type_path_entry_t {
1181 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1183 size_t index; /**< For array types: the current index. */
1184 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1189 * A type path expression a position inside compound or array types.
1191 typedef struct type_path_t type_path_t;
1192 struct type_path_t {
1193 type_path_entry_t *path; /**< An flexible array containing the current path. */
1194 type_t *top_type; /**< type of the element the path points */
1195 size_t max_index; /**< largest index in outermost array */
1199 * Prints a type path for debugging.
1201 static __attribute__((unused)) void debug_print_type_path(
1202 const type_path_t *path)
1204 size_t len = ARR_LEN(path->path);
1206 for(size_t i = 0; i < len; ++i) {
1207 const type_path_entry_t *entry = & path->path[i];
1209 type_t *type = skip_typeref(entry->type);
1210 if(is_type_compound(type)) {
1211 /* in gcc mode structs can have no members */
1212 if(entry->v.compound_entry == NULL) {
1216 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1217 } else if(is_type_array(type)) {
1218 fprintf(stderr, "[%u]", entry->v.index);
1220 fprintf(stderr, "-INVALID-");
1223 if(path->top_type != NULL) {
1224 fprintf(stderr, " (");
1225 print_type(path->top_type);
1226 fprintf(stderr, ")");
1231 * Return the top type path entry, ie. in a path
1232 * (type).a.b returns the b.
1234 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1236 size_t len = ARR_LEN(path->path);
1238 return &path->path[len-1];
1242 * Enlarge the type path by an (empty) element.
1244 static type_path_entry_t *append_to_type_path(type_path_t *path)
1246 size_t len = ARR_LEN(path->path);
1247 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1249 type_path_entry_t *result = & path->path[len];
1250 memset(result, 0, sizeof(result[0]));
1255 * Descending into a sub-type. Enter the scope of the current
1258 static void descend_into_subtype(type_path_t *path)
1260 type_t *orig_top_type = path->top_type;
1261 type_t *top_type = skip_typeref(orig_top_type);
1263 assert(is_type_compound(top_type) || is_type_array(top_type));
1265 type_path_entry_t *top = append_to_type_path(path);
1266 top->type = top_type;
1268 if(is_type_compound(top_type)) {
1269 declaration_t *declaration = top_type->compound.declaration;
1270 declaration_t *entry = declaration->scope.declarations;
1271 top->v.compound_entry = entry;
1274 path->top_type = entry->type;
1276 path->top_type = NULL;
1279 assert(is_type_array(top_type));
1282 path->top_type = top_type->array.element_type;
1287 * Pop an entry from the given type path, ie. returning from
1288 * (type).a.b to (type).a
1290 static void ascend_from_subtype(type_path_t *path)
1292 type_path_entry_t *top = get_type_path_top(path);
1294 path->top_type = top->type;
1296 size_t len = ARR_LEN(path->path);
1297 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1301 * Pop entries from the given type path until the given
1302 * path level is reached.
1304 static void ascend_to(type_path_t *path, size_t top_path_level)
1306 size_t len = ARR_LEN(path->path);
1308 while(len > top_path_level) {
1309 ascend_from_subtype(path);
1310 len = ARR_LEN(path->path);
1314 static bool walk_designator(type_path_t *path, const designator_t *designator,
1315 bool used_in_offsetof)
1317 for( ; designator != NULL; designator = designator->next) {
1318 type_path_entry_t *top = get_type_path_top(path);
1319 type_t *orig_type = top->type;
1321 type_t *type = skip_typeref(orig_type);
1323 if(designator->symbol != NULL) {
1324 symbol_t *symbol = designator->symbol;
1325 if(!is_type_compound(type)) {
1326 if(is_type_valid(type)) {
1327 errorf(designator->source_position,
1328 "'.%Y' designator used for non-compound type '%T'",
1334 declaration_t *declaration = type->compound.declaration;
1335 declaration_t *iter = declaration->scope.declarations;
1336 for( ; iter != NULL; iter = iter->next) {
1337 if(iter->symbol == symbol) {
1342 errorf(designator->source_position,
1343 "'%T' has no member named '%Y'", orig_type, symbol);
1346 if(used_in_offsetof) {
1347 type_t *real_type = skip_typeref(iter->type);
1348 if(real_type->kind == TYPE_BITFIELD) {
1349 errorf(designator->source_position,
1350 "offsetof designator '%Y' may not specify bitfield",
1356 top->type = orig_type;
1357 top->v.compound_entry = iter;
1358 orig_type = iter->type;
1360 expression_t *array_index = designator->array_index;
1361 assert(designator->array_index != NULL);
1363 if(!is_type_array(type)) {
1364 if(is_type_valid(type)) {
1365 errorf(designator->source_position,
1366 "[%E] designator used for non-array type '%T'",
1367 array_index, orig_type);
1371 if(!is_type_valid(array_index->base.type)) {
1375 long index = fold_constant(array_index);
1376 if(!used_in_offsetof) {
1378 errorf(designator->source_position,
1379 "array index [%E] must be positive", array_index);
1382 if(type->array.size_constant == true) {
1383 long array_size = type->array.size;
1384 if(index >= array_size) {
1385 errorf(designator->source_position,
1386 "designator [%E] (%d) exceeds array size %d",
1387 array_index, index, array_size);
1393 top->type = orig_type;
1394 top->v.index = (size_t) index;
1395 orig_type = type->array.element_type;
1397 path->top_type = orig_type;
1399 if(designator->next != NULL) {
1400 descend_into_subtype(path);
1409 static void advance_current_object(type_path_t *path, size_t top_path_level)
1411 type_path_entry_t *top = get_type_path_top(path);
1413 type_t *type = skip_typeref(top->type);
1414 if(is_type_union(type)) {
1415 /* in unions only the first element is initialized */
1416 top->v.compound_entry = NULL;
1417 } else if(is_type_struct(type)) {
1418 declaration_t *entry = top->v.compound_entry;
1420 entry = entry->next;
1421 top->v.compound_entry = entry;
1423 path->top_type = entry->type;
1427 assert(is_type_array(type));
1431 if(!type->array.size_constant || top->v.index < type->array.size) {
1436 /* we're past the last member of the current sub-aggregate, try if we
1437 * can ascend in the type hierarchy and continue with another subobject */
1438 size_t len = ARR_LEN(path->path);
1440 if(len > top_path_level) {
1441 ascend_from_subtype(path);
1442 advance_current_object(path, top_path_level);
1444 path->top_type = NULL;
1449 * skip until token is found.
1451 static void skip_until(int type) {
1452 while(token.type != type) {
1453 if(token.type == T_EOF)
1460 * skip any {...} blocks until a closing braket is reached.
1462 static void skip_initializers(void)
1464 if(token.type == '{')
1467 while(token.type != '}') {
1468 if(token.type == T_EOF)
1470 if(token.type == '{') {
1479 * Parse a part of an initialiser for a struct or union,
1481 static initializer_t *parse_sub_initializer(type_path_t *path,
1482 type_t *outer_type, size_t top_path_level,
1483 parse_initializer_env_t *env)
1485 if(token.type == '}') {
1486 /* empty initializer */
1490 type_t *orig_type = path->top_type;
1491 type_t *type = NULL;
1493 if (orig_type == NULL) {
1494 /* We are initializing an empty compound. */
1496 type = skip_typeref(orig_type);
1498 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1499 * initializers in this case. */
1500 if(!is_type_valid(type)) {
1501 skip_initializers();
1506 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1509 designator_t *designator = NULL;
1510 if(token.type == '.' || token.type == '[') {
1511 designator = parse_designation();
1513 /* reset path to toplevel, evaluate designator from there */
1514 ascend_to(path, top_path_level);
1515 if(!walk_designator(path, designator, false)) {
1516 /* can't continue after designation error */
1520 initializer_t *designator_initializer
1521 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1522 designator_initializer->designator.designator = designator;
1523 ARR_APP1(initializer_t*, initializers, designator_initializer);
1528 if(token.type == '{') {
1529 if(type != NULL && is_type_scalar(type)) {
1530 sub = parse_scalar_initializer(type, env->must_be_constant);
1534 if (env->declaration != NULL)
1535 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1536 env->declaration->symbol);
1538 errorf(HERE, "extra brace group at end of initializer");
1540 descend_into_subtype(path);
1542 add_anchor_token('}');
1543 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1545 rem_anchor_token('}');
1548 ascend_from_subtype(path);
1552 goto error_parse_next;
1556 /* must be an expression */
1557 expression_t *expression = parse_assignment_expression();
1559 if(env->must_be_constant && !is_initializer_constant(expression)) {
1560 errorf(expression->base.source_position,
1561 "Initialisation expression '%E' is not constant\n",
1566 /* we are already outside, ... */
1570 /* handle { "string" } special case */
1571 if((expression->kind == EXPR_STRING_LITERAL
1572 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1573 && outer_type != NULL) {
1574 sub = initializer_from_expression(outer_type, expression);
1576 if(token.type == ',') {
1579 if(token.type != '}') {
1580 warningf(HERE, "excessive elements in initializer for type '%T'",
1583 /* TODO: eat , ... */
1588 /* descend into subtypes until expression matches type */
1590 orig_type = path->top_type;
1591 type = skip_typeref(orig_type);
1593 sub = initializer_from_expression(orig_type, expression);
1597 if(!is_type_valid(type)) {
1600 if(is_type_scalar(type)) {
1601 errorf(expression->base.source_position,
1602 "expression '%E' doesn't match expected type '%T'",
1603 expression, orig_type);
1607 descend_into_subtype(path);
1611 /* update largest index of top array */
1612 const type_path_entry_t *first = &path->path[0];
1613 type_t *first_type = first->type;
1614 first_type = skip_typeref(first_type);
1615 if(is_type_array(first_type)) {
1616 size_t index = first->v.index;
1617 if(index > path->max_index)
1618 path->max_index = index;
1622 /* append to initializers list */
1623 ARR_APP1(initializer_t*, initializers, sub);
1626 if(env->declaration != NULL)
1627 warningf(HERE, "excess elements in struct initializer for '%Y'",
1628 env->declaration->symbol);
1630 warningf(HERE, "excess elements in struct initializer");
1634 if(token.type == '}') {
1638 if(token.type == '}') {
1643 /* advance to the next declaration if we are not at the end */
1644 advance_current_object(path, top_path_level);
1645 orig_type = path->top_type;
1646 if(orig_type != NULL)
1647 type = skip_typeref(orig_type);
1653 size_t len = ARR_LEN(initializers);
1654 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1655 initializer_t *result = allocate_ast_zero(size);
1656 result->kind = INITIALIZER_LIST;
1657 result->list.len = len;
1658 memcpy(&result->list.initializers, initializers,
1659 len * sizeof(initializers[0]));
1661 DEL_ARR_F(initializers);
1662 ascend_to(path, top_path_level);
1667 skip_initializers();
1668 DEL_ARR_F(initializers);
1669 ascend_to(path, top_path_level);
1674 * Parses an initializer. Parsers either a compound literal
1675 * (env->declaration == NULL) or an initializer of a declaration.
1677 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1679 type_t *type = skip_typeref(env->type);
1680 initializer_t *result = NULL;
1683 if(is_type_scalar(type)) {
1684 result = parse_scalar_initializer(type, env->must_be_constant);
1685 } else if(token.type == '{') {
1689 memset(&path, 0, sizeof(path));
1690 path.top_type = env->type;
1691 path.path = NEW_ARR_F(type_path_entry_t, 0);
1693 descend_into_subtype(&path);
1695 add_anchor_token('}');
1696 result = parse_sub_initializer(&path, env->type, 1, env);
1697 rem_anchor_token('}');
1699 max_index = path.max_index;
1700 DEL_ARR_F(path.path);
1704 /* parse_scalar_initializer() also works in this case: we simply
1705 * have an expression without {} around it */
1706 result = parse_scalar_initializer(type, env->must_be_constant);
1709 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1710 * the array type size */
1711 if(is_type_array(type) && type->array.size_expression == NULL
1712 && result != NULL) {
1714 switch (result->kind) {
1715 case INITIALIZER_LIST:
1716 size = max_index + 1;
1719 case INITIALIZER_STRING:
1720 size = result->string.string.size;
1723 case INITIALIZER_WIDE_STRING:
1724 size = result->wide_string.string.size;
1728 internal_errorf(HERE, "invalid initializer type");
1731 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1732 cnst->base.type = type_size_t;
1733 cnst->conste.v.int_value = size;
1735 type_t *new_type = duplicate_type(type);
1737 new_type->array.size_expression = cnst;
1738 new_type->array.size_constant = true;
1739 new_type->array.size = size;
1740 env->type = new_type;
1748 static declaration_t *append_declaration(declaration_t *declaration);
1750 static declaration_t *parse_compound_type_specifier(bool is_struct)
1758 symbol_t *symbol = NULL;
1759 declaration_t *declaration = NULL;
1761 if (token.type == T___attribute__) {
1766 if(token.type == T_IDENTIFIER) {
1767 symbol = token.v.symbol;
1771 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1773 declaration = get_declaration(symbol, NAMESPACE_UNION);
1775 } else if(token.type != '{') {
1777 parse_error_expected("while parsing struct type specifier",
1778 T_IDENTIFIER, '{', 0);
1780 parse_error_expected("while parsing union type specifier",
1781 T_IDENTIFIER, '{', 0);
1787 if(declaration == NULL) {
1788 declaration = allocate_declaration_zero();
1789 declaration->namespc =
1790 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1791 declaration->source_position = token.source_position;
1792 declaration->symbol = symbol;
1793 declaration->parent_scope = scope;
1794 if (symbol != NULL) {
1795 environment_push(declaration);
1797 append_declaration(declaration);
1800 if(token.type == '{') {
1801 if(declaration->init.is_defined) {
1802 assert(symbol != NULL);
1803 errorf(HERE, "multiple definitions of '%s %Y'",
1804 is_struct ? "struct" : "union", symbol);
1805 declaration->scope.declarations = NULL;
1807 declaration->init.is_defined = true;
1809 parse_compound_type_entries(declaration);
1816 static void parse_enum_entries(type_t *const enum_type)
1820 if(token.type == '}') {
1822 errorf(HERE, "empty enum not allowed");
1826 add_anchor_token('}');
1828 if(token.type != T_IDENTIFIER) {
1829 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1831 rem_anchor_token('}');
1835 declaration_t *const entry = allocate_declaration_zero();
1836 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1837 entry->type = enum_type;
1838 entry->symbol = token.v.symbol;
1839 entry->source_position = token.source_position;
1842 if(token.type == '=') {
1844 expression_t *value = parse_constant_expression();
1846 value = create_implicit_cast(value, enum_type);
1847 entry->init.enum_value = value;
1852 record_declaration(entry);
1854 if(token.type != ',')
1857 } while(token.type != '}');
1858 rem_anchor_token('}');
1866 static type_t *parse_enum_specifier(void)
1870 declaration_t *declaration;
1873 if(token.type == T_IDENTIFIER) {
1874 symbol = token.v.symbol;
1877 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1878 } else if(token.type != '{') {
1879 parse_error_expected("while parsing enum type specifier",
1880 T_IDENTIFIER, '{', 0);
1887 if(declaration == NULL) {
1888 declaration = allocate_declaration_zero();
1889 declaration->namespc = NAMESPACE_ENUM;
1890 declaration->source_position = token.source_position;
1891 declaration->symbol = symbol;
1892 declaration->parent_scope = scope;
1895 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1896 type->enumt.declaration = declaration;
1898 if(token.type == '{') {
1899 if(declaration->init.is_defined) {
1900 errorf(HERE, "multiple definitions of enum %Y", symbol);
1902 if (symbol != NULL) {
1903 environment_push(declaration);
1905 append_declaration(declaration);
1906 declaration->init.is_defined = 1;
1908 parse_enum_entries(type);
1916 * if a symbol is a typedef to another type, return true
1918 static bool is_typedef_symbol(symbol_t *symbol)
1920 const declaration_t *const declaration =
1921 get_declaration(symbol, NAMESPACE_NORMAL);
1923 declaration != NULL &&
1924 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1927 static type_t *parse_typeof(void)
1934 add_anchor_token(')');
1936 expression_t *expression = NULL;
1939 switch(token.type) {
1940 case T___extension__:
1941 /* this can be a prefix to a typename or an expression */
1942 /* we simply eat it now. */
1945 } while(token.type == T___extension__);
1949 if(is_typedef_symbol(token.v.symbol)) {
1950 type = parse_typename();
1952 expression = parse_expression();
1953 type = expression->base.type;
1958 type = parse_typename();
1962 expression = parse_expression();
1963 type = expression->base.type;
1967 rem_anchor_token(')');
1970 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1971 typeof_type->typeoft.expression = expression;
1972 typeof_type->typeoft.typeof_type = type;
1980 SPECIFIER_SIGNED = 1 << 0,
1981 SPECIFIER_UNSIGNED = 1 << 1,
1982 SPECIFIER_LONG = 1 << 2,
1983 SPECIFIER_INT = 1 << 3,
1984 SPECIFIER_DOUBLE = 1 << 4,
1985 SPECIFIER_CHAR = 1 << 5,
1986 SPECIFIER_SHORT = 1 << 6,
1987 SPECIFIER_LONG_LONG = 1 << 7,
1988 SPECIFIER_FLOAT = 1 << 8,
1989 SPECIFIER_BOOL = 1 << 9,
1990 SPECIFIER_VOID = 1 << 10,
1991 #ifdef PROVIDE_COMPLEX
1992 SPECIFIER_COMPLEX = 1 << 11,
1993 SPECIFIER_IMAGINARY = 1 << 12,
1997 static type_t *create_builtin_type(symbol_t *const symbol,
1998 type_t *const real_type)
2000 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2001 type->builtin.symbol = symbol;
2002 type->builtin.real_type = real_type;
2004 type_t *result = typehash_insert(type);
2005 if (type != result) {
2012 static type_t *get_typedef_type(symbol_t *symbol)
2014 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2015 if(declaration == NULL
2016 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2019 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2020 type->typedeft.declaration = declaration;
2026 * check for the allowed MS alignment values.
2028 static bool check_elignment_value(long long intvalue) {
2029 if(intvalue < 1 || intvalue > 8192) {
2030 errorf(HERE, "illegal alignment value");
2033 unsigned v = (unsigned)intvalue;
2034 for(unsigned i = 1; i <= 8192; i += i) {
2038 errorf(HERE, "alignment must be power of two");
2042 #define DET_MOD(name, tag) do { \
2043 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2044 *modifiers |= tag; \
2047 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2049 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2052 if(token.type == T_restrict) {
2054 DET_MOD(restrict, DM_RESTRICT);
2056 } else if(token.type != T_IDENTIFIER)
2058 symbol_t *symbol = token.v.symbol;
2059 if(symbol == sym_align) {
2062 if(token.type != T_INTEGER)
2064 if(check_elignment_value(token.v.intvalue)) {
2065 if(specifiers->alignment != 0)
2066 warningf(HERE, "align used more than once");
2067 specifiers->alignment = (unsigned char)token.v.intvalue;
2071 } else if(symbol == sym_allocate) {
2074 if(token.type != T_IDENTIFIER)
2076 (void)token.v.symbol;
2078 } else if(symbol == sym_dllimport) {
2080 DET_MOD(dllimport, DM_DLLIMPORT);
2081 } else if(symbol == sym_dllexport) {
2083 DET_MOD(dllexport, DM_DLLEXPORT);
2084 } else if(symbol == sym_thread) {
2086 DET_MOD(thread, DM_THREAD);
2087 } else if(symbol == sym_naked) {
2089 DET_MOD(naked, DM_NAKED);
2090 } else if(symbol == sym_noinline) {
2092 DET_MOD(noinline, DM_NOINLINE);
2093 } else if(symbol == sym_noreturn) {
2095 DET_MOD(noreturn, DM_NORETURN);
2096 } else if(symbol == sym_nothrow) {
2098 DET_MOD(nothrow, DM_NOTHROW);
2099 } else if(symbol == sym_novtable) {
2101 DET_MOD(novtable, DM_NOVTABLE);
2102 } else if(symbol == sym_property) {
2106 bool is_get = false;
2107 if(token.type != T_IDENTIFIER)
2109 if(token.v.symbol == sym_get) {
2111 } else if(token.v.symbol == sym_put) {
2113 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2118 if(token.type != T_IDENTIFIER)
2121 if(specifiers->get_property_sym != NULL) {
2122 errorf(HERE, "get property name already specified");
2124 specifiers->get_property_sym = token.v.symbol;
2127 if(specifiers->put_property_sym != NULL) {
2128 errorf(HERE, "put property name already specified");
2130 specifiers->put_property_sym = token.v.symbol;
2134 if(token.type == ',') {
2141 } else if(symbol == sym_selectany) {
2143 DET_MOD(selectany, DM_SELECTANY);
2144 } else if(symbol == sym_uuid) {
2147 if(token.type != T_STRING_LITERAL)
2151 } else if(symbol == sym_deprecated) {
2153 DET_MOD(deprecated, DM_DEPRECATED);
2154 if(token.type == '(') {
2156 if(token.type == T_STRING_LITERAL) {
2157 specifiers->deprecated_string = token.v.string.begin;
2160 errorf(HERE, "string literal expected");
2164 } else if(symbol == sym_noalias) {
2166 DET_MOD(noalias, DM_NOALIAS);
2168 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2170 if(token.type == '(')
2174 if (token.type == ',')
2181 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2183 type_t *type = NULL;
2184 unsigned type_qualifiers = 0;
2185 unsigned type_specifiers = 0;
2188 specifiers->source_position = token.source_position;
2191 switch(token.type) {
2194 #define MATCH_STORAGE_CLASS(token, class) \
2196 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2197 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2199 specifiers->declared_storage_class = class; \
2203 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2204 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2205 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2206 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2207 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2212 add_anchor_token(')');
2213 parse_microsoft_extended_decl_modifier(specifiers);
2214 rem_anchor_token(')');
2219 switch (specifiers->declared_storage_class) {
2220 case STORAGE_CLASS_NONE:
2221 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2224 case STORAGE_CLASS_EXTERN:
2225 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2228 case STORAGE_CLASS_STATIC:
2229 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2233 errorf(HERE, "multiple storage classes in declaration specifiers");
2239 /* type qualifiers */
2240 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2242 type_qualifiers |= qualifier; \
2246 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2247 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2248 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2250 case T___extension__:
2255 /* type specifiers */
2256 #define MATCH_SPECIFIER(token, specifier, name) \
2259 if(type_specifiers & specifier) { \
2260 errorf(HERE, "multiple " name " type specifiers given"); \
2262 type_specifiers |= specifier; \
2266 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2267 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2268 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2269 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2270 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2271 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2272 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2273 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2274 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2275 #ifdef PROVIDE_COMPLEX
2276 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2277 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2280 /* only in microsoft mode */
2281 specifiers->decl_modifiers |= DM_FORCEINLINE;
2285 specifiers->is_inline = true;
2290 if(type_specifiers & SPECIFIER_LONG_LONG) {
2291 errorf(HERE, "multiple type specifiers given");
2292 } else if(type_specifiers & SPECIFIER_LONG) {
2293 type_specifiers |= SPECIFIER_LONG_LONG;
2295 type_specifiers |= SPECIFIER_LONG;
2300 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2302 type->compound.declaration = parse_compound_type_specifier(true);
2306 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2308 type->compound.declaration = parse_compound_type_specifier(false);
2312 type = parse_enum_specifier();
2315 type = parse_typeof();
2317 case T___builtin_va_list:
2318 type = duplicate_type(type_valist);
2322 case T___attribute__:
2326 case T_IDENTIFIER: {
2327 /* only parse identifier if we haven't found a type yet */
2328 if(type != NULL || type_specifiers != 0)
2329 goto finish_specifiers;
2331 type_t *typedef_type = get_typedef_type(token.v.symbol);
2333 if(typedef_type == NULL)
2334 goto finish_specifiers;
2337 type = typedef_type;
2341 /* function specifier */
2343 goto finish_specifiers;
2350 atomic_type_kind_t atomic_type;
2352 /* match valid basic types */
2353 switch(type_specifiers) {
2354 case SPECIFIER_VOID:
2355 atomic_type = ATOMIC_TYPE_VOID;
2357 case SPECIFIER_CHAR:
2358 atomic_type = ATOMIC_TYPE_CHAR;
2360 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2361 atomic_type = ATOMIC_TYPE_SCHAR;
2363 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2364 atomic_type = ATOMIC_TYPE_UCHAR;
2366 case SPECIFIER_SHORT:
2367 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2368 case SPECIFIER_SHORT | SPECIFIER_INT:
2369 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2370 atomic_type = ATOMIC_TYPE_SHORT;
2372 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2373 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2374 atomic_type = ATOMIC_TYPE_USHORT;
2377 case SPECIFIER_SIGNED:
2378 case SPECIFIER_SIGNED | SPECIFIER_INT:
2379 atomic_type = ATOMIC_TYPE_INT;
2381 case SPECIFIER_UNSIGNED:
2382 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2383 atomic_type = ATOMIC_TYPE_UINT;
2385 case SPECIFIER_LONG:
2386 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2387 case SPECIFIER_LONG | SPECIFIER_INT:
2388 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2389 atomic_type = ATOMIC_TYPE_LONG;
2391 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2392 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2393 atomic_type = ATOMIC_TYPE_ULONG;
2395 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2396 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2397 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2398 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2400 atomic_type = ATOMIC_TYPE_LONGLONG;
2402 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2403 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2405 atomic_type = ATOMIC_TYPE_ULONGLONG;
2407 case SPECIFIER_FLOAT:
2408 atomic_type = ATOMIC_TYPE_FLOAT;
2410 case SPECIFIER_DOUBLE:
2411 atomic_type = ATOMIC_TYPE_DOUBLE;
2413 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2414 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2416 case SPECIFIER_BOOL:
2417 atomic_type = ATOMIC_TYPE_BOOL;
2419 #ifdef PROVIDE_COMPLEX
2420 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2421 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2423 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2424 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2426 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2427 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2429 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2430 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2432 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2433 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2435 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2436 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2440 /* invalid specifier combination, give an error message */
2441 if(type_specifiers == 0) {
2442 if (! strict_mode) {
2443 if (warning.implicit_int) {
2444 warningf(HERE, "no type specifiers in declaration, using 'int'");
2446 atomic_type = ATOMIC_TYPE_INT;
2449 errorf(HERE, "no type specifiers given in declaration");
2451 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2452 (type_specifiers & SPECIFIER_UNSIGNED)) {
2453 errorf(HERE, "signed and unsigned specifiers gives");
2454 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2455 errorf(HERE, "only integer types can be signed or unsigned");
2457 errorf(HERE, "multiple datatypes in declaration");
2459 atomic_type = ATOMIC_TYPE_INVALID;
2462 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2463 type->atomic.akind = atomic_type;
2466 if(type_specifiers != 0) {
2467 errorf(HERE, "multiple datatypes in declaration");
2471 type->base.qualifiers = type_qualifiers;
2473 type_t *result = typehash_insert(type);
2474 if(newtype && result != type) {
2478 specifiers->type = result;
2483 static type_qualifiers_t parse_type_qualifiers(void)
2485 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2488 switch(token.type) {
2489 /* type qualifiers */
2490 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2491 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2492 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2495 return type_qualifiers;
2500 static declaration_t *parse_identifier_list(void)
2502 declaration_t *declarations = NULL;
2503 declaration_t *last_declaration = NULL;
2505 declaration_t *const declaration = allocate_declaration_zero();
2506 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2507 declaration->source_position = token.source_position;
2508 declaration->symbol = token.v.symbol;
2511 if(last_declaration != NULL) {
2512 last_declaration->next = declaration;
2514 declarations = declaration;
2516 last_declaration = declaration;
2518 if(token.type != ',')
2521 } while(token.type == T_IDENTIFIER);
2523 return declarations;
2526 static void semantic_parameter(declaration_t *declaration)
2528 /* TODO: improve error messages */
2530 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2531 errorf(HERE, "typedef not allowed in parameter list");
2532 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2533 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2534 errorf(HERE, "parameter may only have none or register storage class");
2537 type_t *const orig_type = declaration->type;
2538 type_t * type = skip_typeref(orig_type);
2540 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2541 * into a pointer. § 6.7.5.3 (7) */
2542 if (is_type_array(type)) {
2543 type_t *const element_type = type->array.element_type;
2545 type = make_pointer_type(element_type, type->base.qualifiers);
2547 declaration->type = type;
2550 if(is_type_incomplete(type)) {
2551 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2552 orig_type, declaration->symbol);
2556 static declaration_t *parse_parameter(void)
2558 declaration_specifiers_t specifiers;
2559 memset(&specifiers, 0, sizeof(specifiers));
2561 parse_declaration_specifiers(&specifiers);
2563 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2565 semantic_parameter(declaration);
2570 static declaration_t *parse_parameters(function_type_t *type)
2572 if(token.type == T_IDENTIFIER) {
2573 symbol_t *symbol = token.v.symbol;
2574 if(!is_typedef_symbol(symbol)) {
2575 type->kr_style_parameters = true;
2576 return parse_identifier_list();
2580 if(token.type == ')') {
2581 type->unspecified_parameters = 1;
2584 if(token.type == T_void && look_ahead(1)->type == ')') {
2589 declaration_t *declarations = NULL;
2590 declaration_t *declaration;
2591 declaration_t *last_declaration = NULL;
2592 function_parameter_t *parameter;
2593 function_parameter_t *last_parameter = NULL;
2596 switch(token.type) {
2600 return declarations;
2603 case T___extension__:
2605 declaration = parse_parameter();
2607 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2608 memset(parameter, 0, sizeof(parameter[0]));
2609 parameter->type = declaration->type;
2611 if(last_parameter != NULL) {
2612 last_declaration->next = declaration;
2613 last_parameter->next = parameter;
2615 type->parameters = parameter;
2616 declarations = declaration;
2618 last_parameter = parameter;
2619 last_declaration = declaration;
2623 return declarations;
2625 if(token.type != ',')
2626 return declarations;
2636 } construct_type_kind_t;
2638 typedef struct construct_type_t construct_type_t;
2639 struct construct_type_t {
2640 construct_type_kind_t kind;
2641 construct_type_t *next;
2644 typedef struct parsed_pointer_t parsed_pointer_t;
2645 struct parsed_pointer_t {
2646 construct_type_t construct_type;
2647 type_qualifiers_t type_qualifiers;
2650 typedef struct construct_function_type_t construct_function_type_t;
2651 struct construct_function_type_t {
2652 construct_type_t construct_type;
2653 type_t *function_type;
2656 typedef struct parsed_array_t parsed_array_t;
2657 struct parsed_array_t {
2658 construct_type_t construct_type;
2659 type_qualifiers_t type_qualifiers;
2665 typedef struct construct_base_type_t construct_base_type_t;
2666 struct construct_base_type_t {
2667 construct_type_t construct_type;
2671 static construct_type_t *parse_pointer_declarator(void)
2675 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2676 memset(pointer, 0, sizeof(pointer[0]));
2677 pointer->construct_type.kind = CONSTRUCT_POINTER;
2678 pointer->type_qualifiers = parse_type_qualifiers();
2680 return (construct_type_t*) pointer;
2683 static construct_type_t *parse_array_declarator(void)
2686 add_anchor_token(']');
2688 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2689 memset(array, 0, sizeof(array[0]));
2690 array->construct_type.kind = CONSTRUCT_ARRAY;
2692 if(token.type == T_static) {
2693 array->is_static = true;
2697 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2698 if(type_qualifiers != 0) {
2699 if(token.type == T_static) {
2700 array->is_static = true;
2704 array->type_qualifiers = type_qualifiers;
2706 if(token.type == '*' && look_ahead(1)->type == ']') {
2707 array->is_variable = true;
2709 } else if(token.type != ']') {
2710 array->size = parse_assignment_expression();
2713 rem_anchor_token(']');
2716 return (construct_type_t*) array;
2721 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2724 add_anchor_token(')');
2727 if(declaration != NULL) {
2728 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2730 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2733 declaration_t *parameters = parse_parameters(&type->function);
2734 if(declaration != NULL) {
2735 declaration->scope.declarations = parameters;
2738 construct_function_type_t *construct_function_type =
2739 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2740 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2741 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2742 construct_function_type->function_type = type;
2744 rem_anchor_token(')');
2748 return (construct_type_t*) construct_function_type;
2751 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2752 bool may_be_abstract)
2754 /* construct a single linked list of construct_type_t's which describe
2755 * how to construct the final declarator type */
2756 construct_type_t *first = NULL;
2757 construct_type_t *last = NULL;
2760 while(token.type == '*') {
2761 construct_type_t *type = parse_pointer_declarator();
2772 /* TODO: find out if this is correct */
2775 construct_type_t *inner_types = NULL;
2777 switch(token.type) {
2779 if(declaration == NULL) {
2780 errorf(HERE, "no identifier expected in typename");
2782 declaration->symbol = token.v.symbol;
2783 declaration->source_position = token.source_position;
2789 add_anchor_token(')');
2790 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2791 rem_anchor_token(')');
2797 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2798 /* avoid a loop in the outermost scope, because eat_statement doesn't
2800 if(token.type == '}' && current_function == NULL) {
2808 construct_type_t *p = last;
2811 construct_type_t *type;
2812 switch(token.type) {
2814 type = parse_function_declarator(declaration);
2817 type = parse_array_declarator();
2820 goto declarator_finished;
2823 /* insert in the middle of the list (behind p) */
2825 type->next = p->next;
2836 declarator_finished:
2839 /* append inner_types at the end of the list, we don't to set last anymore
2840 * as it's not needed anymore */
2842 assert(first == NULL);
2843 first = inner_types;
2845 last->next = inner_types;
2853 static type_t *construct_declarator_type(construct_type_t *construct_list,
2856 construct_type_t *iter = construct_list;
2857 for( ; iter != NULL; iter = iter->next) {
2858 switch(iter->kind) {
2859 case CONSTRUCT_INVALID:
2860 internal_errorf(HERE, "invalid type construction found");
2861 case CONSTRUCT_FUNCTION: {
2862 construct_function_type_t *construct_function_type
2863 = (construct_function_type_t*) iter;
2865 type_t *function_type = construct_function_type->function_type;
2867 function_type->function.return_type = type;
2869 type_t *skipped_return_type = skip_typeref(type);
2870 if (is_type_function(skipped_return_type)) {
2871 errorf(HERE, "function returning function is not allowed");
2872 type = type_error_type;
2873 } else if (is_type_array(skipped_return_type)) {
2874 errorf(HERE, "function returning array is not allowed");
2875 type = type_error_type;
2877 type = function_type;
2882 case CONSTRUCT_POINTER: {
2883 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2884 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2885 pointer_type->pointer.points_to = type;
2886 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2888 type = pointer_type;
2892 case CONSTRUCT_ARRAY: {
2893 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2894 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2896 expression_t *size_expression = parsed_array->size;
2897 if(size_expression != NULL) {
2899 = create_implicit_cast(size_expression, type_size_t);
2902 array_type->base.qualifiers = parsed_array->type_qualifiers;
2903 array_type->array.element_type = type;
2904 array_type->array.is_static = parsed_array->is_static;
2905 array_type->array.is_variable = parsed_array->is_variable;
2906 array_type->array.size_expression = size_expression;
2908 if(size_expression != NULL) {
2909 if(is_constant_expression(size_expression)) {
2910 array_type->array.size_constant = true;
2911 array_type->array.size
2912 = fold_constant(size_expression);
2914 array_type->array.is_vla = true;
2918 type_t *skipped_type = skip_typeref(type);
2919 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2920 errorf(HERE, "array of void is not allowed");
2921 type = type_error_type;
2929 type_t *hashed_type = typehash_insert(type);
2930 if(hashed_type != type) {
2931 /* the function type was constructed earlier freeing it here will
2932 * destroy other types... */
2933 if(iter->kind != CONSTRUCT_FUNCTION) {
2943 static declaration_t *parse_declarator(
2944 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2946 declaration_t *const declaration = allocate_declaration_zero();
2947 declaration->declared_storage_class = specifiers->declared_storage_class;
2948 declaration->modifiers = specifiers->decl_modifiers;
2949 declaration->deprecated_string = specifiers->deprecated_string;
2950 declaration->get_property_sym = specifiers->get_property_sym;
2951 declaration->put_property_sym = specifiers->put_property_sym;
2952 declaration->is_inline = specifiers->is_inline;
2954 declaration->storage_class = specifiers->declared_storage_class;
2955 if(declaration->storage_class == STORAGE_CLASS_NONE
2956 && scope != global_scope) {
2957 declaration->storage_class = STORAGE_CLASS_AUTO;
2960 if(specifiers->alignment != 0) {
2961 /* TODO: add checks here */
2962 declaration->alignment = specifiers->alignment;
2965 construct_type_t *construct_type
2966 = parse_inner_declarator(declaration, may_be_abstract);
2967 type_t *const type = specifiers->type;
2968 declaration->type = construct_declarator_type(construct_type, type);
2970 if(construct_type != NULL) {
2971 obstack_free(&temp_obst, construct_type);
2977 static type_t *parse_abstract_declarator(type_t *base_type)
2979 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2981 type_t *result = construct_declarator_type(construct_type, base_type);
2982 if(construct_type != NULL) {
2983 obstack_free(&temp_obst, construct_type);
2989 static declaration_t *append_declaration(declaration_t* const declaration)
2991 if (last_declaration != NULL) {
2992 last_declaration->next = declaration;
2994 scope->declarations = declaration;
2996 last_declaration = declaration;
3001 * Check if the declaration of main is suspicious. main should be a
3002 * function with external linkage, returning int, taking either zero
3003 * arguments, two, or three arguments of appropriate types, ie.
3005 * int main([ int argc, char **argv [, char **env ] ]).
3007 * @param decl the declaration to check
3008 * @param type the function type of the declaration
3010 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3012 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3013 warningf(decl->source_position, "'main' is normally a non-static function");
3015 if (skip_typeref(func_type->return_type) != type_int) {
3016 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3018 const function_parameter_t *parm = func_type->parameters;
3020 type_t *const first_type = parm->type;
3021 if (!types_compatible(skip_typeref(first_type), type_int)) {
3022 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3026 type_t *const second_type = parm->type;
3027 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3028 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3032 type_t *const third_type = parm->type;
3033 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3034 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3038 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3042 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3048 * Check if a symbol is the equal to "main".
3050 static bool is_sym_main(const symbol_t *const sym)
3052 return strcmp(sym->string, "main") == 0;
3055 static declaration_t *internal_record_declaration(
3056 declaration_t *const declaration,
3057 const bool is_function_definition)
3059 const symbol_t *const symbol = declaration->symbol;
3060 const namespace_t namespc = (namespace_t)declaration->namespc;
3062 type_t *const orig_type = declaration->type;
3063 type_t *const type = skip_typeref(orig_type);
3064 if (is_type_function(type) &&
3065 type->function.unspecified_parameters &&
3066 warning.strict_prototypes) {
3067 warningf(declaration->source_position,
3068 "function declaration '%#T' is not a prototype",
3069 orig_type, declaration->symbol);
3072 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3073 check_type_of_main(declaration, &type->function);
3076 assert(declaration->symbol != NULL);
3077 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3079 assert(declaration != previous_declaration);
3080 if (previous_declaration != NULL) {
3081 if (previous_declaration->parent_scope == scope) {
3082 /* can happen for K&R style declarations */
3083 if(previous_declaration->type == NULL) {
3084 previous_declaration->type = declaration->type;
3087 const type_t *prev_type = skip_typeref(previous_declaration->type);
3088 if (!types_compatible(type, prev_type)) {
3089 errorf(declaration->source_position,
3090 "declaration '%#T' is incompatible with "
3091 "previous declaration '%#T'",
3092 orig_type, symbol, previous_declaration->type, symbol);
3093 errorf(previous_declaration->source_position,
3094 "previous declaration of '%Y' was here", symbol);
3096 unsigned old_storage_class = previous_declaration->storage_class;
3097 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3098 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3099 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3100 return previous_declaration;
3103 unsigned new_storage_class = declaration->storage_class;
3105 if(is_type_incomplete(prev_type)) {
3106 previous_declaration->type = type;
3110 /* pretend no storage class means extern for function
3111 * declarations (except if the previous declaration is neither
3112 * none nor extern) */
3113 if (is_type_function(type)) {
3114 switch (old_storage_class) {
3115 case STORAGE_CLASS_NONE:
3116 old_storage_class = STORAGE_CLASS_EXTERN;
3118 case STORAGE_CLASS_EXTERN:
3119 if (is_function_definition) {
3120 if (warning.missing_prototypes &&
3121 prev_type->function.unspecified_parameters &&
3122 !is_sym_main(symbol)) {
3123 warningf(declaration->source_position,
3124 "no previous prototype for '%#T'",
3127 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3128 new_storage_class = STORAGE_CLASS_EXTERN;
3136 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3137 new_storage_class == STORAGE_CLASS_EXTERN) {
3138 warn_redundant_declaration:
3139 if (warning.redundant_decls) {
3140 warningf(declaration->source_position,
3141 "redundant declaration for '%Y'", symbol);
3142 warningf(previous_declaration->source_position,
3143 "previous declaration of '%Y' was here",
3146 } else if (current_function == NULL) {
3147 if (old_storage_class != STORAGE_CLASS_STATIC &&
3148 new_storage_class == STORAGE_CLASS_STATIC) {
3149 errorf(declaration->source_position,
3150 "static declaration of '%Y' follows non-static declaration",
3152 errorf(previous_declaration->source_position,
3153 "previous declaration of '%Y' was here", symbol);
3155 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3156 goto warn_redundant_declaration;
3158 if (new_storage_class == STORAGE_CLASS_NONE) {
3159 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3160 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3164 if (old_storage_class == new_storage_class) {
3165 errorf(declaration->source_position,
3166 "redeclaration of '%Y'", symbol);
3168 errorf(declaration->source_position,
3169 "redeclaration of '%Y' with different linkage",
3172 errorf(previous_declaration->source_position,
3173 "previous declaration of '%Y' was here", symbol);
3176 return previous_declaration;
3178 } else if (is_function_definition) {
3179 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3180 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3181 warningf(declaration->source_position,
3182 "no previous prototype for '%#T'", orig_type, symbol);
3183 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3184 warningf(declaration->source_position,
3185 "no previous declaration for '%#T'", orig_type,
3189 } else if (warning.missing_declarations &&
3190 scope == global_scope &&
3191 !is_type_function(type) && (
3192 declaration->storage_class == STORAGE_CLASS_NONE ||
3193 declaration->storage_class == STORAGE_CLASS_THREAD
3195 warningf(declaration->source_position,
3196 "no previous declaration for '%#T'", orig_type, symbol);
3199 assert(declaration->parent_scope == NULL);
3200 assert(scope != NULL);
3202 declaration->parent_scope = scope;
3204 environment_push(declaration);
3205 return append_declaration(declaration);
3208 static declaration_t *record_declaration(declaration_t *declaration)
3210 return internal_record_declaration(declaration, false);
3213 static declaration_t *record_function_definition(declaration_t *declaration)
3215 return internal_record_declaration(declaration, true);
3218 static void parser_error_multiple_definition(declaration_t *declaration,
3219 const source_position_t source_position)
3221 errorf(source_position, "multiple definition of symbol '%Y'",
3222 declaration->symbol);
3223 errorf(declaration->source_position,
3224 "this is the location of the previous definition.");
3227 static bool is_declaration_specifier(const token_t *token,
3228 bool only_type_specifiers)
3230 switch(token->type) {
3234 return is_typedef_symbol(token->v.symbol);
3236 case T___extension__:
3239 return !only_type_specifiers;
3246 static void parse_init_declarator_rest(declaration_t *declaration)
3250 type_t *orig_type = declaration->type;
3251 type_t *type = skip_typeref(orig_type);
3253 if(declaration->init.initializer != NULL) {
3254 parser_error_multiple_definition(declaration, token.source_position);
3257 bool must_be_constant = false;
3258 if(declaration->storage_class == STORAGE_CLASS_STATIC
3259 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3260 || declaration->parent_scope == global_scope) {
3261 must_be_constant = true;
3264 parse_initializer_env_t env;
3265 env.type = orig_type;
3266 env.must_be_constant = must_be_constant;
3267 env.declaration = declaration;
3269 initializer_t *initializer = parse_initializer(&env);
3271 if(env.type != orig_type) {
3272 orig_type = env.type;
3273 type = skip_typeref(orig_type);
3274 declaration->type = env.type;
3277 if(is_type_function(type)) {
3278 errorf(declaration->source_position,
3279 "initializers not allowed for function types at declator '%Y' (type '%T')",
3280 declaration->symbol, orig_type);
3282 declaration->init.initializer = initializer;
3286 /* parse rest of a declaration without any declarator */
3287 static void parse_anonymous_declaration_rest(
3288 const declaration_specifiers_t *specifiers,
3289 parsed_declaration_func finished_declaration)
3293 declaration_t *const declaration = allocate_declaration_zero();
3294 declaration->type = specifiers->type;
3295 declaration->declared_storage_class = specifiers->declared_storage_class;
3296 declaration->source_position = specifiers->source_position;
3297 declaration->modifiers = specifiers->decl_modifiers;
3299 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3300 warningf(declaration->source_position, "useless storage class in empty declaration");
3302 declaration->storage_class = STORAGE_CLASS_NONE;
3304 type_t *type = declaration->type;
3305 switch (type->kind) {
3306 case TYPE_COMPOUND_STRUCT:
3307 case TYPE_COMPOUND_UNION: {
3308 if (type->compound.declaration->symbol == NULL) {
3309 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3318 warningf(declaration->source_position, "empty declaration");
3322 finished_declaration(declaration);
3325 static void parse_declaration_rest(declaration_t *ndeclaration,
3326 const declaration_specifiers_t *specifiers,
3327 parsed_declaration_func finished_declaration)
3329 add_anchor_token(';');
3330 add_anchor_token('=');
3331 add_anchor_token(',');
3333 declaration_t *declaration = finished_declaration(ndeclaration);
3335 type_t *orig_type = declaration->type;
3336 type_t *type = skip_typeref(orig_type);
3338 if (type->kind != TYPE_FUNCTION &&
3339 declaration->is_inline &&
3340 is_type_valid(type)) {
3341 warningf(declaration->source_position,
3342 "variable '%Y' declared 'inline'\n", declaration->symbol);
3345 if(token.type == '=') {
3346 parse_init_declarator_rest(declaration);
3349 if(token.type != ',')
3353 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3358 rem_anchor_token(';');
3359 rem_anchor_token('=');
3360 rem_anchor_token(',');
3363 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3365 symbol_t *symbol = declaration->symbol;
3366 if(symbol == NULL) {
3367 errorf(HERE, "anonymous declaration not valid as function parameter");
3370 namespace_t namespc = (namespace_t) declaration->namespc;
3371 if(namespc != NAMESPACE_NORMAL) {
3372 return record_declaration(declaration);
3375 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3376 if(previous_declaration == NULL ||
3377 previous_declaration->parent_scope != scope) {
3378 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3383 if(previous_declaration->type == NULL) {
3384 previous_declaration->type = declaration->type;
3385 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3386 previous_declaration->storage_class = declaration->storage_class;
3387 previous_declaration->parent_scope = scope;
3388 return previous_declaration;
3390 return record_declaration(declaration);
3394 static void parse_declaration(parsed_declaration_func finished_declaration)
3396 declaration_specifiers_t specifiers;
3397 memset(&specifiers, 0, sizeof(specifiers));
3398 parse_declaration_specifiers(&specifiers);
3400 if(token.type == ';') {
3401 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3403 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3404 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3408 static void parse_kr_declaration_list(declaration_t *declaration)
3410 type_t *type = skip_typeref(declaration->type);
3411 if(!is_type_function(type))
3414 if(!type->function.kr_style_parameters)
3417 /* push function parameters */
3418 int top = environment_top();
3419 scope_t *last_scope = scope;
3420 set_scope(&declaration->scope);
3422 declaration_t *parameter = declaration->scope.declarations;
3423 for( ; parameter != NULL; parameter = parameter->next) {
3424 assert(parameter->parent_scope == NULL);
3425 parameter->parent_scope = scope;
3426 environment_push(parameter);
3429 /* parse declaration list */
3430 while(is_declaration_specifier(&token, false)) {
3431 parse_declaration(finished_kr_declaration);
3434 /* pop function parameters */
3435 assert(scope == &declaration->scope);
3436 set_scope(last_scope);
3437 environment_pop_to(top);
3439 /* update function type */
3440 type_t *new_type = duplicate_type(type);
3441 new_type->function.kr_style_parameters = false;
3443 function_parameter_t *parameters = NULL;
3444 function_parameter_t *last_parameter = NULL;
3446 declaration_t *parameter_declaration = declaration->scope.declarations;
3447 for( ; parameter_declaration != NULL;
3448 parameter_declaration = parameter_declaration->next) {
3449 type_t *parameter_type = parameter_declaration->type;
3450 if(parameter_type == NULL) {
3452 errorf(HERE, "no type specified for function parameter '%Y'",
3453 parameter_declaration->symbol);
3455 if (warning.implicit_int) {
3456 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3457 parameter_declaration->symbol);
3459 parameter_type = type_int;
3460 parameter_declaration->type = parameter_type;
3464 semantic_parameter(parameter_declaration);
3465 parameter_type = parameter_declaration->type;
3467 function_parameter_t *function_parameter
3468 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3469 memset(function_parameter, 0, sizeof(function_parameter[0]));
3471 function_parameter->type = parameter_type;
3472 if(last_parameter != NULL) {
3473 last_parameter->next = function_parameter;
3475 parameters = function_parameter;
3477 last_parameter = function_parameter;
3479 new_type->function.parameters = parameters;
3481 type = typehash_insert(new_type);
3482 if(type != new_type) {
3483 obstack_free(type_obst, new_type);
3486 declaration->type = type;
3489 static bool first_err = true;
3492 * When called with first_err set, prints the name of the current function,
3495 static void print_in_function(void) {
3498 diagnosticf("%s: In function '%Y':\n",
3499 current_function->source_position.input_name,
3500 current_function->symbol);
3505 * Check if all labels are defined in the current function.
3506 * Check if all labels are used in the current function.
3508 static void check_labels(void)
3510 for (const goto_statement_t *goto_statement = goto_first;
3511 goto_statement != NULL;
3512 goto_statement = goto_statement->next) {
3513 declaration_t *label = goto_statement->label;
3516 if (label->source_position.input_name == NULL) {
3517 print_in_function();
3518 errorf(goto_statement->base.source_position,
3519 "label '%Y' used but not defined", label->symbol);
3522 goto_first = goto_last = NULL;
3524 if (warning.unused_label) {
3525 for (const label_statement_t *label_statement = label_first;
3526 label_statement != NULL;
3527 label_statement = label_statement->next) {
3528 const declaration_t *label = label_statement->label;
3530 if (! label->used) {
3531 print_in_function();
3532 warningf(label_statement->base.source_position,
3533 "label '%Y' defined but not used", label->symbol);
3537 label_first = label_last = NULL;
3541 * Check declarations of current_function for unused entities.
3543 static void check_declarations(void)
3545 if (warning.unused_parameter) {
3546 const scope_t *scope = ¤t_function->scope;
3548 const declaration_t *parameter = scope->declarations;
3549 for (; parameter != NULL; parameter = parameter->next) {
3550 if (! parameter->used) {
3551 print_in_function();
3552 warningf(parameter->source_position,
3553 "unused parameter '%Y'", parameter->symbol);
3557 if (warning.unused_variable) {
3561 static void parse_external_declaration(void)
3563 /* function-definitions and declarations both start with declaration
3565 declaration_specifiers_t specifiers;
3566 memset(&specifiers, 0, sizeof(specifiers));
3568 add_anchor_token(';');
3569 parse_declaration_specifiers(&specifiers);
3570 rem_anchor_token(';');
3572 /* must be a declaration */
3573 if(token.type == ';') {
3574 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3578 add_anchor_token(',');
3579 add_anchor_token('=');
3580 rem_anchor_token(';');
3582 /* declarator is common to both function-definitions and declarations */
3583 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3585 rem_anchor_token(',');
3586 rem_anchor_token('=');
3587 rem_anchor_token(';');
3589 /* must be a declaration */
3590 if(token.type == ',' || token.type == '=' || token.type == ';') {
3591 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3595 /* must be a function definition */
3596 parse_kr_declaration_list(ndeclaration);
3598 if(token.type != '{') {
3599 parse_error_expected("while parsing function definition", '{', 0);
3600 eat_until_matching_token(';');
3604 type_t *type = ndeclaration->type;
3606 /* note that we don't skip typerefs: the standard doesn't allow them here
3607 * (so we can't use is_type_function here) */
3608 if(type->kind != TYPE_FUNCTION) {
3609 if (is_type_valid(type)) {
3610 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3611 type, ndeclaration->symbol);
3617 /* § 6.7.5.3 (14) a function definition with () means no
3618 * parameters (and not unspecified parameters) */
3619 if(type->function.unspecified_parameters) {
3620 type_t *duplicate = duplicate_type(type);
3621 duplicate->function.unspecified_parameters = false;
3623 type = typehash_insert(duplicate);
3624 if(type != duplicate) {
3625 obstack_free(type_obst, duplicate);
3627 ndeclaration->type = type;
3630 declaration_t *const declaration = record_function_definition(ndeclaration);
3631 if(ndeclaration != declaration) {
3632 declaration->scope = ndeclaration->scope;
3634 type = skip_typeref(declaration->type);
3636 /* push function parameters and switch scope */
3637 int top = environment_top();
3638 scope_t *last_scope = scope;
3639 set_scope(&declaration->scope);
3641 declaration_t *parameter = declaration->scope.declarations;
3642 for( ; parameter != NULL; parameter = parameter->next) {
3643 if(parameter->parent_scope == &ndeclaration->scope) {
3644 parameter->parent_scope = scope;
3646 assert(parameter->parent_scope == NULL
3647 || parameter->parent_scope == scope);
3648 parameter->parent_scope = scope;
3649 environment_push(parameter);
3652 if(declaration->init.statement != NULL) {
3653 parser_error_multiple_definition(declaration, token.source_position);
3655 goto end_of_parse_external_declaration;
3657 /* parse function body */
3658 int label_stack_top = label_top();
3659 declaration_t *old_current_function = current_function;
3660 current_function = declaration;
3662 declaration->init.statement = parse_compound_statement();
3665 check_declarations();
3667 assert(current_function == declaration);
3668 current_function = old_current_function;
3669 label_pop_to(label_stack_top);
3672 end_of_parse_external_declaration:
3673 assert(scope == &declaration->scope);
3674 set_scope(last_scope);
3675 environment_pop_to(top);
3678 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3679 source_position_t source_position)
3681 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3682 type->bitfield.base = base;
3683 type->bitfield.size = size;
3688 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3691 declaration_t *iter = compound_declaration->scope.declarations;
3692 for( ; iter != NULL; iter = iter->next) {
3693 if(iter->namespc != NAMESPACE_NORMAL)
3696 if(iter->symbol == NULL) {
3697 type_t *type = skip_typeref(iter->type);
3698 if(is_type_compound(type)) {
3699 declaration_t *result
3700 = find_compound_entry(type->compound.declaration, symbol);
3707 if(iter->symbol == symbol) {
3715 static void parse_compound_declarators(declaration_t *struct_declaration,
3716 const declaration_specifiers_t *specifiers)
3718 declaration_t *last_declaration = struct_declaration->scope.declarations;
3719 if(last_declaration != NULL) {
3720 while(last_declaration->next != NULL) {
3721 last_declaration = last_declaration->next;
3726 declaration_t *declaration;
3728 if(token.type == ':') {
3729 source_position_t source_position = HERE;
3732 type_t *base_type = specifiers->type;
3733 expression_t *size = parse_constant_expression();
3735 if(!is_type_integer(skip_typeref(base_type))) {
3736 errorf(HERE, "bitfield base type '%T' is not an integer type",
3740 type_t *type = make_bitfield_type(base_type, size, source_position);
3742 declaration = allocate_declaration_zero();
3743 declaration->namespc = NAMESPACE_NORMAL;
3744 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3745 declaration->storage_class = STORAGE_CLASS_NONE;
3746 declaration->source_position = source_position;
3747 declaration->modifiers = specifiers->decl_modifiers;
3748 declaration->type = type;
3750 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3752 type_t *orig_type = declaration->type;
3753 type_t *type = skip_typeref(orig_type);
3755 if(token.type == ':') {
3756 source_position_t source_position = HERE;
3758 expression_t *size = parse_constant_expression();
3760 if(!is_type_integer(type)) {
3761 errorf(HERE, "bitfield base type '%T' is not an "
3762 "integer type", orig_type);
3765 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3766 declaration->type = bitfield_type;
3768 /* TODO we ignore arrays for now... what is missing is a check
3769 * that they're at the end of the struct */
3770 if(is_type_incomplete(type) && !is_type_array(type)) {
3772 "compound member '%Y' has incomplete type '%T'",
3773 declaration->symbol, orig_type);
3774 } else if(is_type_function(type)) {
3775 errorf(HERE, "compound member '%Y' must not have function "
3776 "type '%T'", declaration->symbol, orig_type);
3781 /* make sure we don't define a symbol multiple times */
3782 symbol_t *symbol = declaration->symbol;
3783 if(symbol != NULL) {
3784 declaration_t *prev_decl
3785 = find_compound_entry(struct_declaration, symbol);
3787 if(prev_decl != NULL) {
3788 assert(prev_decl->symbol == symbol);
3789 errorf(declaration->source_position,
3790 "multiple declarations of symbol '%Y'", symbol);
3791 errorf(prev_decl->source_position,
3792 "previous declaration of '%Y' was here", symbol);
3796 /* append declaration */
3797 if(last_declaration != NULL) {
3798 last_declaration->next = declaration;
3800 struct_declaration->scope.declarations = declaration;
3802 last_declaration = declaration;
3804 if(token.type != ',')
3814 static void parse_compound_type_entries(declaration_t *compound_declaration)
3817 add_anchor_token('}');
3819 while(token.type != '}' && token.type != T_EOF) {
3820 declaration_specifiers_t specifiers;
3821 memset(&specifiers, 0, sizeof(specifiers));
3822 parse_declaration_specifiers(&specifiers);
3824 parse_compound_declarators(compound_declaration, &specifiers);
3826 rem_anchor_token('}');
3828 if(token.type == T_EOF) {
3829 errorf(HERE, "EOF while parsing struct");
3834 static type_t *parse_typename(void)
3836 declaration_specifiers_t specifiers;
3837 memset(&specifiers, 0, sizeof(specifiers));
3838 parse_declaration_specifiers(&specifiers);
3839 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3840 /* TODO: improve error message, user does probably not know what a
3841 * storage class is...
3843 errorf(HERE, "typename may not have a storage class");
3846 type_t *result = parse_abstract_declarator(specifiers.type);
3854 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3855 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3856 expression_t *left);
3858 typedef struct expression_parser_function_t expression_parser_function_t;
3859 struct expression_parser_function_t {
3860 unsigned precedence;
3861 parse_expression_function parser;
3862 unsigned infix_precedence;
3863 parse_expression_infix_function infix_parser;
3866 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3869 * Creates a new invalid expression.
3871 static expression_t *create_invalid_expression(void)
3873 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3874 expression->base.source_position = token.source_position;
3879 * Prints an error message if an expression was expected but not read
3881 static expression_t *expected_expression_error(void)
3883 /* skip the error message if the error token was read */
3884 if (token.type != T_ERROR) {
3885 errorf(HERE, "expected expression, got token '%K'", &token);
3889 return create_invalid_expression();
3893 * Parse a string constant.
3895 static expression_t *parse_string_const(void)
3898 if (token.type == T_STRING_LITERAL) {
3899 string_t res = token.v.string;
3901 while (token.type == T_STRING_LITERAL) {
3902 res = concat_strings(&res, &token.v.string);
3905 if (token.type != T_WIDE_STRING_LITERAL) {
3906 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3907 /* note: that we use type_char_ptr here, which is already the
3908 * automatic converted type. revert_automatic_type_conversion
3909 * will construct the array type */
3910 cnst->base.type = type_char_ptr;
3911 cnst->string.value = res;
3915 wres = concat_string_wide_string(&res, &token.v.wide_string);
3917 wres = token.v.wide_string;
3922 switch (token.type) {
3923 case T_WIDE_STRING_LITERAL:
3924 wres = concat_wide_strings(&wres, &token.v.wide_string);
3927 case T_STRING_LITERAL:
3928 wres = concat_wide_string_string(&wres, &token.v.string);
3932 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3933 cnst->base.type = type_wchar_t_ptr;
3934 cnst->wide_string.value = wres;
3943 * Parse an integer constant.
3945 static expression_t *parse_int_const(void)
3947 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3948 cnst->base.source_position = HERE;
3949 cnst->base.type = token.datatype;
3950 cnst->conste.v.int_value = token.v.intvalue;
3958 * Parse a character constant.
3960 static expression_t *parse_character_constant(void)
3962 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3964 cnst->base.source_position = HERE;
3965 cnst->base.type = token.datatype;
3966 cnst->conste.v.character = token.v.string;
3968 if (cnst->conste.v.character.size != 1) {
3969 if (warning.multichar && (c_mode & _GNUC)) {
3971 warningf(HERE, "multi-character character constant");
3973 errorf(HERE, "more than 1 characters in character constant");
3982 * Parse a wide character constant.
3984 static expression_t *parse_wide_character_constant(void)
3986 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3988 cnst->base.source_position = HERE;
3989 cnst->base.type = token.datatype;
3990 cnst->conste.v.wide_character = token.v.wide_string;
3992 if (cnst->conste.v.wide_character.size != 1) {
3993 if (warning.multichar && (c_mode & _GNUC)) {
3995 warningf(HERE, "multi-character character constant");
3997 errorf(HERE, "more than 1 characters in character constant");
4006 * Parse a float constant.
4008 static expression_t *parse_float_const(void)
4010 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4011 cnst->base.type = token.datatype;
4012 cnst->conste.v.float_value = token.v.floatvalue;
4019 static declaration_t *create_implicit_function(symbol_t *symbol,
4020 const source_position_t source_position)
4022 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4023 ntype->function.return_type = type_int;
4024 ntype->function.unspecified_parameters = true;
4026 type_t *type = typehash_insert(ntype);
4031 declaration_t *const declaration = allocate_declaration_zero();
4032 declaration->storage_class = STORAGE_CLASS_EXTERN;
4033 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4034 declaration->type = type;
4035 declaration->symbol = symbol;
4036 declaration->source_position = source_position;
4037 declaration->parent_scope = global_scope;
4039 scope_t *old_scope = scope;
4040 set_scope(global_scope);
4042 environment_push(declaration);
4043 /* prepends the declaration to the global declarations list */
4044 declaration->next = scope->declarations;
4045 scope->declarations = declaration;
4047 assert(scope == global_scope);
4048 set_scope(old_scope);
4054 * Creates a return_type (func)(argument_type) function type if not
4057 * @param return_type the return type
4058 * @param argument_type the argument type
4060 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4062 function_parameter_t *parameter
4063 = obstack_alloc(type_obst, sizeof(parameter[0]));
4064 memset(parameter, 0, sizeof(parameter[0]));
4065 parameter->type = argument_type;
4067 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4068 type->function.return_type = return_type;
4069 type->function.parameters = parameter;
4071 type_t *result = typehash_insert(type);
4072 if(result != type) {
4080 * Creates a function type for some function like builtins.
4082 * @param symbol the symbol describing the builtin
4084 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4086 switch(symbol->ID) {
4087 case T___builtin_alloca:
4088 return make_function_1_type(type_void_ptr, type_size_t);
4089 case T___builtin_nan:
4090 return make_function_1_type(type_double, type_char_ptr);
4091 case T___builtin_nanf:
4092 return make_function_1_type(type_float, type_char_ptr);
4093 case T___builtin_nand:
4094 return make_function_1_type(type_long_double, type_char_ptr);
4095 case T___builtin_va_end:
4096 return make_function_1_type(type_void, type_valist);
4098 internal_errorf(HERE, "not implemented builtin symbol found");
4103 * Performs automatic type cast as described in § 6.3.2.1.
4105 * @param orig_type the original type
4107 static type_t *automatic_type_conversion(type_t *orig_type)
4109 type_t *type = skip_typeref(orig_type);
4110 if(is_type_array(type)) {
4111 array_type_t *array_type = &type->array;
4112 type_t *element_type = array_type->element_type;
4113 unsigned qualifiers = array_type->type.qualifiers;
4115 return make_pointer_type(element_type, qualifiers);
4118 if(is_type_function(type)) {
4119 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4126 * reverts the automatic casts of array to pointer types and function
4127 * to function-pointer types as defined § 6.3.2.1
4129 type_t *revert_automatic_type_conversion(const expression_t *expression)
4131 switch (expression->kind) {
4132 case EXPR_REFERENCE: return expression->reference.declaration->type;
4133 case EXPR_SELECT: return expression->select.compound_entry->type;
4135 case EXPR_UNARY_DEREFERENCE: {
4136 const expression_t *const value = expression->unary.value;
4137 type_t *const type = skip_typeref(value->base.type);
4138 assert(is_type_pointer(type));
4139 return type->pointer.points_to;
4142 case EXPR_BUILTIN_SYMBOL:
4143 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4145 case EXPR_ARRAY_ACCESS: {
4146 const expression_t *array_ref = expression->array_access.array_ref;
4147 type_t *type_left = skip_typeref(array_ref->base.type);
4148 if (!is_type_valid(type_left))
4150 assert(is_type_pointer(type_left));
4151 return type_left->pointer.points_to;
4154 case EXPR_STRING_LITERAL: {
4155 size_t size = expression->string.value.size;
4156 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4159 case EXPR_WIDE_STRING_LITERAL: {
4160 size_t size = expression->wide_string.value.size;
4161 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4164 case EXPR_COMPOUND_LITERAL:
4165 return expression->compound_literal.type;
4170 return expression->base.type;
4173 static expression_t *parse_reference(void)
4175 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4177 reference_expression_t *ref = &expression->reference;
4178 ref->symbol = token.v.symbol;
4180 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4182 source_position_t source_position = token.source_position;
4185 if(declaration == NULL) {
4186 if (! strict_mode && token.type == '(') {
4187 /* an implicitly defined function */
4188 if (warning.implicit_function_declaration) {
4189 warningf(HERE, "implicit declaration of function '%Y'",
4193 declaration = create_implicit_function(ref->symbol,
4196 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4197 return create_invalid_expression();
4201 type_t *type = declaration->type;
4203 /* we always do the auto-type conversions; the & and sizeof parser contains
4204 * code to revert this! */
4205 type = automatic_type_conversion(type);
4207 ref->declaration = declaration;
4208 ref->base.type = type;
4210 /* this declaration is used */
4211 declaration->used = true;
4216 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4220 /* TODO check if explicit cast is allowed and issue warnings/errors */
4223 static expression_t *parse_compound_literal(type_t *type)
4225 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4227 parse_initializer_env_t env;
4229 env.declaration = NULL;
4230 env.must_be_constant = false;
4231 initializer_t *initializer = parse_initializer(&env);
4234 expression->compound_literal.initializer = initializer;
4235 expression->compound_literal.type = type;
4236 expression->base.type = automatic_type_conversion(type);
4242 * Parse a cast expression.
4244 static expression_t *parse_cast(void)
4246 source_position_t source_position = token.source_position;
4248 type_t *type = parse_typename();
4250 /* matching add_anchor_token() is at call site */
4251 rem_anchor_token(')');
4254 if(token.type == '{') {
4255 return parse_compound_literal(type);
4258 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4259 cast->base.source_position = source_position;
4261 expression_t *value = parse_sub_expression(20);
4263 check_cast_allowed(value, type);
4265 cast->base.type = type;
4266 cast->unary.value = value;
4270 return create_invalid_expression();
4274 * Parse a statement expression.
4276 static expression_t *parse_statement_expression(void)
4278 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4280 statement_t *statement = parse_compound_statement();
4281 expression->statement.statement = statement;
4282 expression->base.source_position = statement->base.source_position;
4284 /* find last statement and use its type */
4285 type_t *type = type_void;
4286 const statement_t *stmt = statement->compound.statements;
4288 while (stmt->base.next != NULL)
4289 stmt = stmt->base.next;
4291 if (stmt->kind == STATEMENT_EXPRESSION) {
4292 type = stmt->expression.expression->base.type;
4295 warningf(expression->base.source_position, "empty statement expression ({})");
4297 expression->base.type = type;
4303 return create_invalid_expression();
4307 * Parse a braced expression.
4309 static expression_t *parse_brace_expression(void)
4312 add_anchor_token(')');
4314 switch(token.type) {
4316 /* gcc extension: a statement expression */
4317 return parse_statement_expression();
4321 return parse_cast();
4323 if(is_typedef_symbol(token.v.symbol)) {
4324 return parse_cast();
4328 expression_t *result = parse_expression();
4329 rem_anchor_token(')');
4334 return create_invalid_expression();
4337 static expression_t *parse_function_keyword(void)
4342 if (current_function == NULL) {
4343 errorf(HERE, "'__func__' used outside of a function");
4346 expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4347 expression->base.type = type_char_ptr;
4352 static expression_t *parse_pretty_function_keyword(void)
4354 eat(T___PRETTY_FUNCTION__);
4357 if (current_function == NULL) {
4358 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4361 expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4362 expression->base.type = type_char_ptr;
4367 static designator_t *parse_designator(void)
4369 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4370 result->source_position = HERE;
4372 if(token.type != T_IDENTIFIER) {
4373 parse_error_expected("while parsing member designator",
4377 result->symbol = token.v.symbol;
4380 designator_t *last_designator = result;
4382 if(token.type == '.') {
4384 if(token.type != T_IDENTIFIER) {
4385 parse_error_expected("while parsing member designator",
4389 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4390 designator->source_position = HERE;
4391 designator->symbol = token.v.symbol;
4394 last_designator->next = designator;
4395 last_designator = designator;
4398 if(token.type == '[') {
4400 add_anchor_token(']');
4401 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4402 designator->source_position = HERE;
4403 designator->array_index = parse_expression();
4404 rem_anchor_token(']');
4406 if(designator->array_index == NULL) {
4410 last_designator->next = designator;
4411 last_designator = designator;
4423 * Parse the __builtin_offsetof() expression.
4425 static expression_t *parse_offsetof(void)
4427 eat(T___builtin_offsetof);
4429 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4430 expression->base.type = type_size_t;
4433 add_anchor_token(',');
4434 type_t *type = parse_typename();
4435 rem_anchor_token(',');
4437 add_anchor_token(')');
4438 designator_t *designator = parse_designator();
4439 rem_anchor_token(')');
4442 expression->offsetofe.type = type;
4443 expression->offsetofe.designator = designator;
4446 memset(&path, 0, sizeof(path));
4447 path.top_type = type;
4448 path.path = NEW_ARR_F(type_path_entry_t, 0);
4450 descend_into_subtype(&path);
4452 if(!walk_designator(&path, designator, true)) {
4453 return create_invalid_expression();
4456 DEL_ARR_F(path.path);
4460 return create_invalid_expression();
4464 * Parses a _builtin_va_start() expression.
4466 static expression_t *parse_va_start(void)
4468 eat(T___builtin_va_start);
4470 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4473 add_anchor_token(',');
4474 expression->va_starte.ap = parse_assignment_expression();
4475 rem_anchor_token(',');
4477 expression_t *const expr = parse_assignment_expression();
4478 if (expr->kind == EXPR_REFERENCE) {
4479 declaration_t *const decl = expr->reference.declaration;
4481 return create_invalid_expression();
4482 if (decl->parent_scope == ¤t_function->scope &&
4483 decl->next == NULL) {
4484 expression->va_starte.parameter = decl;
4489 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4491 return create_invalid_expression();
4495 * Parses a _builtin_va_arg() expression.
4497 static expression_t *parse_va_arg(void)
4499 eat(T___builtin_va_arg);
4501 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4504 expression->va_arge.ap = parse_assignment_expression();
4506 expression->base.type = parse_typename();
4511 return create_invalid_expression();
4514 static expression_t *parse_builtin_symbol(void)
4516 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4518 symbol_t *symbol = token.v.symbol;
4520 expression->builtin_symbol.symbol = symbol;
4523 type_t *type = get_builtin_symbol_type(symbol);
4524 type = automatic_type_conversion(type);
4526 expression->base.type = type;
4531 * Parses a __builtin_constant() expression.
4533 static expression_t *parse_builtin_constant(void)
4535 eat(T___builtin_constant_p);
4537 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4540 add_anchor_token(')');
4541 expression->builtin_constant.value = parse_assignment_expression();
4542 rem_anchor_token(')');
4544 expression->base.type = type_int;
4548 return create_invalid_expression();
4552 * Parses a __builtin_prefetch() expression.
4554 static expression_t *parse_builtin_prefetch(void)
4556 eat(T___builtin_prefetch);
4558 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4561 add_anchor_token(')');
4562 expression->builtin_prefetch.adr = parse_assignment_expression();
4563 if (token.type == ',') {
4565 expression->builtin_prefetch.rw = parse_assignment_expression();
4567 if (token.type == ',') {
4569 expression->builtin_prefetch.locality = parse_assignment_expression();
4571 rem_anchor_token(')');
4573 expression->base.type = type_void;
4577 return create_invalid_expression();
4581 * Parses a __builtin_is_*() compare expression.
4583 static expression_t *parse_compare_builtin(void)
4585 expression_t *expression;
4587 switch(token.type) {
4588 case T___builtin_isgreater:
4589 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4591 case T___builtin_isgreaterequal:
4592 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4594 case T___builtin_isless:
4595 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4597 case T___builtin_islessequal:
4598 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4600 case T___builtin_islessgreater:
4601 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4603 case T___builtin_isunordered:
4604 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4607 internal_errorf(HERE, "invalid compare builtin found");
4610 expression->base.source_position = HERE;
4614 expression->binary.left = parse_assignment_expression();
4616 expression->binary.right = parse_assignment_expression();
4619 type_t *const orig_type_left = expression->binary.left->base.type;
4620 type_t *const orig_type_right = expression->binary.right->base.type;
4622 type_t *const type_left = skip_typeref(orig_type_left);
4623 type_t *const type_right = skip_typeref(orig_type_right);
4624 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4625 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4626 type_error_incompatible("invalid operands in comparison",
4627 expression->base.source_position, orig_type_left, orig_type_right);
4630 semantic_comparison(&expression->binary);
4635 return create_invalid_expression();
4639 * Parses a __builtin_expect() expression.
4641 static expression_t *parse_builtin_expect(void)
4643 eat(T___builtin_expect);
4645 expression_t *expression
4646 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4649 expression->binary.left = parse_assignment_expression();
4651 expression->binary.right = parse_constant_expression();
4654 expression->base.type = expression->binary.left->base.type;
4658 return create_invalid_expression();
4662 * Parses a MS assume() expression.
4664 static expression_t *parse_assume(void) {
4667 expression_t *expression
4668 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4671 add_anchor_token(')');
4672 expression->unary.value = parse_assignment_expression();
4673 rem_anchor_token(')');
4676 expression->base.type = type_void;
4679 return create_invalid_expression();
4683 * Parses a primary expression.
4685 static expression_t *parse_primary_expression(void)
4687 switch (token.type) {
4688 case T_INTEGER: return parse_int_const();
4689 case T_CHARACTER_CONSTANT: return parse_character_constant();
4690 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4691 case T_FLOATINGPOINT: return parse_float_const();
4692 case T_STRING_LITERAL:
4693 case T_WIDE_STRING_LITERAL: return parse_string_const();
4694 case T_IDENTIFIER: return parse_reference();
4695 case T___FUNCTION__:
4696 case T___func__: return parse_function_keyword();
4697 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4698 case T___builtin_offsetof: return parse_offsetof();
4699 case T___builtin_va_start: return parse_va_start();
4700 case T___builtin_va_arg: return parse_va_arg();
4701 case T___builtin_expect: return parse_builtin_expect();
4702 case T___builtin_alloca:
4703 case T___builtin_nan:
4704 case T___builtin_nand:
4705 case T___builtin_nanf:
4706 case T___builtin_va_end: return parse_builtin_symbol();
4707 case T___builtin_isgreater:
4708 case T___builtin_isgreaterequal:
4709 case T___builtin_isless:
4710 case T___builtin_islessequal:
4711 case T___builtin_islessgreater:
4712 case T___builtin_isunordered: return parse_compare_builtin();
4713 case T___builtin_constant_p: return parse_builtin_constant();
4714 case T___builtin_prefetch: return parse_builtin_prefetch();
4715 case T_assume: return parse_assume();
4717 case '(': return parse_brace_expression();
4720 errorf(HERE, "unexpected token %K, expected an expression", &token);
4721 return create_invalid_expression();
4725 * Check if the expression has the character type and issue a warning then.
4727 static void check_for_char_index_type(const expression_t *expression) {
4728 type_t *const type = expression->base.type;
4729 const type_t *const base_type = skip_typeref(type);
4731 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4732 warning.char_subscripts) {
4733 warningf(expression->base.source_position,
4734 "array subscript has type '%T'", type);
4738 static expression_t *parse_array_expression(unsigned precedence,
4744 add_anchor_token(']');
4746 expression_t *inside = parse_expression();
4748 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4750 array_access_expression_t *array_access = &expression->array_access;
4752 type_t *const orig_type_left = left->base.type;
4753 type_t *const orig_type_inside = inside->base.type;
4755 type_t *const type_left = skip_typeref(orig_type_left);
4756 type_t *const type_inside = skip_typeref(orig_type_inside);
4758 type_t *return_type;
4759 if (is_type_pointer(type_left)) {
4760 return_type = type_left->pointer.points_to;
4761 array_access->array_ref = left;
4762 array_access->index = inside;
4763 check_for_char_index_type(inside);
4764 } else if (is_type_pointer(type_inside)) {
4765 return_type = type_inside->pointer.points_to;
4766 array_access->array_ref = inside;
4767 array_access->index = left;
4768 array_access->flipped = true;
4769 check_for_char_index_type(left);
4771 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4773 "array access on object with non-pointer types '%T', '%T'",
4774 orig_type_left, orig_type_inside);
4776 return_type = type_error_type;
4777 array_access->array_ref = create_invalid_expression();
4780 rem_anchor_token(']');
4781 if(token.type != ']') {
4782 parse_error_expected("Problem while parsing array access", ']', 0);
4787 return_type = automatic_type_conversion(return_type);
4788 expression->base.type = return_type;
4793 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4795 expression_t *tp_expression = allocate_expression_zero(kind);
4796 tp_expression->base.type = type_size_t;
4798 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4800 add_anchor_token(')');
4801 tp_expression->typeprop.type = parse_typename();
4802 rem_anchor_token(')');
4805 expression_t *expression = parse_sub_expression(precedence);
4806 expression->base.type = revert_automatic_type_conversion(expression);
4808 tp_expression->typeprop.type = expression->base.type;
4809 tp_expression->typeprop.tp_expression = expression;
4812 return tp_expression;
4814 return create_invalid_expression();
4817 static expression_t *parse_sizeof(unsigned precedence)
4820 return parse_typeprop(EXPR_SIZEOF, precedence);
4823 static expression_t *parse_alignof(unsigned precedence)
4826 return parse_typeprop(EXPR_SIZEOF, precedence);
4829 static expression_t *parse_select_expression(unsigned precedence,
4830 expression_t *compound)
4833 assert(token.type == '.' || token.type == T_MINUSGREATER);
4835 bool is_pointer = (token.type == T_MINUSGREATER);
4838 expression_t *select = allocate_expression_zero(EXPR_SELECT);
4839 select->select.compound = compound;
4841 if(token.type != T_IDENTIFIER) {
4842 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4845 symbol_t *symbol = token.v.symbol;
4846 select->select.symbol = symbol;
4849 type_t *const orig_type = compound->base.type;
4850 type_t *const type = skip_typeref(orig_type);
4852 type_t *type_left = type;
4854 if (!is_type_pointer(type)) {
4855 if (is_type_valid(type)) {
4856 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4858 return create_invalid_expression();
4860 type_left = type->pointer.points_to;
4862 type_left = skip_typeref(type_left);
4864 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4865 type_left->kind != TYPE_COMPOUND_UNION) {
4866 if (is_type_valid(type_left)) {
4867 errorf(HERE, "request for member '%Y' in something not a struct or "
4868 "union, but '%T'", symbol, type_left);
4870 return create_invalid_expression();
4873 declaration_t *const declaration = type_left->compound.declaration;
4875 if(!declaration->init.is_defined) {
4876 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4878 return create_invalid_expression();
4881 declaration_t *iter = find_compound_entry(declaration, symbol);
4883 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4884 return create_invalid_expression();
4887 /* we always do the auto-type conversions; the & and sizeof parser contains
4888 * code to revert this! */
4889 type_t *expression_type = automatic_type_conversion(iter->type);
4891 select->select.compound_entry = iter;
4892 select->base.type = expression_type;
4894 if(expression_type->kind == TYPE_BITFIELD) {
4895 expression_t *extract
4896 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4897 extract->unary.value = select;
4898 extract->base.type = expression_type->bitfield.base;
4907 * Parse a call expression, ie. expression '( ... )'.
4909 * @param expression the function address
4911 static expression_t *parse_call_expression(unsigned precedence,
4912 expression_t *expression)
4915 expression_t *result = allocate_expression_zero(EXPR_CALL);
4917 call_expression_t *call = &result->call;
4918 call->function = expression;
4920 type_t *const orig_type = expression->base.type;
4921 type_t *const type = skip_typeref(orig_type);
4923 function_type_t *function_type = NULL;
4924 if (is_type_pointer(type)) {
4925 type_t *const to_type = skip_typeref(type->pointer.points_to);
4927 if (is_type_function(to_type)) {
4928 function_type = &to_type->function;
4929 call->base.type = function_type->return_type;
4933 if (function_type == NULL && is_type_valid(type)) {
4934 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4937 /* parse arguments */
4939 add_anchor_token(')');
4940 add_anchor_token(',');
4942 if(token.type != ')') {
4943 call_argument_t *last_argument = NULL;
4946 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4948 argument->expression = parse_assignment_expression();
4949 if(last_argument == NULL) {
4950 call->arguments = argument;
4952 last_argument->next = argument;
4954 last_argument = argument;
4956 if(token.type != ',')
4961 rem_anchor_token(',');
4962 rem_anchor_token(')');
4965 if(function_type != NULL) {
4966 function_parameter_t *parameter = function_type->parameters;
4967 call_argument_t *argument = call->arguments;
4968 for( ; parameter != NULL && argument != NULL;
4969 parameter = parameter->next, argument = argument->next) {
4970 type_t *expected_type = parameter->type;
4971 /* TODO report scope in error messages */
4972 expression_t *const arg_expr = argument->expression;
4973 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4974 if (res_type == NULL) {
4975 /* TODO improve error message */
4976 errorf(arg_expr->base.source_position,
4977 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4978 arg_expr, arg_expr->base.type, expected_type);
4980 argument->expression = create_implicit_cast(argument->expression, expected_type);
4983 /* too few parameters */
4984 if(parameter != NULL) {
4985 errorf(HERE, "too few arguments to function '%E'", expression);
4986 } else if(argument != NULL) {
4987 /* too many parameters */
4988 if(!function_type->variadic
4989 && !function_type->unspecified_parameters) {
4990 errorf(HERE, "too many arguments to function '%E'", expression);
4992 /* do default promotion */
4993 for( ; argument != NULL; argument = argument->next) {
4994 type_t *type = argument->expression->base.type;
4996 type = skip_typeref(type);
4997 if(is_type_integer(type)) {
4998 type = promote_integer(type);
4999 } else if(type == type_float) {
5003 argument->expression
5004 = create_implicit_cast(argument->expression, type);
5007 check_format(&result->call);
5010 check_format(&result->call);
5016 return create_invalid_expression();
5019 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5021 static bool same_compound_type(const type_t *type1, const type_t *type2)
5024 is_type_compound(type1) &&
5025 type1->kind == type2->kind &&
5026 type1->compound.declaration == type2->compound.declaration;
5030 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5032 * @param expression the conditional expression
5034 static expression_t *parse_conditional_expression(unsigned precedence,
5035 expression_t *expression)
5038 add_anchor_token(':');
5040 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5042 conditional_expression_t *conditional = &result->conditional;
5043 conditional->condition = expression;
5046 type_t *const condition_type_orig = expression->base.type;
5047 type_t *const condition_type = skip_typeref(condition_type_orig);
5048 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5049 type_error("expected a scalar type in conditional condition",
5050 expression->base.source_position, condition_type_orig);
5053 expression_t *true_expression = parse_expression();
5054 rem_anchor_token(':');
5056 expression_t *false_expression = parse_sub_expression(precedence);
5058 type_t *const orig_true_type = true_expression->base.type;
5059 type_t *const orig_false_type = false_expression->base.type;
5060 type_t *const true_type = skip_typeref(orig_true_type);
5061 type_t *const false_type = skip_typeref(orig_false_type);
5064 type_t *result_type;
5065 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
5066 result_type = semantic_arithmetic(true_type, false_type);
5068 true_expression = create_implicit_cast(true_expression, result_type);
5069 false_expression = create_implicit_cast(false_expression, result_type);
5071 conditional->true_expression = true_expression;
5072 conditional->false_expression = false_expression;
5073 conditional->base.type = result_type;
5074 } else if (same_compound_type(true_type, false_type) || (
5075 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
5076 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
5078 /* just take 1 of the 2 types */
5079 result_type = true_type;
5080 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
5081 && pointers_compatible(true_type, false_type)) {
5083 result_type = true_type;
5084 } else if (is_type_pointer(true_type)
5085 && is_null_pointer_constant(false_expression)) {
5086 result_type = true_type;
5087 } else if (is_type_pointer(false_type)
5088 && is_null_pointer_constant(true_expression)) {
5089 result_type = false_type;
5091 /* TODO: one pointer to void*, other some pointer */
5093 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5094 type_error_incompatible("while parsing conditional",
5095 expression->base.source_position, true_type,
5098 result_type = type_error_type;
5101 conditional->true_expression
5102 = create_implicit_cast(true_expression, result_type);
5103 conditional->false_expression
5104 = create_implicit_cast(false_expression, result_type);
5105 conditional->base.type = result_type;
5108 return create_invalid_expression();
5112 * Parse an extension expression.
5114 static expression_t *parse_extension(unsigned precedence)
5116 eat(T___extension__);
5118 /* TODO enable extensions */
5119 expression_t *expression = parse_sub_expression(precedence);
5120 /* TODO disable extensions */
5125 * Parse a __builtin_classify_type() expression.
5127 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5129 eat(T___builtin_classify_type);
5131 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5132 result->base.type = type_int;
5135 add_anchor_token(')');
5136 expression_t *expression = parse_sub_expression(precedence);
5137 rem_anchor_token(')');
5139 result->classify_type.type_expression = expression;
5143 return create_invalid_expression();
5146 static void semantic_incdec(unary_expression_t *expression)
5148 type_t *const orig_type = expression->value->base.type;
5149 type_t *const type = skip_typeref(orig_type);
5150 /* TODO !is_type_real && !is_type_pointer */
5151 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5152 if (is_type_valid(type)) {
5153 /* TODO: improve error message */
5154 errorf(HERE, "operation needs an arithmetic or pointer type");
5159 expression->base.type = orig_type;
5162 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5164 type_t *const orig_type = expression->value->base.type;
5165 type_t *const type = skip_typeref(orig_type);
5166 if(!is_type_arithmetic(type)) {
5167 if (is_type_valid(type)) {
5168 /* TODO: improve error message */
5169 errorf(HERE, "operation needs an arithmetic type");
5174 expression->base.type = orig_type;
5177 static void semantic_unexpr_scalar(unary_expression_t *expression)
5179 type_t *const orig_type = expression->value->base.type;
5180 type_t *const type = skip_typeref(orig_type);
5181 if (!is_type_scalar(type)) {
5182 if (is_type_valid(type)) {
5183 errorf(HERE, "operand of ! must be of scalar type");
5188 expression->base.type = orig_type;
5191 static void semantic_unexpr_integer(unary_expression_t *expression)
5193 type_t *const orig_type = expression->value->base.type;
5194 type_t *const type = skip_typeref(orig_type);
5195 if (!is_type_integer(type)) {
5196 if (is_type_valid(type)) {
5197 errorf(HERE, "operand of ~ must be of integer type");
5202 expression->base.type = orig_type;
5205 static void semantic_dereference(unary_expression_t *expression)
5207 type_t *const orig_type = expression->value->base.type;
5208 type_t *const type = skip_typeref(orig_type);
5209 if(!is_type_pointer(type)) {
5210 if (is_type_valid(type)) {
5211 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5216 type_t *result_type = type->pointer.points_to;
5217 result_type = automatic_type_conversion(result_type);
5218 expression->base.type = result_type;
5222 * Check the semantic of the address taken expression.
5224 static void semantic_take_addr(unary_expression_t *expression)
5226 expression_t *value = expression->value;
5227 value->base.type = revert_automatic_type_conversion(value);
5229 type_t *orig_type = value->base.type;
5230 if(!is_type_valid(orig_type))
5233 if(value->kind == EXPR_REFERENCE) {
5234 declaration_t *const declaration = value->reference.declaration;
5235 if(declaration != NULL) {
5236 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5237 errorf(expression->base.source_position,
5238 "address of register variable '%Y' requested",
5239 declaration->symbol);
5241 declaration->address_taken = 1;
5245 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5248 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5249 static expression_t *parse_##unexpression_type(unsigned precedence) \
5253 expression_t *unary_expression \
5254 = allocate_expression_zero(unexpression_type); \
5255 unary_expression->base.source_position = HERE; \
5256 unary_expression->unary.value = parse_sub_expression(precedence); \
5258 sfunc(&unary_expression->unary); \
5260 return unary_expression; \
5263 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5264 semantic_unexpr_arithmetic)
5265 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5266 semantic_unexpr_arithmetic)
5267 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5268 semantic_unexpr_scalar)
5269 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5270 semantic_dereference)
5271 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5273 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5274 semantic_unexpr_integer)
5275 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5277 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5280 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5282 static expression_t *parse_##unexpression_type(unsigned precedence, \
5283 expression_t *left) \
5285 (void) precedence; \
5288 expression_t *unary_expression \
5289 = allocate_expression_zero(unexpression_type); \
5290 unary_expression->unary.value = left; \
5292 sfunc(&unary_expression->unary); \
5294 return unary_expression; \
5297 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5298 EXPR_UNARY_POSTFIX_INCREMENT,
5300 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5301 EXPR_UNARY_POSTFIX_DECREMENT,
5304 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5306 /* TODO: handle complex + imaginary types */
5308 /* § 6.3.1.8 Usual arithmetic conversions */
5309 if(type_left == type_long_double || type_right == type_long_double) {
5310 return type_long_double;
5311 } else if(type_left == type_double || type_right == type_double) {
5313 } else if(type_left == type_float || type_right == type_float) {
5317 type_right = promote_integer(type_right);
5318 type_left = promote_integer(type_left);
5320 if(type_left == type_right)
5323 bool signed_left = is_type_signed(type_left);
5324 bool signed_right = is_type_signed(type_right);
5325 int rank_left = get_rank(type_left);
5326 int rank_right = get_rank(type_right);
5327 if(rank_left < rank_right) {
5328 if(signed_left == signed_right || !signed_right) {
5334 if(signed_left == signed_right || !signed_left) {
5343 * Check the semantic restrictions for a binary expression.
5345 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5347 expression_t *const left = expression->left;
5348 expression_t *const right = expression->right;
5349 type_t *const orig_type_left = left->base.type;
5350 type_t *const orig_type_right = right->base.type;
5351 type_t *const type_left = skip_typeref(orig_type_left);
5352 type_t *const type_right = skip_typeref(orig_type_right);
5354 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5355 /* TODO: improve error message */
5356 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5357 errorf(HERE, "operation needs arithmetic types");
5362 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5363 expression->left = create_implicit_cast(left, arithmetic_type);
5364 expression->right = create_implicit_cast(right, arithmetic_type);
5365 expression->base.type = arithmetic_type;
5368 static void semantic_shift_op(binary_expression_t *expression)
5370 expression_t *const left = expression->left;
5371 expression_t *const right = expression->right;
5372 type_t *const orig_type_left = left->base.type;
5373 type_t *const orig_type_right = right->base.type;
5374 type_t * type_left = skip_typeref(orig_type_left);
5375 type_t * type_right = skip_typeref(orig_type_right);
5377 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5378 /* TODO: improve error message */
5379 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5380 errorf(HERE, "operation needs integer types");
5385 type_left = promote_integer(type_left);
5386 type_right = promote_integer(type_right);
5388 expression->left = create_implicit_cast(left, type_left);
5389 expression->right = create_implicit_cast(right, type_right);
5390 expression->base.type = type_left;
5393 static void semantic_add(binary_expression_t *expression)
5395 expression_t *const left = expression->left;
5396 expression_t *const right = expression->right;
5397 type_t *const orig_type_left = left->base.type;
5398 type_t *const orig_type_right = right->base.type;
5399 type_t *const type_left = skip_typeref(orig_type_left);
5400 type_t *const type_right = skip_typeref(orig_type_right);
5403 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5404 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5405 expression->left = create_implicit_cast(left, arithmetic_type);
5406 expression->right = create_implicit_cast(right, arithmetic_type);
5407 expression->base.type = arithmetic_type;
5409 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5410 expression->base.type = type_left;
5411 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5412 expression->base.type = type_right;
5413 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5414 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5418 static void semantic_sub(binary_expression_t *expression)
5420 expression_t *const left = expression->left;
5421 expression_t *const right = expression->right;
5422 type_t *const orig_type_left = left->base.type;
5423 type_t *const orig_type_right = right->base.type;
5424 type_t *const type_left = skip_typeref(orig_type_left);
5425 type_t *const type_right = skip_typeref(orig_type_right);
5428 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5429 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5430 expression->left = create_implicit_cast(left, arithmetic_type);
5431 expression->right = create_implicit_cast(right, arithmetic_type);
5432 expression->base.type = arithmetic_type;
5434 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5435 expression->base.type = type_left;
5436 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5437 if(!pointers_compatible(type_left, type_right)) {
5439 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5440 orig_type_left, orig_type_right);
5442 expression->base.type = type_ptrdiff_t;
5444 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5445 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5446 orig_type_left, orig_type_right);
5451 * Check the semantics of comparison expressions.
5453 * @param expression The expression to check.
5455 static void semantic_comparison(binary_expression_t *expression)
5457 expression_t *left = expression->left;
5458 expression_t *right = expression->right;
5459 type_t *orig_type_left = left->base.type;
5460 type_t *orig_type_right = right->base.type;
5462 type_t *type_left = skip_typeref(orig_type_left);
5463 type_t *type_right = skip_typeref(orig_type_right);
5465 /* TODO non-arithmetic types */
5466 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5467 if (warning.sign_compare &&
5468 (expression->base.kind != EXPR_BINARY_EQUAL &&
5469 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5470 (is_type_signed(type_left) != is_type_signed(type_right))) {
5471 warningf(expression->base.source_position,
5472 "comparison between signed and unsigned");
5474 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5475 expression->left = create_implicit_cast(left, arithmetic_type);
5476 expression->right = create_implicit_cast(right, arithmetic_type);
5477 expression->base.type = arithmetic_type;
5478 if (warning.float_equal &&
5479 (expression->base.kind == EXPR_BINARY_EQUAL ||
5480 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5481 is_type_float(arithmetic_type)) {
5482 warningf(expression->base.source_position,
5483 "comparing floating point with == or != is unsafe");
5485 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5486 /* TODO check compatibility */
5487 } else if (is_type_pointer(type_left)) {
5488 expression->right = create_implicit_cast(right, type_left);
5489 } else if (is_type_pointer(type_right)) {
5490 expression->left = create_implicit_cast(left, type_right);
5491 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5492 type_error_incompatible("invalid operands in comparison",
5493 expression->base.source_position,
5494 type_left, type_right);
5496 expression->base.type = type_int;
5499 static void semantic_arithmetic_assign(binary_expression_t *expression)
5501 expression_t *left = expression->left;
5502 expression_t *right = expression->right;
5503 type_t *orig_type_left = left->base.type;
5504 type_t *orig_type_right = right->base.type;
5506 type_t *type_left = skip_typeref(orig_type_left);
5507 type_t *type_right = skip_typeref(orig_type_right);
5509 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5510 /* TODO: improve error message */
5511 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5512 errorf(HERE, "operation needs arithmetic types");
5517 /* combined instructions are tricky. We can't create an implicit cast on
5518 * the left side, because we need the uncasted form for the store.
5519 * The ast2firm pass has to know that left_type must be right_type
5520 * for the arithmetic operation and create a cast by itself */
5521 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5522 expression->right = create_implicit_cast(right, arithmetic_type);
5523 expression->base.type = type_left;
5526 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5528 expression_t *const left = expression->left;
5529 expression_t *const right = expression->right;
5530 type_t *const orig_type_left = left->base.type;
5531 type_t *const orig_type_right = right->base.type;
5532 type_t *const type_left = skip_typeref(orig_type_left);
5533 type_t *const type_right = skip_typeref(orig_type_right);
5535 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5536 /* combined instructions are tricky. We can't create an implicit cast on
5537 * the left side, because we need the uncasted form for the store.
5538 * The ast2firm pass has to know that left_type must be right_type
5539 * for the arithmetic operation and create a cast by itself */
5540 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5541 expression->right = create_implicit_cast(right, arithmetic_type);
5542 expression->base.type = type_left;
5543 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5544 expression->base.type = type_left;
5545 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5546 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5551 * Check the semantic restrictions of a logical expression.
5553 static void semantic_logical_op(binary_expression_t *expression)
5555 expression_t *const left = expression->left;
5556 expression_t *const right = expression->right;
5557 type_t *const orig_type_left = left->base.type;
5558 type_t *const orig_type_right = right->base.type;
5559 type_t *const type_left = skip_typeref(orig_type_left);
5560 type_t *const type_right = skip_typeref(orig_type_right);
5562 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5563 /* TODO: improve error message */
5564 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5565 errorf(HERE, "operation needs scalar types");
5570 expression->base.type = type_int;
5574 * Checks if a compound type has constant fields.
5576 static bool has_const_fields(const compound_type_t *type)
5578 const scope_t *scope = &type->declaration->scope;
5579 const declaration_t *declaration = scope->declarations;
5581 for (; declaration != NULL; declaration = declaration->next) {
5582 if (declaration->namespc != NAMESPACE_NORMAL)
5585 const type_t *decl_type = skip_typeref(declaration->type);
5586 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5594 * Check the semantic restrictions of a binary assign expression.
5596 static void semantic_binexpr_assign(binary_expression_t *expression)
5598 expression_t *left = expression->left;
5599 type_t *orig_type_left = left->base.type;
5601 type_t *type_left = revert_automatic_type_conversion(left);
5602 type_left = skip_typeref(orig_type_left);
5604 /* must be a modifiable lvalue */
5605 if (is_type_array(type_left)) {
5606 errorf(HERE, "cannot assign to arrays ('%E')", left);
5609 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5610 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5614 if(is_type_incomplete(type_left)) {
5616 "left-hand side of assignment '%E' has incomplete type '%T'",
5617 left, orig_type_left);
5620 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5621 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5622 left, orig_type_left);
5626 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5628 if (res_type == NULL) {
5629 errorf(expression->base.source_position,
5630 "cannot assign to '%T' from '%T'",
5631 orig_type_left, expression->right->base.type);
5633 expression->right = create_implicit_cast(expression->right, res_type);
5636 expression->base.type = orig_type_left;
5640 * Determine if the outermost operation (or parts thereof) of the given
5641 * expression has no effect in order to generate a warning about this fact.
5642 * Therefore in some cases this only examines some of the operands of the
5643 * expression (see comments in the function and examples below).
5645 * f() + 23; // warning, because + has no effect
5646 * x || f(); // no warning, because x controls execution of f()
5647 * x ? y : f(); // warning, because y has no effect
5648 * (void)x; // no warning to be able to suppress the warning
5649 * This function can NOT be used for an "expression has definitely no effect"-
5651 static bool expression_has_effect(const expression_t *const expr)
5653 switch (expr->kind) {
5654 case EXPR_UNKNOWN: break;
5655 case EXPR_INVALID: return true; /* do NOT warn */
5656 case EXPR_REFERENCE: return false;
5657 case EXPR_CONST: return false;
5658 case EXPR_CHARACTER_CONSTANT: return false;
5659 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5660 case EXPR_STRING_LITERAL: return false;
5661 case EXPR_WIDE_STRING_LITERAL: return false;
5664 const call_expression_t *const call = &expr->call;
5665 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5668 switch (call->function->builtin_symbol.symbol->ID) {
5669 case T___builtin_va_end: return true;
5670 default: return false;
5674 /* Generate the warning if either the left or right hand side of a
5675 * conditional expression has no effect */
5676 case EXPR_CONDITIONAL: {
5677 const conditional_expression_t *const cond = &expr->conditional;
5679 expression_has_effect(cond->true_expression) &&
5680 expression_has_effect(cond->false_expression);
5683 case EXPR_SELECT: return false;
5684 case EXPR_ARRAY_ACCESS: return false;
5685 case EXPR_SIZEOF: return false;
5686 case EXPR_CLASSIFY_TYPE: return false;
5687 case EXPR_ALIGNOF: return false;
5689 case EXPR_FUNCTION: return false;
5690 case EXPR_PRETTY_FUNCTION: return false;
5691 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5692 case EXPR_BUILTIN_CONSTANT_P: return false;
5693 case EXPR_BUILTIN_PREFETCH: return true;
5694 case EXPR_OFFSETOF: return false;
5695 case EXPR_VA_START: return true;
5696 case EXPR_VA_ARG: return true;
5697 case EXPR_STATEMENT: return true; // TODO
5698 case EXPR_COMPOUND_LITERAL: return false;
5700 case EXPR_UNARY_NEGATE: return false;
5701 case EXPR_UNARY_PLUS: return false;
5702 case EXPR_UNARY_BITWISE_NEGATE: return false;
5703 case EXPR_UNARY_NOT: return false;
5704 case EXPR_UNARY_DEREFERENCE: return false;
5705 case EXPR_UNARY_TAKE_ADDRESS: return false;
5706 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5707 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5708 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5709 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5711 /* Treat void casts as if they have an effect in order to being able to
5712 * suppress the warning */
5713 case EXPR_UNARY_CAST: {
5714 type_t *const type = skip_typeref(expr->base.type);
5715 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5718 case EXPR_UNARY_CAST_IMPLICIT: return true;
5719 case EXPR_UNARY_ASSUME: return true;
5720 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5722 case EXPR_BINARY_ADD: return false;
5723 case EXPR_BINARY_SUB: return false;
5724 case EXPR_BINARY_MUL: return false;
5725 case EXPR_BINARY_DIV: return false;
5726 case EXPR_BINARY_MOD: return false;
5727 case EXPR_BINARY_EQUAL: return false;
5728 case EXPR_BINARY_NOTEQUAL: return false;
5729 case EXPR_BINARY_LESS: return false;
5730 case EXPR_BINARY_LESSEQUAL: return false;
5731 case EXPR_BINARY_GREATER: return false;
5732 case EXPR_BINARY_GREATEREQUAL: return false;
5733 case EXPR_BINARY_BITWISE_AND: return false;
5734 case EXPR_BINARY_BITWISE_OR: return false;
5735 case EXPR_BINARY_BITWISE_XOR: return false;
5736 case EXPR_BINARY_SHIFTLEFT: return false;
5737 case EXPR_BINARY_SHIFTRIGHT: return false;
5738 case EXPR_BINARY_ASSIGN: return true;
5739 case EXPR_BINARY_MUL_ASSIGN: return true;
5740 case EXPR_BINARY_DIV_ASSIGN: return true;
5741 case EXPR_BINARY_MOD_ASSIGN: return true;
5742 case EXPR_BINARY_ADD_ASSIGN: return true;
5743 case EXPR_BINARY_SUB_ASSIGN: return true;
5744 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5745 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5746 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5747 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5748 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5750 /* Only examine the right hand side of && and ||, because the left hand
5751 * side already has the effect of controlling the execution of the right
5753 case EXPR_BINARY_LOGICAL_AND:
5754 case EXPR_BINARY_LOGICAL_OR:
5755 /* Only examine the right hand side of a comma expression, because the left
5756 * hand side has a separate warning */
5757 case EXPR_BINARY_COMMA:
5758 return expression_has_effect(expr->binary.right);
5760 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5761 case EXPR_BINARY_ISGREATER: return false;
5762 case EXPR_BINARY_ISGREATEREQUAL: return false;
5763 case EXPR_BINARY_ISLESS: return false;
5764 case EXPR_BINARY_ISLESSEQUAL: return false;
5765 case EXPR_BINARY_ISLESSGREATER: return false;
5766 case EXPR_BINARY_ISUNORDERED: return false;
5769 internal_errorf(HERE, "unexpected expression");
5772 static void semantic_comma(binary_expression_t *expression)
5774 if (warning.unused_value) {
5775 const expression_t *const left = expression->left;
5776 if (!expression_has_effect(left)) {
5777 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5780 expression->base.type = expression->right->base.type;
5783 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5784 static expression_t *parse_##binexpression_type(unsigned precedence, \
5785 expression_t *left) \
5788 source_position_t pos = HERE; \
5790 expression_t *right = parse_sub_expression(precedence + lr); \
5792 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5793 binexpr->base.source_position = pos; \
5794 binexpr->binary.left = left; \
5795 binexpr->binary.right = right; \
5796 sfunc(&binexpr->binary); \
5801 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5802 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5803 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5804 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5805 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5806 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5807 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5808 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5809 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5811 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5812 semantic_comparison, 1)
5813 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5814 semantic_comparison, 1)
5815 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5816 semantic_comparison, 1)
5817 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5818 semantic_comparison, 1)
5820 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5821 semantic_binexpr_arithmetic, 1)
5822 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5823 semantic_binexpr_arithmetic, 1)
5824 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5825 semantic_binexpr_arithmetic, 1)
5826 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5827 semantic_logical_op, 1)
5828 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5829 semantic_logical_op, 1)
5830 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5831 semantic_shift_op, 1)
5832 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5833 semantic_shift_op, 1)
5834 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5835 semantic_arithmetic_addsubb_assign, 0)
5836 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5837 semantic_arithmetic_addsubb_assign, 0)
5838 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5839 semantic_arithmetic_assign, 0)
5840 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5841 semantic_arithmetic_assign, 0)
5842 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5843 semantic_arithmetic_assign, 0)
5844 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5845 semantic_arithmetic_assign, 0)
5846 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5847 semantic_arithmetic_assign, 0)
5848 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5849 semantic_arithmetic_assign, 0)
5850 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5851 semantic_arithmetic_assign, 0)
5852 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5853 semantic_arithmetic_assign, 0)
5855 static expression_t *parse_sub_expression(unsigned precedence)
5857 if(token.type < 0) {
5858 return expected_expression_error();
5861 expression_parser_function_t *parser
5862 = &expression_parsers[token.type];
5863 source_position_t source_position = token.source_position;
5866 if(parser->parser != NULL) {
5867 left = parser->parser(parser->precedence);
5869 left = parse_primary_expression();
5871 assert(left != NULL);
5872 left->base.source_position = source_position;
5875 if(token.type < 0) {
5876 return expected_expression_error();
5879 parser = &expression_parsers[token.type];
5880 if(parser->infix_parser == NULL)
5882 if(parser->infix_precedence < precedence)
5885 left = parser->infix_parser(parser->infix_precedence, left);
5887 assert(left != NULL);
5888 assert(left->kind != EXPR_UNKNOWN);
5889 left->base.source_position = source_position;
5896 * Parse an expression.
5898 static expression_t *parse_expression(void)
5900 return parse_sub_expression(1);
5904 * Register a parser for a prefix-like operator with given precedence.
5906 * @param parser the parser function
5907 * @param token_type the token type of the prefix token
5908 * @param precedence the precedence of the operator
5910 static void register_expression_parser(parse_expression_function parser,
5911 int token_type, unsigned precedence)
5913 expression_parser_function_t *entry = &expression_parsers[token_type];
5915 if(entry->parser != NULL) {
5916 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5917 panic("trying to register multiple expression parsers for a token");
5919 entry->parser = parser;
5920 entry->precedence = precedence;
5924 * Register a parser for an infix operator with given precedence.
5926 * @param parser the parser function
5927 * @param token_type the token type of the infix operator
5928 * @param precedence the precedence of the operator
5930 static void register_infix_parser(parse_expression_infix_function parser,
5931 int token_type, unsigned precedence)
5933 expression_parser_function_t *entry = &expression_parsers[token_type];
5935 if(entry->infix_parser != NULL) {
5936 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5937 panic("trying to register multiple infix expression parsers for a "
5940 entry->infix_parser = parser;
5941 entry->infix_precedence = precedence;
5945 * Initialize the expression parsers.
5947 static void init_expression_parsers(void)
5949 memset(&expression_parsers, 0, sizeof(expression_parsers));
5951 register_infix_parser(parse_array_expression, '[', 30);
5952 register_infix_parser(parse_call_expression, '(', 30);
5953 register_infix_parser(parse_select_expression, '.', 30);
5954 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
5955 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5957 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5960 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
5961 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
5962 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
5963 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
5964 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
5965 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
5966 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
5967 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
5968 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
5969 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
5970 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
5971 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
5972 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5973 T_EXCLAMATIONMARKEQUAL, 13);
5974 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
5975 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
5976 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
5977 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
5978 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
5979 register_infix_parser(parse_conditional_expression, '?', 7);
5980 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
5981 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
5982 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
5983 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
5984 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
5985 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
5986 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5987 T_LESSLESSEQUAL, 2);
5988 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5989 T_GREATERGREATEREQUAL, 2);
5990 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5992 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5994 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5997 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
5999 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6000 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6001 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6002 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6003 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6004 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6005 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6007 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6009 register_expression_parser(parse_sizeof, T_sizeof, 25);
6010 register_expression_parser(parse_alignof, T___alignof__, 25);
6011 register_expression_parser(parse_extension, T___extension__, 25);
6012 register_expression_parser(parse_builtin_classify_type,
6013 T___builtin_classify_type, 25);
6017 * Parse a asm statement constraints specification.
6019 static asm_constraint_t *parse_asm_constraints(void)
6021 asm_constraint_t *result = NULL;
6022 asm_constraint_t *last = NULL;
6024 while(token.type == T_STRING_LITERAL || token.type == '[') {
6025 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6026 memset(constraint, 0, sizeof(constraint[0]));
6028 if(token.type == '[') {
6030 if(token.type != T_IDENTIFIER) {
6031 parse_error_expected("while parsing asm constraint",
6035 constraint->symbol = token.v.symbol;
6040 constraint->constraints = parse_string_literals();
6042 constraint->expression = parse_expression();
6046 last->next = constraint;
6048 result = constraint;
6052 if(token.type != ',')
6063 * Parse a asm statement clobber specification.
6065 static asm_clobber_t *parse_asm_clobbers(void)
6067 asm_clobber_t *result = NULL;
6068 asm_clobber_t *last = NULL;
6070 while(token.type == T_STRING_LITERAL) {
6071 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6072 clobber->clobber = parse_string_literals();
6075 last->next = clobber;
6081 if(token.type != ',')
6090 * Parse an asm statement.
6092 static statement_t *parse_asm_statement(void)
6096 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6097 statement->base.source_position = token.source_position;
6099 asm_statement_t *asm_statement = &statement->asms;
6101 if(token.type == T_volatile) {
6103 asm_statement->is_volatile = true;
6107 add_anchor_token(')');
6108 add_anchor_token(':');
6109 asm_statement->asm_text = parse_string_literals();
6111 if(token.type != ':') {
6112 rem_anchor_token(':');
6117 asm_statement->inputs = parse_asm_constraints();
6118 if(token.type != ':') {
6119 rem_anchor_token(':');
6124 asm_statement->outputs = parse_asm_constraints();
6125 if(token.type != ':') {
6126 rem_anchor_token(':');
6129 rem_anchor_token(':');
6132 asm_statement->clobbers = parse_asm_clobbers();
6135 rem_anchor_token(')');
6140 return create_invalid_statement();
6144 * Parse a case statement.
6146 static statement_t *parse_case_statement(void)
6150 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6152 statement->base.source_position = token.source_position;
6153 statement->case_label.expression = parse_expression();
6155 if (c_mode & _GNUC) {
6156 if (token.type == T_DOTDOTDOT) {
6158 statement->case_label.end_range = parse_expression();
6164 if (! is_constant_expression(statement->case_label.expression)) {
6165 errorf(statement->base.source_position,
6166 "case label does not reduce to an integer constant");
6168 /* TODO: check if the case label is already known */
6169 if (current_switch != NULL) {
6170 /* link all cases into the switch statement */
6171 if (current_switch->last_case == NULL) {
6172 current_switch->first_case =
6173 current_switch->last_case = &statement->case_label;
6175 current_switch->last_case->next = &statement->case_label;
6178 errorf(statement->base.source_position,
6179 "case label not within a switch statement");
6182 statement->case_label.statement = parse_statement();
6186 return create_invalid_statement();
6190 * Finds an existing default label of a switch statement.
6192 static case_label_statement_t *
6193 find_default_label(const switch_statement_t *statement)
6195 case_label_statement_t *label = statement->first_case;
6196 for ( ; label != NULL; label = label->next) {
6197 if (label->expression == NULL)
6204 * Parse a default statement.
6206 static statement_t *parse_default_statement(void)
6210 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6212 statement->base.source_position = token.source_position;
6215 if (current_switch != NULL) {
6216 const case_label_statement_t *def_label = find_default_label(current_switch);
6217 if (def_label != NULL) {
6218 errorf(HERE, "multiple default labels in one switch");
6219 errorf(def_label->base.source_position,
6220 "this is the first default label");
6222 /* link all cases into the switch statement */
6223 if (current_switch->last_case == NULL) {
6224 current_switch->first_case =
6225 current_switch->last_case = &statement->case_label;
6227 current_switch->last_case->next = &statement->case_label;
6231 errorf(statement->base.source_position,
6232 "'default' label not within a switch statement");
6234 statement->case_label.statement = parse_statement();
6238 return create_invalid_statement();
6242 * Return the declaration for a given label symbol or create a new one.
6244 static declaration_t *get_label(symbol_t *symbol)
6246 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6247 assert(current_function != NULL);
6248 /* if we found a label in the same function, then we already created the
6250 if(candidate != NULL
6251 && candidate->parent_scope == ¤t_function->scope) {
6255 /* otherwise we need to create a new one */
6256 declaration_t *const declaration = allocate_declaration_zero();
6257 declaration->namespc = NAMESPACE_LABEL;
6258 declaration->symbol = symbol;
6260 label_push(declaration);
6266 * Parse a label statement.
6268 static statement_t *parse_label_statement(void)
6270 assert(token.type == T_IDENTIFIER);
6271 symbol_t *symbol = token.v.symbol;
6274 declaration_t *label = get_label(symbol);
6276 /* if source position is already set then the label is defined twice,
6277 * otherwise it was just mentioned in a goto so far */
6278 if(label->source_position.input_name != NULL) {
6279 errorf(HERE, "duplicate label '%Y'", symbol);
6280 errorf(label->source_position, "previous definition of '%Y' was here",
6283 label->source_position = token.source_position;
6286 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6288 statement->base.source_position = token.source_position;
6289 statement->label.label = label;
6293 if(token.type == '}') {
6294 /* TODO only warn? */
6296 warningf(HERE, "label at end of compound statement");
6297 statement->label.statement = create_empty_statement();
6299 errorf(HERE, "label at end of compound statement");
6300 statement->label.statement = create_invalid_statement();
6304 if (token.type == ';') {
6305 /* eat an empty statement here, to avoid the warning about an empty
6306 * after a label. label:; is commonly used to have a label before
6308 statement->label.statement = create_empty_statement();
6311 statement->label.statement = parse_statement();
6315 /* remember the labels's in a list for later checking */
6316 if (label_last == NULL) {
6317 label_first = &statement->label;
6319 label_last->next = &statement->label;
6321 label_last = &statement->label;
6327 * Parse an if statement.
6329 static statement_t *parse_if(void)
6333 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6334 statement->base.source_position = token.source_position;
6337 add_anchor_token(')');
6338 statement->ifs.condition = parse_expression();
6339 rem_anchor_token(')');
6342 add_anchor_token(T_else);
6343 statement->ifs.true_statement = parse_statement();
6344 rem_anchor_token(T_else);
6346 if(token.type == T_else) {
6348 statement->ifs.false_statement = parse_statement();
6353 return create_invalid_statement();
6357 * Parse a switch statement.
6359 static statement_t *parse_switch(void)
6363 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6364 statement->base.source_position = token.source_position;
6367 expression_t *const expr = parse_expression();
6368 type_t * type = skip_typeref(expr->base.type);
6369 if (is_type_integer(type)) {
6370 type = promote_integer(type);
6371 } else if (is_type_valid(type)) {
6372 errorf(expr->base.source_position,
6373 "switch quantity is not an integer, but '%T'", type);
6374 type = type_error_type;
6376 statement->switchs.expression = create_implicit_cast(expr, type);
6379 switch_statement_t *rem = current_switch;
6380 current_switch = &statement->switchs;
6381 statement->switchs.body = parse_statement();
6382 current_switch = rem;
6384 if (warning.switch_default
6385 && find_default_label(&statement->switchs) == NULL) {
6386 warningf(statement->base.source_position, "switch has no default case");
6391 return create_invalid_statement();
6394 static statement_t *parse_loop_body(statement_t *const loop)
6396 statement_t *const rem = current_loop;
6397 current_loop = loop;
6399 statement_t *const body = parse_statement();
6406 * Parse a while statement.
6408 static statement_t *parse_while(void)
6412 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6413 statement->base.source_position = token.source_position;
6416 add_anchor_token(')');
6417 statement->whiles.condition = parse_expression();
6418 rem_anchor_token(')');
6421 statement->whiles.body = parse_loop_body(statement);
6425 return create_invalid_statement();
6429 * Parse a do statement.
6431 static statement_t *parse_do(void)
6435 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6437 statement->base.source_position = token.source_position;
6439 add_anchor_token(T_while);
6440 statement->do_while.body = parse_loop_body(statement);
6441 rem_anchor_token(T_while);
6445 add_anchor_token(')');
6446 statement->do_while.condition = parse_expression();
6447 rem_anchor_token(')');
6453 return create_invalid_statement();
6457 * Parse a for statement.
6459 static statement_t *parse_for(void)
6463 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6464 statement->base.source_position = token.source_position;
6466 int top = environment_top();
6467 scope_t *last_scope = scope;
6468 set_scope(&statement->fors.scope);
6471 add_anchor_token(')');
6473 if(token.type != ';') {
6474 if(is_declaration_specifier(&token, false)) {
6475 parse_declaration(record_declaration);
6477 expression_t *const init = parse_expression();
6478 statement->fors.initialisation = init;
6479 if (warning.unused_value && !expression_has_effect(init)) {
6480 warningf(init->base.source_position,
6481 "initialisation of 'for'-statement has no effect");
6489 if(token.type != ';') {
6490 statement->fors.condition = parse_expression();
6493 if(token.type != ')') {
6494 expression_t *const step = parse_expression();
6495 statement->fors.step = step;
6496 if (warning.unused_value && !expression_has_effect(step)) {
6497 warningf(step->base.source_position,
6498 "step of 'for'-statement has no effect");
6501 rem_anchor_token(')');
6503 statement->fors.body = parse_loop_body(statement);
6505 assert(scope == &statement->fors.scope);
6506 set_scope(last_scope);
6507 environment_pop_to(top);
6512 rem_anchor_token(')');
6513 assert(scope == &statement->fors.scope);
6514 set_scope(last_scope);
6515 environment_pop_to(top);
6517 return create_invalid_statement();
6521 * Parse a goto statement.
6523 static statement_t *parse_goto(void)
6527 if(token.type != T_IDENTIFIER) {
6528 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6532 symbol_t *symbol = token.v.symbol;
6535 declaration_t *label = get_label(symbol);
6537 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6538 statement->base.source_position = token.source_position;
6540 statement->gotos.label = label;
6542 /* remember the goto's in a list for later checking */
6543 if (goto_last == NULL) {
6544 goto_first = &statement->gotos;
6546 goto_last->next = &statement->gotos;
6548 goto_last = &statement->gotos;
6554 return create_invalid_statement();
6558 * Parse a continue statement.
6560 static statement_t *parse_continue(void)
6562 statement_t *statement;
6563 if (current_loop == NULL) {
6564 errorf(HERE, "continue statement not within loop");
6567 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6569 statement->base.source_position = token.source_position;
6577 return create_invalid_statement();
6581 * Parse a break statement.
6583 static statement_t *parse_break(void)
6585 statement_t *statement;
6586 if (current_switch == NULL && current_loop == NULL) {
6587 errorf(HERE, "break statement not within loop or switch");
6590 statement = allocate_statement_zero(STATEMENT_BREAK);
6592 statement->base.source_position = token.source_position;
6600 return create_invalid_statement();
6604 * Check if a given declaration represents a local variable.
6606 static bool is_local_var_declaration(const declaration_t *declaration) {
6607 switch ((storage_class_tag_t) declaration->storage_class) {
6608 case STORAGE_CLASS_AUTO:
6609 case STORAGE_CLASS_REGISTER: {
6610 const type_t *type = skip_typeref(declaration->type);
6611 if(is_type_function(type)) {
6623 * Check if a given declaration represents a variable.
6625 static bool is_var_declaration(const declaration_t *declaration) {
6626 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6629 const type_t *type = skip_typeref(declaration->type);
6630 return !is_type_function(type);
6634 * Check if a given expression represents a local variable.
6636 static bool is_local_variable(const expression_t *expression)
6638 if (expression->base.kind != EXPR_REFERENCE) {
6641 const declaration_t *declaration = expression->reference.declaration;
6642 return is_local_var_declaration(declaration);
6646 * Check if a given expression represents a local variable and
6647 * return its declaration then, else return NULL.
6649 declaration_t *expr_is_variable(const expression_t *expression)
6651 if (expression->base.kind != EXPR_REFERENCE) {
6654 declaration_t *declaration = expression->reference.declaration;
6655 if (is_var_declaration(declaration))
6661 * Parse a return statement.
6663 static statement_t *parse_return(void)
6667 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6668 statement->base.source_position = token.source_position;
6670 expression_t *return_value = NULL;
6671 if(token.type != ';') {
6672 return_value = parse_expression();
6676 const type_t *const func_type = current_function->type;
6677 assert(is_type_function(func_type));
6678 type_t *const return_type = skip_typeref(func_type->function.return_type);
6680 if(return_value != NULL) {
6681 type_t *return_value_type = skip_typeref(return_value->base.type);
6683 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6684 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6685 warningf(statement->base.source_position,
6686 "'return' with a value, in function returning void");
6687 return_value = NULL;
6689 type_t *const res_type = semantic_assign(return_type,
6690 return_value, "'return'");
6691 if (res_type == NULL) {
6692 errorf(statement->base.source_position,
6693 "cannot return something of type '%T' in function returning '%T'",
6694 return_value->base.type, return_type);
6696 return_value = create_implicit_cast(return_value, res_type);
6699 /* check for returning address of a local var */
6700 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6701 const expression_t *expression = return_value->unary.value;
6702 if (is_local_variable(expression)) {
6703 warningf(statement->base.source_position,
6704 "function returns address of local variable");
6708 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6709 warningf(statement->base.source_position,
6710 "'return' without value, in function returning non-void");
6713 statement->returns.value = return_value;
6717 return create_invalid_statement();
6721 * Parse a declaration statement.
6723 static statement_t *parse_declaration_statement(void)
6725 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6727 statement->base.source_position = token.source_position;
6729 declaration_t *before = last_declaration;
6730 parse_declaration(record_declaration);
6732 if(before == NULL) {
6733 statement->declaration.declarations_begin = scope->declarations;
6735 statement->declaration.declarations_begin = before->next;
6737 statement->declaration.declarations_end = last_declaration;
6743 * Parse an expression statement, ie. expr ';'.
6745 static statement_t *parse_expression_statement(void)
6747 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6749 statement->base.source_position = token.source_position;
6750 expression_t *const expr = parse_expression();
6751 statement->expression.expression = expr;
6753 if (warning.unused_value && !expression_has_effect(expr)) {
6754 warningf(expr->base.source_position, "statement has no effect");
6761 return create_invalid_statement();
6765 * Parse a statement.
6767 static statement_t *parse_statement(void)
6769 statement_t *statement = NULL;
6771 /* declaration or statement */
6772 add_anchor_token(';');
6773 switch(token.type) {
6775 statement = parse_asm_statement();
6779 statement = parse_case_statement();
6783 statement = parse_default_statement();
6787 statement = parse_compound_statement();
6791 statement = parse_if();
6795 statement = parse_switch();
6799 statement = parse_while();
6803 statement = parse_do();
6807 statement = parse_for();
6811 statement = parse_goto();
6815 statement = parse_continue();
6819 statement = parse_break();
6823 statement = parse_return();
6827 if(warning.empty_statement) {
6828 warningf(HERE, "statement is empty");
6830 statement = create_empty_statement();
6835 if(look_ahead(1)->type == ':') {
6836 statement = parse_label_statement();
6840 if(is_typedef_symbol(token.v.symbol)) {
6841 statement = parse_declaration_statement();
6845 statement = parse_expression_statement();
6848 case T___extension__:
6849 /* this can be a prefix to a declaration or an expression statement */
6850 /* we simply eat it now and parse the rest with tail recursion */
6853 } while(token.type == T___extension__);
6854 statement = parse_statement();
6858 statement = parse_declaration_statement();
6862 statement = parse_expression_statement();
6865 rem_anchor_token(';');
6867 assert(statement != NULL
6868 && statement->base.source_position.input_name != NULL);
6874 * Parse a compound statement.
6876 static statement_t *parse_compound_statement(void)
6878 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6880 statement->base.source_position = token.source_position;
6883 add_anchor_token('}');
6885 int top = environment_top();
6886 scope_t *last_scope = scope;
6887 set_scope(&statement->compound.scope);
6889 statement_t *last_statement = NULL;
6891 while(token.type != '}' && token.type != T_EOF) {
6892 statement_t *sub_statement = parse_statement();
6893 if(is_invalid_statement(sub_statement)) {
6894 /* an error occurred. if we are at an anchor, return */
6900 if(last_statement != NULL) {
6901 last_statement->base.next = sub_statement;
6903 statement->compound.statements = sub_statement;
6906 while(sub_statement->base.next != NULL)
6907 sub_statement = sub_statement->base.next;
6909 last_statement = sub_statement;
6912 if(token.type == '}') {
6915 errorf(statement->base.source_position,
6916 "end of file while looking for closing '}'");
6920 rem_anchor_token('}');
6921 assert(scope == &statement->compound.scope);
6922 set_scope(last_scope);
6923 environment_pop_to(top);
6929 * Initialize builtin types.
6931 static void initialize_builtin_types(void)
6933 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
6934 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
6935 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
6936 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
6937 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
6938 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6939 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
6940 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
6942 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
6943 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6944 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
6945 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
6949 * Check for unused global static functions and variables
6951 static void check_unused_globals(void)
6953 if (!warning.unused_function && !warning.unused_variable)
6956 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6957 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6960 type_t *const type = decl->type;
6962 if (is_type_function(skip_typeref(type))) {
6963 if (!warning.unused_function || decl->is_inline)
6966 s = (decl->init.statement != NULL ? "defined" : "declared");
6968 if (!warning.unused_variable)
6974 warningf(decl->source_position, "'%#T' %s but not used",
6975 type, decl->symbol, s);
6980 * Parse a translation unit.
6982 static translation_unit_t *parse_translation_unit(void)
6984 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6986 assert(global_scope == NULL);
6987 global_scope = &unit->scope;
6989 assert(scope == NULL);
6990 set_scope(&unit->scope);
6992 initialize_builtin_types();
6994 while(token.type != T_EOF) {
6995 if (token.type == ';') {
6996 /* TODO error in strict mode */
6997 warningf(HERE, "stray ';' outside of function");
7000 parse_external_declaration();
7004 assert(scope == &unit->scope);
7006 last_declaration = NULL;
7008 assert(global_scope == &unit->scope);
7009 check_unused_globals();
7010 global_scope = NULL;
7018 * @return the translation unit or NULL if errors occurred.
7020 translation_unit_t *parse(void)
7022 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7023 label_stack = NEW_ARR_F(stack_entry_t, 0);
7024 diagnostic_count = 0;
7028 type_set_output(stderr);
7029 ast_set_output(stderr);
7031 lookahead_bufpos = 0;
7032 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7035 translation_unit_t *unit = parse_translation_unit();
7037 DEL_ARR_F(environment_stack);
7038 DEL_ARR_F(label_stack);
7044 * Initialize the parser.
7046 void init_parser(void)
7049 /* add predefined symbols for extended-decl-modifier */
7050 sym_align = symbol_table_insert("align");
7051 sym_allocate = symbol_table_insert("allocate");
7052 sym_dllimport = symbol_table_insert("dllimport");
7053 sym_dllexport = symbol_table_insert("dllexport");
7054 sym_naked = symbol_table_insert("naked");
7055 sym_noinline = symbol_table_insert("noinline");
7056 sym_noreturn = symbol_table_insert("noreturn");
7057 sym_nothrow = symbol_table_insert("nothrow");
7058 sym_novtable = symbol_table_insert("novtable");
7059 sym_property = symbol_table_insert("property");
7060 sym_get = symbol_table_insert("get");
7061 sym_put = symbol_table_insert("put");
7062 sym_selectany = symbol_table_insert("selectany");
7063 sym_thread = symbol_table_insert("thread");
7064 sym_uuid = symbol_table_insert("uuid");
7065 sym_deprecated = symbol_table_insert("deprecated");
7066 sym_restrict = symbol_table_insert("restrict");
7067 sym_noalias = symbol_table_insert("noalias");
7069 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7071 init_expression_parsers();
7072 obstack_init(&temp_obst);
7074 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7075 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7079 * Terminate the parser.
7081 void exit_parser(void)
7083 obstack_free(&temp_obst, NULL);