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 == '{') {
1478 static initializer_t *create_empty_initializer(void)
1480 static initializer_t empty_initializer
1481 = { .list = { { INITIALIZER_LIST }, 0 } };
1482 return &empty_initializer;
1486 * Parse a part of an initialiser for a struct or union,
1488 static initializer_t *parse_sub_initializer(type_path_t *path,
1489 type_t *outer_type, size_t top_path_level,
1490 parse_initializer_env_t *env)
1492 if(token.type == '}') {
1493 /* empty initializer */
1494 return create_empty_initializer();
1497 type_t *orig_type = path->top_type;
1498 type_t *type = NULL;
1500 if (orig_type == NULL) {
1501 /* We are initializing an empty compound. */
1503 type = skip_typeref(orig_type);
1505 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1506 * initializers in this case. */
1507 if(!is_type_valid(type)) {
1508 skip_initializers();
1509 return create_empty_initializer();
1513 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1516 designator_t *designator = NULL;
1517 if(token.type == '.' || token.type == '[') {
1518 designator = parse_designation();
1520 /* reset path to toplevel, evaluate designator from there */
1521 ascend_to(path, top_path_level);
1522 if(!walk_designator(path, designator, false)) {
1523 /* can't continue after designation error */
1527 initializer_t *designator_initializer
1528 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1529 designator_initializer->designator.designator = designator;
1530 ARR_APP1(initializer_t*, initializers, designator_initializer);
1535 if(token.type == '{') {
1536 if(type != NULL && is_type_scalar(type)) {
1537 sub = parse_scalar_initializer(type, env->must_be_constant);
1541 if (env->declaration != NULL)
1542 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1543 env->declaration->symbol);
1545 errorf(HERE, "extra brace group at end of initializer");
1547 descend_into_subtype(path);
1549 add_anchor_token('}');
1550 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1552 rem_anchor_token('}');
1555 ascend_from_subtype(path);
1559 goto error_parse_next;
1563 /* must be an expression */
1564 expression_t *expression = parse_assignment_expression();
1566 if(env->must_be_constant && !is_initializer_constant(expression)) {
1567 errorf(expression->base.source_position,
1568 "Initialisation expression '%E' is not constant\n",
1573 /* we are already outside, ... */
1577 /* handle { "string" } special case */
1578 if((expression->kind == EXPR_STRING_LITERAL
1579 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1580 && outer_type != NULL) {
1581 sub = initializer_from_expression(outer_type, expression);
1583 if(token.type == ',') {
1586 if(token.type != '}') {
1587 warningf(HERE, "excessive elements in initializer for type '%T'",
1590 /* TODO: eat , ... */
1595 /* descend into subtypes until expression matches type */
1597 orig_type = path->top_type;
1598 type = skip_typeref(orig_type);
1600 sub = initializer_from_expression(orig_type, expression);
1604 if(!is_type_valid(type)) {
1607 if(is_type_scalar(type)) {
1608 errorf(expression->base.source_position,
1609 "expression '%E' doesn't match expected type '%T'",
1610 expression, orig_type);
1614 descend_into_subtype(path);
1618 /* update largest index of top array */
1619 const type_path_entry_t *first = &path->path[0];
1620 type_t *first_type = first->type;
1621 first_type = skip_typeref(first_type);
1622 if(is_type_array(first_type)) {
1623 size_t index = first->v.index;
1624 if(index > path->max_index)
1625 path->max_index = index;
1629 /* append to initializers list */
1630 ARR_APP1(initializer_t*, initializers, sub);
1633 if(env->declaration != NULL)
1634 warningf(HERE, "excess elements in struct initializer for '%Y'",
1635 env->declaration->symbol);
1637 warningf(HERE, "excess elements in struct initializer");
1641 if(token.type == '}') {
1645 if(token.type == '}') {
1650 /* advance to the next declaration if we are not at the end */
1651 advance_current_object(path, top_path_level);
1652 orig_type = path->top_type;
1653 if(orig_type != NULL)
1654 type = skip_typeref(orig_type);
1660 size_t len = ARR_LEN(initializers);
1661 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1662 initializer_t *result = allocate_ast_zero(size);
1663 result->kind = INITIALIZER_LIST;
1664 result->list.len = len;
1665 memcpy(&result->list.initializers, initializers,
1666 len * sizeof(initializers[0]));
1668 DEL_ARR_F(initializers);
1669 ascend_to(path, top_path_level);
1674 skip_initializers();
1675 DEL_ARR_F(initializers);
1676 ascend_to(path, top_path_level);
1681 * Parses an initializer. Parsers either a compound literal
1682 * (env->declaration == NULL) or an initializer of a declaration.
1684 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1686 type_t *type = skip_typeref(env->type);
1687 initializer_t *result = NULL;
1690 if(is_type_scalar(type)) {
1691 result = parse_scalar_initializer(type, env->must_be_constant);
1692 } else if(token.type == '{') {
1696 memset(&path, 0, sizeof(path));
1697 path.top_type = env->type;
1698 path.path = NEW_ARR_F(type_path_entry_t, 0);
1700 descend_into_subtype(&path);
1702 add_anchor_token('}');
1703 result = parse_sub_initializer(&path, env->type, 1, env);
1704 rem_anchor_token('}');
1706 max_index = path.max_index;
1707 DEL_ARR_F(path.path);
1711 /* parse_scalar_initializer() also works in this case: we simply
1712 * have an expression without {} around it */
1713 result = parse_scalar_initializer(type, env->must_be_constant);
1716 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1717 * the array type size */
1718 if(is_type_array(type) && type->array.size_expression == NULL
1719 && result != NULL) {
1721 switch (result->kind) {
1722 case INITIALIZER_LIST:
1723 size = max_index + 1;
1726 case INITIALIZER_STRING:
1727 size = result->string.string.size;
1730 case INITIALIZER_WIDE_STRING:
1731 size = result->wide_string.string.size;
1735 internal_errorf(HERE, "invalid initializer type");
1738 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1739 cnst->base.type = type_size_t;
1740 cnst->conste.v.int_value = size;
1742 type_t *new_type = duplicate_type(type);
1744 new_type->array.size_expression = cnst;
1745 new_type->array.size_constant = true;
1746 new_type->array.size = size;
1747 env->type = new_type;
1755 static declaration_t *append_declaration(declaration_t *declaration);
1757 static declaration_t *parse_compound_type_specifier(bool is_struct)
1765 symbol_t *symbol = NULL;
1766 declaration_t *declaration = NULL;
1768 if (token.type == T___attribute__) {
1773 if(token.type == T_IDENTIFIER) {
1774 symbol = token.v.symbol;
1778 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1780 declaration = get_declaration(symbol, NAMESPACE_UNION);
1782 } else if(token.type != '{') {
1784 parse_error_expected("while parsing struct type specifier",
1785 T_IDENTIFIER, '{', 0);
1787 parse_error_expected("while parsing union type specifier",
1788 T_IDENTIFIER, '{', 0);
1794 if(declaration == NULL) {
1795 declaration = allocate_declaration_zero();
1796 declaration->namespc =
1797 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1798 declaration->source_position = token.source_position;
1799 declaration->symbol = symbol;
1800 declaration->parent_scope = scope;
1801 if (symbol != NULL) {
1802 environment_push(declaration);
1804 append_declaration(declaration);
1807 if(token.type == '{') {
1808 if(declaration->init.is_defined) {
1809 assert(symbol != NULL);
1810 errorf(HERE, "multiple definitions of '%s %Y'",
1811 is_struct ? "struct" : "union", symbol);
1812 declaration->scope.declarations = NULL;
1814 declaration->init.is_defined = true;
1816 parse_compound_type_entries(declaration);
1823 static void parse_enum_entries(type_t *const enum_type)
1827 if(token.type == '}') {
1829 errorf(HERE, "empty enum not allowed");
1833 add_anchor_token('}');
1835 if(token.type != T_IDENTIFIER) {
1836 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1838 rem_anchor_token('}');
1842 declaration_t *const entry = allocate_declaration_zero();
1843 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1844 entry->type = enum_type;
1845 entry->symbol = token.v.symbol;
1846 entry->source_position = token.source_position;
1849 if(token.type == '=') {
1851 expression_t *value = parse_constant_expression();
1853 value = create_implicit_cast(value, enum_type);
1854 entry->init.enum_value = value;
1859 record_declaration(entry);
1861 if(token.type != ',')
1864 } while(token.type != '}');
1865 rem_anchor_token('}');
1873 static type_t *parse_enum_specifier(void)
1877 declaration_t *declaration;
1880 if(token.type == T_IDENTIFIER) {
1881 symbol = token.v.symbol;
1884 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1885 } else if(token.type != '{') {
1886 parse_error_expected("while parsing enum type specifier",
1887 T_IDENTIFIER, '{', 0);
1894 if(declaration == NULL) {
1895 declaration = allocate_declaration_zero();
1896 declaration->namespc = NAMESPACE_ENUM;
1897 declaration->source_position = token.source_position;
1898 declaration->symbol = symbol;
1899 declaration->parent_scope = scope;
1902 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1903 type->enumt.declaration = declaration;
1905 if(token.type == '{') {
1906 if(declaration->init.is_defined) {
1907 errorf(HERE, "multiple definitions of enum %Y", symbol);
1909 if (symbol != NULL) {
1910 environment_push(declaration);
1912 append_declaration(declaration);
1913 declaration->init.is_defined = 1;
1915 parse_enum_entries(type);
1923 * if a symbol is a typedef to another type, return true
1925 static bool is_typedef_symbol(symbol_t *symbol)
1927 const declaration_t *const declaration =
1928 get_declaration(symbol, NAMESPACE_NORMAL);
1930 declaration != NULL &&
1931 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1934 static type_t *parse_typeof(void)
1941 add_anchor_token(')');
1943 expression_t *expression = NULL;
1946 switch(token.type) {
1947 case T___extension__:
1948 /* this can be a prefix to a typename or an expression */
1949 /* we simply eat it now. */
1952 } while(token.type == T___extension__);
1956 if(is_typedef_symbol(token.v.symbol)) {
1957 type = parse_typename();
1959 expression = parse_expression();
1960 type = expression->base.type;
1965 type = parse_typename();
1969 expression = parse_expression();
1970 type = expression->base.type;
1974 rem_anchor_token(')');
1977 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1978 typeof_type->typeoft.expression = expression;
1979 typeof_type->typeoft.typeof_type = type;
1987 SPECIFIER_SIGNED = 1 << 0,
1988 SPECIFIER_UNSIGNED = 1 << 1,
1989 SPECIFIER_LONG = 1 << 2,
1990 SPECIFIER_INT = 1 << 3,
1991 SPECIFIER_DOUBLE = 1 << 4,
1992 SPECIFIER_CHAR = 1 << 5,
1993 SPECIFIER_SHORT = 1 << 6,
1994 SPECIFIER_LONG_LONG = 1 << 7,
1995 SPECIFIER_FLOAT = 1 << 8,
1996 SPECIFIER_BOOL = 1 << 9,
1997 SPECIFIER_VOID = 1 << 10,
1998 #ifdef PROVIDE_COMPLEX
1999 SPECIFIER_COMPLEX = 1 << 11,
2000 SPECIFIER_IMAGINARY = 1 << 12,
2004 static type_t *create_builtin_type(symbol_t *const symbol,
2005 type_t *const real_type)
2007 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2008 type->builtin.symbol = symbol;
2009 type->builtin.real_type = real_type;
2011 type_t *result = typehash_insert(type);
2012 if (type != result) {
2019 static type_t *get_typedef_type(symbol_t *symbol)
2021 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2022 if(declaration == NULL
2023 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2026 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2027 type->typedeft.declaration = declaration;
2033 * check for the allowed MS alignment values.
2035 static bool check_elignment_value(long long intvalue) {
2036 if(intvalue < 1 || intvalue > 8192) {
2037 errorf(HERE, "illegal alignment value");
2040 unsigned v = (unsigned)intvalue;
2041 for(unsigned i = 1; i <= 8192; i += i) {
2045 errorf(HERE, "alignment must be power of two");
2049 #define DET_MOD(name, tag) do { \
2050 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2051 *modifiers |= tag; \
2054 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2056 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2059 if(token.type == T_restrict) {
2061 DET_MOD(restrict, DM_RESTRICT);
2063 } else if(token.type != T_IDENTIFIER)
2065 symbol_t *symbol = token.v.symbol;
2066 if(symbol == sym_align) {
2069 if(token.type != T_INTEGER)
2071 if(check_elignment_value(token.v.intvalue)) {
2072 if(specifiers->alignment != 0)
2073 warningf(HERE, "align used more than once");
2074 specifiers->alignment = (unsigned char)token.v.intvalue;
2078 } else if(symbol == sym_allocate) {
2081 if(token.type != T_IDENTIFIER)
2083 (void)token.v.symbol;
2085 } else if(symbol == sym_dllimport) {
2087 DET_MOD(dllimport, DM_DLLIMPORT);
2088 } else if(symbol == sym_dllexport) {
2090 DET_MOD(dllexport, DM_DLLEXPORT);
2091 } else if(symbol == sym_thread) {
2093 DET_MOD(thread, DM_THREAD);
2094 } else if(symbol == sym_naked) {
2096 DET_MOD(naked, DM_NAKED);
2097 } else if(symbol == sym_noinline) {
2099 DET_MOD(noinline, DM_NOINLINE);
2100 } else if(symbol == sym_noreturn) {
2102 DET_MOD(noreturn, DM_NORETURN);
2103 } else if(symbol == sym_nothrow) {
2105 DET_MOD(nothrow, DM_NOTHROW);
2106 } else if(symbol == sym_novtable) {
2108 DET_MOD(novtable, DM_NOVTABLE);
2109 } else if(symbol == sym_property) {
2113 bool is_get = false;
2114 if(token.type != T_IDENTIFIER)
2116 if(token.v.symbol == sym_get) {
2118 } else if(token.v.symbol == sym_put) {
2120 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2125 if(token.type != T_IDENTIFIER)
2128 if(specifiers->get_property_sym != NULL) {
2129 errorf(HERE, "get property name already specified");
2131 specifiers->get_property_sym = token.v.symbol;
2134 if(specifiers->put_property_sym != NULL) {
2135 errorf(HERE, "put property name already specified");
2137 specifiers->put_property_sym = token.v.symbol;
2141 if(token.type == ',') {
2148 } else if(symbol == sym_selectany) {
2150 DET_MOD(selectany, DM_SELECTANY);
2151 } else if(symbol == sym_uuid) {
2154 if(token.type != T_STRING_LITERAL)
2158 } else if(symbol == sym_deprecated) {
2160 DET_MOD(deprecated, DM_DEPRECATED);
2161 if(token.type == '(') {
2163 if(token.type == T_STRING_LITERAL) {
2164 specifiers->deprecated_string = token.v.string.begin;
2167 errorf(HERE, "string literal expected");
2171 } else if(symbol == sym_noalias) {
2173 DET_MOD(noalias, DM_NOALIAS);
2175 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2177 if(token.type == '(')
2181 if (token.type == ',')
2188 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2190 type_t *type = NULL;
2191 unsigned type_qualifiers = 0;
2192 unsigned type_specifiers = 0;
2195 specifiers->source_position = token.source_position;
2198 switch(token.type) {
2201 #define MATCH_STORAGE_CLASS(token, class) \
2203 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2204 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2206 specifiers->declared_storage_class = class; \
2210 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2211 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2212 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2213 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2214 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2219 add_anchor_token(')');
2220 parse_microsoft_extended_decl_modifier(specifiers);
2221 rem_anchor_token(')');
2226 switch (specifiers->declared_storage_class) {
2227 case STORAGE_CLASS_NONE:
2228 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2231 case STORAGE_CLASS_EXTERN:
2232 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2235 case STORAGE_CLASS_STATIC:
2236 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2240 errorf(HERE, "multiple storage classes in declaration specifiers");
2246 /* type qualifiers */
2247 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2249 type_qualifiers |= qualifier; \
2253 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2254 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2255 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2257 case T___extension__:
2262 /* type specifiers */
2263 #define MATCH_SPECIFIER(token, specifier, name) \
2266 if(type_specifiers & specifier) { \
2267 errorf(HERE, "multiple " name " type specifiers given"); \
2269 type_specifiers |= specifier; \
2273 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2274 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2275 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2276 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2277 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2278 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2279 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2280 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2281 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2282 #ifdef PROVIDE_COMPLEX
2283 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2284 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2287 /* only in microsoft mode */
2288 specifiers->decl_modifiers |= DM_FORCEINLINE;
2292 specifiers->is_inline = true;
2297 if(type_specifiers & SPECIFIER_LONG_LONG) {
2298 errorf(HERE, "multiple type specifiers given");
2299 } else if(type_specifiers & SPECIFIER_LONG) {
2300 type_specifiers |= SPECIFIER_LONG_LONG;
2302 type_specifiers |= SPECIFIER_LONG;
2307 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2309 type->compound.declaration = parse_compound_type_specifier(true);
2313 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2315 type->compound.declaration = parse_compound_type_specifier(false);
2319 type = parse_enum_specifier();
2322 type = parse_typeof();
2324 case T___builtin_va_list:
2325 type = duplicate_type(type_valist);
2329 case T___attribute__:
2333 case T_IDENTIFIER: {
2334 /* only parse identifier if we haven't found a type yet */
2335 if(type != NULL || type_specifiers != 0)
2336 goto finish_specifiers;
2338 type_t *typedef_type = get_typedef_type(token.v.symbol);
2340 if(typedef_type == NULL)
2341 goto finish_specifiers;
2344 type = typedef_type;
2348 /* function specifier */
2350 goto finish_specifiers;
2357 atomic_type_kind_t atomic_type;
2359 /* match valid basic types */
2360 switch(type_specifiers) {
2361 case SPECIFIER_VOID:
2362 atomic_type = ATOMIC_TYPE_VOID;
2364 case SPECIFIER_CHAR:
2365 atomic_type = ATOMIC_TYPE_CHAR;
2367 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2368 atomic_type = ATOMIC_TYPE_SCHAR;
2370 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2371 atomic_type = ATOMIC_TYPE_UCHAR;
2373 case SPECIFIER_SHORT:
2374 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2375 case SPECIFIER_SHORT | SPECIFIER_INT:
2376 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2377 atomic_type = ATOMIC_TYPE_SHORT;
2379 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2380 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2381 atomic_type = ATOMIC_TYPE_USHORT;
2384 case SPECIFIER_SIGNED:
2385 case SPECIFIER_SIGNED | SPECIFIER_INT:
2386 atomic_type = ATOMIC_TYPE_INT;
2388 case SPECIFIER_UNSIGNED:
2389 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2390 atomic_type = ATOMIC_TYPE_UINT;
2392 case SPECIFIER_LONG:
2393 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2394 case SPECIFIER_LONG | SPECIFIER_INT:
2395 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2396 atomic_type = ATOMIC_TYPE_LONG;
2398 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2399 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2400 atomic_type = ATOMIC_TYPE_ULONG;
2402 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2403 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2404 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2405 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2407 atomic_type = ATOMIC_TYPE_LONGLONG;
2409 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2410 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2412 atomic_type = ATOMIC_TYPE_ULONGLONG;
2414 case SPECIFIER_FLOAT:
2415 atomic_type = ATOMIC_TYPE_FLOAT;
2417 case SPECIFIER_DOUBLE:
2418 atomic_type = ATOMIC_TYPE_DOUBLE;
2420 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2421 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2423 case SPECIFIER_BOOL:
2424 atomic_type = ATOMIC_TYPE_BOOL;
2426 #ifdef PROVIDE_COMPLEX
2427 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2428 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2430 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2431 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2433 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2434 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2436 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2437 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2439 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2440 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2442 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2443 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2447 /* invalid specifier combination, give an error message */
2448 if(type_specifiers == 0) {
2449 if (! strict_mode) {
2450 if (warning.implicit_int) {
2451 warningf(HERE, "no type specifiers in declaration, using 'int'");
2453 atomic_type = ATOMIC_TYPE_INT;
2456 errorf(HERE, "no type specifiers given in declaration");
2458 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2459 (type_specifiers & SPECIFIER_UNSIGNED)) {
2460 errorf(HERE, "signed and unsigned specifiers gives");
2461 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2462 errorf(HERE, "only integer types can be signed or unsigned");
2464 errorf(HERE, "multiple datatypes in declaration");
2466 atomic_type = ATOMIC_TYPE_INVALID;
2469 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2470 type->atomic.akind = atomic_type;
2473 if(type_specifiers != 0) {
2474 errorf(HERE, "multiple datatypes in declaration");
2478 type->base.qualifiers = type_qualifiers;
2480 type_t *result = typehash_insert(type);
2481 if(newtype && result != type) {
2485 specifiers->type = result;
2490 static type_qualifiers_t parse_type_qualifiers(void)
2492 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2495 switch(token.type) {
2496 /* type qualifiers */
2497 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2498 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2499 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2502 return type_qualifiers;
2507 static declaration_t *parse_identifier_list(void)
2509 declaration_t *declarations = NULL;
2510 declaration_t *last_declaration = NULL;
2512 declaration_t *const declaration = allocate_declaration_zero();
2513 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2514 declaration->source_position = token.source_position;
2515 declaration->symbol = token.v.symbol;
2518 if(last_declaration != NULL) {
2519 last_declaration->next = declaration;
2521 declarations = declaration;
2523 last_declaration = declaration;
2525 if(token.type != ',')
2528 } while(token.type == T_IDENTIFIER);
2530 return declarations;
2533 static void semantic_parameter(declaration_t *declaration)
2535 /* TODO: improve error messages */
2537 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2538 errorf(HERE, "typedef not allowed in parameter list");
2539 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2540 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2541 errorf(HERE, "parameter may only have none or register storage class");
2544 type_t *const orig_type = declaration->type;
2545 type_t * type = skip_typeref(orig_type);
2547 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2548 * into a pointer. § 6.7.5.3 (7) */
2549 if (is_type_array(type)) {
2550 type_t *const element_type = type->array.element_type;
2552 type = make_pointer_type(element_type, type->base.qualifiers);
2554 declaration->type = type;
2557 if(is_type_incomplete(type)) {
2558 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2559 orig_type, declaration->symbol);
2563 static declaration_t *parse_parameter(void)
2565 declaration_specifiers_t specifiers;
2566 memset(&specifiers, 0, sizeof(specifiers));
2568 parse_declaration_specifiers(&specifiers);
2570 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2572 semantic_parameter(declaration);
2577 static declaration_t *parse_parameters(function_type_t *type)
2579 if(token.type == T_IDENTIFIER) {
2580 symbol_t *symbol = token.v.symbol;
2581 if(!is_typedef_symbol(symbol)) {
2582 type->kr_style_parameters = true;
2583 return parse_identifier_list();
2587 if(token.type == ')') {
2588 type->unspecified_parameters = 1;
2591 if(token.type == T_void && look_ahead(1)->type == ')') {
2596 declaration_t *declarations = NULL;
2597 declaration_t *declaration;
2598 declaration_t *last_declaration = NULL;
2599 function_parameter_t *parameter;
2600 function_parameter_t *last_parameter = NULL;
2603 switch(token.type) {
2607 return declarations;
2610 case T___extension__:
2612 declaration = parse_parameter();
2614 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2615 memset(parameter, 0, sizeof(parameter[0]));
2616 parameter->type = declaration->type;
2618 if(last_parameter != NULL) {
2619 last_declaration->next = declaration;
2620 last_parameter->next = parameter;
2622 type->parameters = parameter;
2623 declarations = declaration;
2625 last_parameter = parameter;
2626 last_declaration = declaration;
2630 return declarations;
2632 if(token.type != ',')
2633 return declarations;
2643 } construct_type_kind_t;
2645 typedef struct construct_type_t construct_type_t;
2646 struct construct_type_t {
2647 construct_type_kind_t kind;
2648 construct_type_t *next;
2651 typedef struct parsed_pointer_t parsed_pointer_t;
2652 struct parsed_pointer_t {
2653 construct_type_t construct_type;
2654 type_qualifiers_t type_qualifiers;
2657 typedef struct construct_function_type_t construct_function_type_t;
2658 struct construct_function_type_t {
2659 construct_type_t construct_type;
2660 type_t *function_type;
2663 typedef struct parsed_array_t parsed_array_t;
2664 struct parsed_array_t {
2665 construct_type_t construct_type;
2666 type_qualifiers_t type_qualifiers;
2672 typedef struct construct_base_type_t construct_base_type_t;
2673 struct construct_base_type_t {
2674 construct_type_t construct_type;
2678 static construct_type_t *parse_pointer_declarator(void)
2682 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2683 memset(pointer, 0, sizeof(pointer[0]));
2684 pointer->construct_type.kind = CONSTRUCT_POINTER;
2685 pointer->type_qualifiers = parse_type_qualifiers();
2687 return (construct_type_t*) pointer;
2690 static construct_type_t *parse_array_declarator(void)
2693 add_anchor_token(']');
2695 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2696 memset(array, 0, sizeof(array[0]));
2697 array->construct_type.kind = CONSTRUCT_ARRAY;
2699 if(token.type == T_static) {
2700 array->is_static = true;
2704 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2705 if(type_qualifiers != 0) {
2706 if(token.type == T_static) {
2707 array->is_static = true;
2711 array->type_qualifiers = type_qualifiers;
2713 if(token.type == '*' && look_ahead(1)->type == ']') {
2714 array->is_variable = true;
2716 } else if(token.type != ']') {
2717 array->size = parse_assignment_expression();
2720 rem_anchor_token(']');
2723 return (construct_type_t*) array;
2728 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2731 add_anchor_token(')');
2734 if(declaration != NULL) {
2735 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2737 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2740 declaration_t *parameters = parse_parameters(&type->function);
2741 if(declaration != NULL) {
2742 declaration->scope.declarations = parameters;
2745 construct_function_type_t *construct_function_type =
2746 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2747 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2748 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2749 construct_function_type->function_type = type;
2751 rem_anchor_token(')');
2755 return (construct_type_t*) construct_function_type;
2758 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2759 bool may_be_abstract)
2761 /* construct a single linked list of construct_type_t's which describe
2762 * how to construct the final declarator type */
2763 construct_type_t *first = NULL;
2764 construct_type_t *last = NULL;
2767 while(token.type == '*') {
2768 construct_type_t *type = parse_pointer_declarator();
2779 /* TODO: find out if this is correct */
2782 construct_type_t *inner_types = NULL;
2784 switch(token.type) {
2786 if(declaration == NULL) {
2787 errorf(HERE, "no identifier expected in typename");
2789 declaration->symbol = token.v.symbol;
2790 declaration->source_position = token.source_position;
2796 add_anchor_token(')');
2797 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2798 rem_anchor_token(')');
2804 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2805 /* avoid a loop in the outermost scope, because eat_statement doesn't
2807 if(token.type == '}' && current_function == NULL) {
2815 construct_type_t *p = last;
2818 construct_type_t *type;
2819 switch(token.type) {
2821 type = parse_function_declarator(declaration);
2824 type = parse_array_declarator();
2827 goto declarator_finished;
2830 /* insert in the middle of the list (behind p) */
2832 type->next = p->next;
2843 declarator_finished:
2846 /* append inner_types at the end of the list, we don't to set last anymore
2847 * as it's not needed anymore */
2849 assert(first == NULL);
2850 first = inner_types;
2852 last->next = inner_types;
2860 static type_t *construct_declarator_type(construct_type_t *construct_list,
2863 construct_type_t *iter = construct_list;
2864 for( ; iter != NULL; iter = iter->next) {
2865 switch(iter->kind) {
2866 case CONSTRUCT_INVALID:
2867 internal_errorf(HERE, "invalid type construction found");
2868 case CONSTRUCT_FUNCTION: {
2869 construct_function_type_t *construct_function_type
2870 = (construct_function_type_t*) iter;
2872 type_t *function_type = construct_function_type->function_type;
2874 function_type->function.return_type = type;
2876 type_t *skipped_return_type = skip_typeref(type);
2877 if (is_type_function(skipped_return_type)) {
2878 errorf(HERE, "function returning function is not allowed");
2879 type = type_error_type;
2880 } else if (is_type_array(skipped_return_type)) {
2881 errorf(HERE, "function returning array is not allowed");
2882 type = type_error_type;
2884 type = function_type;
2889 case CONSTRUCT_POINTER: {
2890 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2891 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2892 pointer_type->pointer.points_to = type;
2893 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2895 type = pointer_type;
2899 case CONSTRUCT_ARRAY: {
2900 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2901 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2903 expression_t *size_expression = parsed_array->size;
2904 if(size_expression != NULL) {
2906 = create_implicit_cast(size_expression, type_size_t);
2909 array_type->base.qualifiers = parsed_array->type_qualifiers;
2910 array_type->array.element_type = type;
2911 array_type->array.is_static = parsed_array->is_static;
2912 array_type->array.is_variable = parsed_array->is_variable;
2913 array_type->array.size_expression = size_expression;
2915 if(size_expression != NULL) {
2916 if(is_constant_expression(size_expression)) {
2917 array_type->array.size_constant = true;
2918 array_type->array.size
2919 = fold_constant(size_expression);
2921 array_type->array.is_vla = true;
2925 type_t *skipped_type = skip_typeref(type);
2926 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2927 errorf(HERE, "array of void is not allowed");
2928 type = type_error_type;
2936 type_t *hashed_type = typehash_insert(type);
2937 if(hashed_type != type) {
2938 /* the function type was constructed earlier freeing it here will
2939 * destroy other types... */
2940 if(iter->kind != CONSTRUCT_FUNCTION) {
2950 static declaration_t *parse_declarator(
2951 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2953 declaration_t *const declaration = allocate_declaration_zero();
2954 declaration->declared_storage_class = specifiers->declared_storage_class;
2955 declaration->modifiers = specifiers->decl_modifiers;
2956 declaration->deprecated_string = specifiers->deprecated_string;
2957 declaration->get_property_sym = specifiers->get_property_sym;
2958 declaration->put_property_sym = specifiers->put_property_sym;
2959 declaration->is_inline = specifiers->is_inline;
2961 declaration->storage_class = specifiers->declared_storage_class;
2962 if(declaration->storage_class == STORAGE_CLASS_NONE
2963 && scope != global_scope) {
2964 declaration->storage_class = STORAGE_CLASS_AUTO;
2967 if(specifiers->alignment != 0) {
2968 /* TODO: add checks here */
2969 declaration->alignment = specifiers->alignment;
2972 construct_type_t *construct_type
2973 = parse_inner_declarator(declaration, may_be_abstract);
2974 type_t *const type = specifiers->type;
2975 declaration->type = construct_declarator_type(construct_type, type);
2977 if(construct_type != NULL) {
2978 obstack_free(&temp_obst, construct_type);
2984 static type_t *parse_abstract_declarator(type_t *base_type)
2986 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2988 type_t *result = construct_declarator_type(construct_type, base_type);
2989 if(construct_type != NULL) {
2990 obstack_free(&temp_obst, construct_type);
2996 static declaration_t *append_declaration(declaration_t* const declaration)
2998 if (last_declaration != NULL) {
2999 last_declaration->next = declaration;
3001 scope->declarations = declaration;
3003 last_declaration = declaration;
3008 * Check if the declaration of main is suspicious. main should be a
3009 * function with external linkage, returning int, taking either zero
3010 * arguments, two, or three arguments of appropriate types, ie.
3012 * int main([ int argc, char **argv [, char **env ] ]).
3014 * @param decl the declaration to check
3015 * @param type the function type of the declaration
3017 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3019 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3020 warningf(decl->source_position, "'main' is normally a non-static function");
3022 if (skip_typeref(func_type->return_type) != type_int) {
3023 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3025 const function_parameter_t *parm = func_type->parameters;
3027 type_t *const first_type = parm->type;
3028 if (!types_compatible(skip_typeref(first_type), type_int)) {
3029 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3033 type_t *const second_type = parm->type;
3034 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3035 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3039 type_t *const third_type = parm->type;
3040 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3041 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3045 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3049 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3055 * Check if a symbol is the equal to "main".
3057 static bool is_sym_main(const symbol_t *const sym)
3059 return strcmp(sym->string, "main") == 0;
3062 static declaration_t *internal_record_declaration(
3063 declaration_t *const declaration,
3064 const bool is_function_definition)
3066 const symbol_t *const symbol = declaration->symbol;
3067 const namespace_t namespc = (namespace_t)declaration->namespc;
3069 type_t *const orig_type = declaration->type;
3070 type_t *const type = skip_typeref(orig_type);
3071 if (is_type_function(type) &&
3072 type->function.unspecified_parameters &&
3073 warning.strict_prototypes) {
3074 warningf(declaration->source_position,
3075 "function declaration '%#T' is not a prototype",
3076 orig_type, declaration->symbol);
3079 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3080 check_type_of_main(declaration, &type->function);
3083 assert(declaration->symbol != NULL);
3084 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3086 assert(declaration != previous_declaration);
3087 if (previous_declaration != NULL) {
3088 if (previous_declaration->parent_scope == scope) {
3089 /* can happen for K&R style declarations */
3090 if(previous_declaration->type == NULL) {
3091 previous_declaration->type = declaration->type;
3094 const type_t *prev_type = skip_typeref(previous_declaration->type);
3095 if (!types_compatible(type, prev_type)) {
3096 errorf(declaration->source_position,
3097 "declaration '%#T' is incompatible with "
3098 "previous declaration '%#T'",
3099 orig_type, symbol, previous_declaration->type, symbol);
3100 errorf(previous_declaration->source_position,
3101 "previous declaration of '%Y' was here", symbol);
3103 unsigned old_storage_class = previous_declaration->storage_class;
3104 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3105 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3106 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3107 return previous_declaration;
3110 unsigned new_storage_class = declaration->storage_class;
3112 if(is_type_incomplete(prev_type)) {
3113 previous_declaration->type = type;
3117 /* pretend no storage class means extern for function
3118 * declarations (except if the previous declaration is neither
3119 * none nor extern) */
3120 if (is_type_function(type)) {
3121 switch (old_storage_class) {
3122 case STORAGE_CLASS_NONE:
3123 old_storage_class = STORAGE_CLASS_EXTERN;
3125 case STORAGE_CLASS_EXTERN:
3126 if (is_function_definition) {
3127 if (warning.missing_prototypes &&
3128 prev_type->function.unspecified_parameters &&
3129 !is_sym_main(symbol)) {
3130 warningf(declaration->source_position,
3131 "no previous prototype for '%#T'",
3134 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3135 new_storage_class = STORAGE_CLASS_EXTERN;
3143 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3144 new_storage_class == STORAGE_CLASS_EXTERN) {
3145 warn_redundant_declaration:
3146 if (warning.redundant_decls) {
3147 warningf(declaration->source_position,
3148 "redundant declaration for '%Y'", symbol);
3149 warningf(previous_declaration->source_position,
3150 "previous declaration of '%Y' was here",
3153 } else if (current_function == NULL) {
3154 if (old_storage_class != STORAGE_CLASS_STATIC &&
3155 new_storage_class == STORAGE_CLASS_STATIC) {
3156 errorf(declaration->source_position,
3157 "static declaration of '%Y' follows non-static declaration",
3159 errorf(previous_declaration->source_position,
3160 "previous declaration of '%Y' was here", symbol);
3162 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3163 goto warn_redundant_declaration;
3165 if (new_storage_class == STORAGE_CLASS_NONE) {
3166 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3167 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3171 if (old_storage_class == new_storage_class) {
3172 errorf(declaration->source_position,
3173 "redeclaration of '%Y'", symbol);
3175 errorf(declaration->source_position,
3176 "redeclaration of '%Y' with different linkage",
3179 errorf(previous_declaration->source_position,
3180 "previous declaration of '%Y' was here", symbol);
3183 return previous_declaration;
3185 } else if (is_function_definition) {
3186 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3187 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3188 warningf(declaration->source_position,
3189 "no previous prototype for '%#T'", orig_type, symbol);
3190 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3191 warningf(declaration->source_position,
3192 "no previous declaration for '%#T'", orig_type,
3196 } else if (warning.missing_declarations &&
3197 scope == global_scope &&
3198 !is_type_function(type) && (
3199 declaration->storage_class == STORAGE_CLASS_NONE ||
3200 declaration->storage_class == STORAGE_CLASS_THREAD
3202 warningf(declaration->source_position,
3203 "no previous declaration for '%#T'", orig_type, symbol);
3206 assert(declaration->parent_scope == NULL);
3207 assert(scope != NULL);
3209 declaration->parent_scope = scope;
3211 environment_push(declaration);
3212 return append_declaration(declaration);
3215 static declaration_t *record_declaration(declaration_t *declaration)
3217 return internal_record_declaration(declaration, false);
3220 static declaration_t *record_function_definition(declaration_t *declaration)
3222 return internal_record_declaration(declaration, true);
3225 static void parser_error_multiple_definition(declaration_t *declaration,
3226 const source_position_t source_position)
3228 errorf(source_position, "multiple definition of symbol '%Y'",
3229 declaration->symbol);
3230 errorf(declaration->source_position,
3231 "this is the location of the previous definition.");
3234 static bool is_declaration_specifier(const token_t *token,
3235 bool only_type_specifiers)
3237 switch(token->type) {
3241 return is_typedef_symbol(token->v.symbol);
3243 case T___extension__:
3246 return !only_type_specifiers;
3253 static void parse_init_declarator_rest(declaration_t *declaration)
3257 type_t *orig_type = declaration->type;
3258 type_t *type = skip_typeref(orig_type);
3260 if(declaration->init.initializer != NULL) {
3261 parser_error_multiple_definition(declaration, token.source_position);
3264 bool must_be_constant = false;
3265 if(declaration->storage_class == STORAGE_CLASS_STATIC
3266 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3267 || declaration->parent_scope == global_scope) {
3268 must_be_constant = true;
3271 parse_initializer_env_t env;
3272 env.type = orig_type;
3273 env.must_be_constant = must_be_constant;
3274 env.declaration = declaration;
3276 initializer_t *initializer = parse_initializer(&env);
3278 if(env.type != orig_type) {
3279 orig_type = env.type;
3280 type = skip_typeref(orig_type);
3281 declaration->type = env.type;
3284 if(is_type_function(type)) {
3285 errorf(declaration->source_position,
3286 "initializers not allowed for function types at declator '%Y' (type '%T')",
3287 declaration->symbol, orig_type);
3289 declaration->init.initializer = initializer;
3293 /* parse rest of a declaration without any declarator */
3294 static void parse_anonymous_declaration_rest(
3295 const declaration_specifiers_t *specifiers,
3296 parsed_declaration_func finished_declaration)
3300 declaration_t *const declaration = allocate_declaration_zero();
3301 declaration->type = specifiers->type;
3302 declaration->declared_storage_class = specifiers->declared_storage_class;
3303 declaration->source_position = specifiers->source_position;
3304 declaration->modifiers = specifiers->decl_modifiers;
3306 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3307 warningf(declaration->source_position, "useless storage class in empty declaration");
3309 declaration->storage_class = STORAGE_CLASS_NONE;
3311 type_t *type = declaration->type;
3312 switch (type->kind) {
3313 case TYPE_COMPOUND_STRUCT:
3314 case TYPE_COMPOUND_UNION: {
3315 if (type->compound.declaration->symbol == NULL) {
3316 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3325 warningf(declaration->source_position, "empty declaration");
3329 finished_declaration(declaration);
3332 static void parse_declaration_rest(declaration_t *ndeclaration,
3333 const declaration_specifiers_t *specifiers,
3334 parsed_declaration_func finished_declaration)
3336 add_anchor_token(';');
3337 add_anchor_token('=');
3338 add_anchor_token(',');
3340 declaration_t *declaration = finished_declaration(ndeclaration);
3342 type_t *orig_type = declaration->type;
3343 type_t *type = skip_typeref(orig_type);
3345 if (type->kind != TYPE_FUNCTION &&
3346 declaration->is_inline &&
3347 is_type_valid(type)) {
3348 warningf(declaration->source_position,
3349 "variable '%Y' declared 'inline'\n", declaration->symbol);
3352 if(token.type == '=') {
3353 parse_init_declarator_rest(declaration);
3356 if(token.type != ',')
3360 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3365 rem_anchor_token(';');
3366 rem_anchor_token('=');
3367 rem_anchor_token(',');
3370 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3372 symbol_t *symbol = declaration->symbol;
3373 if(symbol == NULL) {
3374 errorf(HERE, "anonymous declaration not valid as function parameter");
3377 namespace_t namespc = (namespace_t) declaration->namespc;
3378 if(namespc != NAMESPACE_NORMAL) {
3379 return record_declaration(declaration);
3382 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3383 if(previous_declaration == NULL ||
3384 previous_declaration->parent_scope != scope) {
3385 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3390 if(previous_declaration->type == NULL) {
3391 previous_declaration->type = declaration->type;
3392 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3393 previous_declaration->storage_class = declaration->storage_class;
3394 previous_declaration->parent_scope = scope;
3395 return previous_declaration;
3397 return record_declaration(declaration);
3401 static void parse_declaration(parsed_declaration_func finished_declaration)
3403 declaration_specifiers_t specifiers;
3404 memset(&specifiers, 0, sizeof(specifiers));
3405 parse_declaration_specifiers(&specifiers);
3407 if(token.type == ';') {
3408 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3410 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3411 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3415 static void parse_kr_declaration_list(declaration_t *declaration)
3417 type_t *type = skip_typeref(declaration->type);
3418 if(!is_type_function(type))
3421 if(!type->function.kr_style_parameters)
3424 /* push function parameters */
3425 int top = environment_top();
3426 scope_t *last_scope = scope;
3427 set_scope(&declaration->scope);
3429 declaration_t *parameter = declaration->scope.declarations;
3430 for( ; parameter != NULL; parameter = parameter->next) {
3431 assert(parameter->parent_scope == NULL);
3432 parameter->parent_scope = scope;
3433 environment_push(parameter);
3436 /* parse declaration list */
3437 while(is_declaration_specifier(&token, false)) {
3438 parse_declaration(finished_kr_declaration);
3441 /* pop function parameters */
3442 assert(scope == &declaration->scope);
3443 set_scope(last_scope);
3444 environment_pop_to(top);
3446 /* update function type */
3447 type_t *new_type = duplicate_type(type);
3448 new_type->function.kr_style_parameters = false;
3450 function_parameter_t *parameters = NULL;
3451 function_parameter_t *last_parameter = NULL;
3453 declaration_t *parameter_declaration = declaration->scope.declarations;
3454 for( ; parameter_declaration != NULL;
3455 parameter_declaration = parameter_declaration->next) {
3456 type_t *parameter_type = parameter_declaration->type;
3457 if(parameter_type == NULL) {
3459 errorf(HERE, "no type specified for function parameter '%Y'",
3460 parameter_declaration->symbol);
3462 if (warning.implicit_int) {
3463 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3464 parameter_declaration->symbol);
3466 parameter_type = type_int;
3467 parameter_declaration->type = parameter_type;
3471 semantic_parameter(parameter_declaration);
3472 parameter_type = parameter_declaration->type;
3474 function_parameter_t *function_parameter
3475 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3476 memset(function_parameter, 0, sizeof(function_parameter[0]));
3478 function_parameter->type = parameter_type;
3479 if(last_parameter != NULL) {
3480 last_parameter->next = function_parameter;
3482 parameters = function_parameter;
3484 last_parameter = function_parameter;
3486 new_type->function.parameters = parameters;
3488 type = typehash_insert(new_type);
3489 if(type != new_type) {
3490 obstack_free(type_obst, new_type);
3493 declaration->type = type;
3496 static bool first_err = true;
3499 * When called with first_err set, prints the name of the current function,
3502 static void print_in_function(void) {
3505 diagnosticf("%s: In function '%Y':\n",
3506 current_function->source_position.input_name,
3507 current_function->symbol);
3512 * Check if all labels are defined in the current function.
3513 * Check if all labels are used in the current function.
3515 static void check_labels(void)
3517 for (const goto_statement_t *goto_statement = goto_first;
3518 goto_statement != NULL;
3519 goto_statement = goto_statement->next) {
3520 declaration_t *label = goto_statement->label;
3523 if (label->source_position.input_name == NULL) {
3524 print_in_function();
3525 errorf(goto_statement->base.source_position,
3526 "label '%Y' used but not defined", label->symbol);
3529 goto_first = goto_last = NULL;
3531 if (warning.unused_label) {
3532 for (const label_statement_t *label_statement = label_first;
3533 label_statement != NULL;
3534 label_statement = label_statement->next) {
3535 const declaration_t *label = label_statement->label;
3537 if (! label->used) {
3538 print_in_function();
3539 warningf(label_statement->base.source_position,
3540 "label '%Y' defined but not used", label->symbol);
3544 label_first = label_last = NULL;
3548 * Check declarations of current_function for unused entities.
3550 static void check_declarations(void)
3552 if (warning.unused_parameter) {
3553 const scope_t *scope = ¤t_function->scope;
3555 const declaration_t *parameter = scope->declarations;
3556 for (; parameter != NULL; parameter = parameter->next) {
3557 if (! parameter->used) {
3558 print_in_function();
3559 warningf(parameter->source_position,
3560 "unused parameter '%Y'", parameter->symbol);
3564 if (warning.unused_variable) {
3568 static void parse_external_declaration(void)
3570 /* function-definitions and declarations both start with declaration
3572 declaration_specifiers_t specifiers;
3573 memset(&specifiers, 0, sizeof(specifiers));
3575 add_anchor_token(';');
3576 parse_declaration_specifiers(&specifiers);
3577 rem_anchor_token(';');
3579 /* must be a declaration */
3580 if(token.type == ';') {
3581 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3585 add_anchor_token(',');
3586 add_anchor_token('=');
3587 rem_anchor_token(';');
3589 /* declarator is common to both function-definitions and declarations */
3590 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3592 rem_anchor_token(',');
3593 rem_anchor_token('=');
3594 rem_anchor_token(';');
3596 /* must be a declaration */
3597 if(token.type == ',' || token.type == '=' || token.type == ';') {
3598 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3602 /* must be a function definition */
3603 parse_kr_declaration_list(ndeclaration);
3605 if(token.type != '{') {
3606 parse_error_expected("while parsing function definition", '{', 0);
3607 eat_until_matching_token(';');
3611 type_t *type = ndeclaration->type;
3613 /* note that we don't skip typerefs: the standard doesn't allow them here
3614 * (so we can't use is_type_function here) */
3615 if(type->kind != TYPE_FUNCTION) {
3616 if (is_type_valid(type)) {
3617 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3618 type, ndeclaration->symbol);
3624 /* § 6.7.5.3 (14) a function definition with () means no
3625 * parameters (and not unspecified parameters) */
3626 if(type->function.unspecified_parameters) {
3627 type_t *duplicate = duplicate_type(type);
3628 duplicate->function.unspecified_parameters = false;
3630 type = typehash_insert(duplicate);
3631 if(type != duplicate) {
3632 obstack_free(type_obst, duplicate);
3634 ndeclaration->type = type;
3637 declaration_t *const declaration = record_function_definition(ndeclaration);
3638 if(ndeclaration != declaration) {
3639 declaration->scope = ndeclaration->scope;
3641 type = skip_typeref(declaration->type);
3643 /* push function parameters and switch scope */
3644 int top = environment_top();
3645 scope_t *last_scope = scope;
3646 set_scope(&declaration->scope);
3648 declaration_t *parameter = declaration->scope.declarations;
3649 for( ; parameter != NULL; parameter = parameter->next) {
3650 if(parameter->parent_scope == &ndeclaration->scope) {
3651 parameter->parent_scope = scope;
3653 assert(parameter->parent_scope == NULL
3654 || parameter->parent_scope == scope);
3655 parameter->parent_scope = scope;
3656 environment_push(parameter);
3659 if(declaration->init.statement != NULL) {
3660 parser_error_multiple_definition(declaration, token.source_position);
3662 goto end_of_parse_external_declaration;
3664 /* parse function body */
3665 int label_stack_top = label_top();
3666 declaration_t *old_current_function = current_function;
3667 current_function = declaration;
3669 declaration->init.statement = parse_compound_statement();
3672 check_declarations();
3674 assert(current_function == declaration);
3675 current_function = old_current_function;
3676 label_pop_to(label_stack_top);
3679 end_of_parse_external_declaration:
3680 assert(scope == &declaration->scope);
3681 set_scope(last_scope);
3682 environment_pop_to(top);
3685 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3686 source_position_t source_position)
3688 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3689 type->bitfield.base = base;
3690 type->bitfield.size = size;
3695 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3698 declaration_t *iter = compound_declaration->scope.declarations;
3699 for( ; iter != NULL; iter = iter->next) {
3700 if(iter->namespc != NAMESPACE_NORMAL)
3703 if(iter->symbol == NULL) {
3704 type_t *type = skip_typeref(iter->type);
3705 if(is_type_compound(type)) {
3706 declaration_t *result
3707 = find_compound_entry(type->compound.declaration, symbol);
3714 if(iter->symbol == symbol) {
3722 static void parse_compound_declarators(declaration_t *struct_declaration,
3723 const declaration_specifiers_t *specifiers)
3725 declaration_t *last_declaration = struct_declaration->scope.declarations;
3726 if(last_declaration != NULL) {
3727 while(last_declaration->next != NULL) {
3728 last_declaration = last_declaration->next;
3733 declaration_t *declaration;
3735 if(token.type == ':') {
3736 source_position_t source_position = HERE;
3739 type_t *base_type = specifiers->type;
3740 expression_t *size = parse_constant_expression();
3742 if(!is_type_integer(skip_typeref(base_type))) {
3743 errorf(HERE, "bitfield base type '%T' is not an integer type",
3747 type_t *type = make_bitfield_type(base_type, size, source_position);
3749 declaration = allocate_declaration_zero();
3750 declaration->namespc = NAMESPACE_NORMAL;
3751 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3752 declaration->storage_class = STORAGE_CLASS_NONE;
3753 declaration->source_position = source_position;
3754 declaration->modifiers = specifiers->decl_modifiers;
3755 declaration->type = type;
3757 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3759 type_t *orig_type = declaration->type;
3760 type_t *type = skip_typeref(orig_type);
3762 if(token.type == ':') {
3763 source_position_t source_position = HERE;
3765 expression_t *size = parse_constant_expression();
3767 if(!is_type_integer(type)) {
3768 errorf(HERE, "bitfield base type '%T' is not an "
3769 "integer type", orig_type);
3772 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3773 declaration->type = bitfield_type;
3775 /* TODO we ignore arrays for now... what is missing is a check
3776 * that they're at the end of the struct */
3777 if(is_type_incomplete(type) && !is_type_array(type)) {
3779 "compound member '%Y' has incomplete type '%T'",
3780 declaration->symbol, orig_type);
3781 } else if(is_type_function(type)) {
3782 errorf(HERE, "compound member '%Y' must not have function "
3783 "type '%T'", declaration->symbol, orig_type);
3788 /* make sure we don't define a symbol multiple times */
3789 symbol_t *symbol = declaration->symbol;
3790 if(symbol != NULL) {
3791 declaration_t *prev_decl
3792 = find_compound_entry(struct_declaration, symbol);
3794 if(prev_decl != NULL) {
3795 assert(prev_decl->symbol == symbol);
3796 errorf(declaration->source_position,
3797 "multiple declarations of symbol '%Y'", symbol);
3798 errorf(prev_decl->source_position,
3799 "previous declaration of '%Y' was here", symbol);
3803 /* append declaration */
3804 if(last_declaration != NULL) {
3805 last_declaration->next = declaration;
3807 struct_declaration->scope.declarations = declaration;
3809 last_declaration = declaration;
3811 if(token.type != ',')
3821 static void parse_compound_type_entries(declaration_t *compound_declaration)
3824 add_anchor_token('}');
3826 while(token.type != '}' && token.type != T_EOF) {
3827 declaration_specifiers_t specifiers;
3828 memset(&specifiers, 0, sizeof(specifiers));
3829 parse_declaration_specifiers(&specifiers);
3831 parse_compound_declarators(compound_declaration, &specifiers);
3833 rem_anchor_token('}');
3835 if(token.type == T_EOF) {
3836 errorf(HERE, "EOF while parsing struct");
3841 static type_t *parse_typename(void)
3843 declaration_specifiers_t specifiers;
3844 memset(&specifiers, 0, sizeof(specifiers));
3845 parse_declaration_specifiers(&specifiers);
3846 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3847 /* TODO: improve error message, user does probably not know what a
3848 * storage class is...
3850 errorf(HERE, "typename may not have a storage class");
3853 type_t *result = parse_abstract_declarator(specifiers.type);
3861 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3862 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3863 expression_t *left);
3865 typedef struct expression_parser_function_t expression_parser_function_t;
3866 struct expression_parser_function_t {
3867 unsigned precedence;
3868 parse_expression_function parser;
3869 unsigned infix_precedence;
3870 parse_expression_infix_function infix_parser;
3873 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3876 * Creates a new invalid expression.
3878 static expression_t *create_invalid_expression(void)
3880 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3881 expression->base.source_position = token.source_position;
3886 * Prints an error message if an expression was expected but not read
3888 static expression_t *expected_expression_error(void)
3890 /* skip the error message if the error token was read */
3891 if (token.type != T_ERROR) {
3892 errorf(HERE, "expected expression, got token '%K'", &token);
3896 return create_invalid_expression();
3900 * Parse a string constant.
3902 static expression_t *parse_string_const(void)
3905 if (token.type == T_STRING_LITERAL) {
3906 string_t res = token.v.string;
3908 while (token.type == T_STRING_LITERAL) {
3909 res = concat_strings(&res, &token.v.string);
3912 if (token.type != T_WIDE_STRING_LITERAL) {
3913 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3914 /* note: that we use type_char_ptr here, which is already the
3915 * automatic converted type. revert_automatic_type_conversion
3916 * will construct the array type */
3917 cnst->base.type = type_char_ptr;
3918 cnst->string.value = res;
3922 wres = concat_string_wide_string(&res, &token.v.wide_string);
3924 wres = token.v.wide_string;
3929 switch (token.type) {
3930 case T_WIDE_STRING_LITERAL:
3931 wres = concat_wide_strings(&wres, &token.v.wide_string);
3934 case T_STRING_LITERAL:
3935 wres = concat_wide_string_string(&wres, &token.v.string);
3939 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3940 cnst->base.type = type_wchar_t_ptr;
3941 cnst->wide_string.value = wres;
3950 * Parse an integer constant.
3952 static expression_t *parse_int_const(void)
3954 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3955 cnst->base.source_position = HERE;
3956 cnst->base.type = token.datatype;
3957 cnst->conste.v.int_value = token.v.intvalue;
3965 * Parse a character constant.
3967 static expression_t *parse_character_constant(void)
3969 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3971 cnst->base.source_position = HERE;
3972 cnst->base.type = token.datatype;
3973 cnst->conste.v.character = token.v.string;
3975 if (cnst->conste.v.character.size != 1) {
3976 if (warning.multichar && (c_mode & _GNUC)) {
3978 warningf(HERE, "multi-character character constant");
3980 errorf(HERE, "more than 1 characters in character constant");
3989 * Parse a wide character constant.
3991 static expression_t *parse_wide_character_constant(void)
3993 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3995 cnst->base.source_position = HERE;
3996 cnst->base.type = token.datatype;
3997 cnst->conste.v.wide_character = token.v.wide_string;
3999 if (cnst->conste.v.wide_character.size != 1) {
4000 if (warning.multichar && (c_mode & _GNUC)) {
4002 warningf(HERE, "multi-character character constant");
4004 errorf(HERE, "more than 1 characters in character constant");
4013 * Parse a float constant.
4015 static expression_t *parse_float_const(void)
4017 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4018 cnst->base.type = token.datatype;
4019 cnst->conste.v.float_value = token.v.floatvalue;
4026 static declaration_t *create_implicit_function(symbol_t *symbol,
4027 const source_position_t source_position)
4029 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4030 ntype->function.return_type = type_int;
4031 ntype->function.unspecified_parameters = true;
4033 type_t *type = typehash_insert(ntype);
4038 declaration_t *const declaration = allocate_declaration_zero();
4039 declaration->storage_class = STORAGE_CLASS_EXTERN;
4040 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4041 declaration->type = type;
4042 declaration->symbol = symbol;
4043 declaration->source_position = source_position;
4044 declaration->parent_scope = global_scope;
4046 scope_t *old_scope = scope;
4047 set_scope(global_scope);
4049 environment_push(declaration);
4050 /* prepends the declaration to the global declarations list */
4051 declaration->next = scope->declarations;
4052 scope->declarations = declaration;
4054 assert(scope == global_scope);
4055 set_scope(old_scope);
4061 * Creates a return_type (func)(argument_type) function type if not
4064 * @param return_type the return type
4065 * @param argument_type the argument type
4067 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4069 function_parameter_t *parameter
4070 = obstack_alloc(type_obst, sizeof(parameter[0]));
4071 memset(parameter, 0, sizeof(parameter[0]));
4072 parameter->type = argument_type;
4074 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4075 type->function.return_type = return_type;
4076 type->function.parameters = parameter;
4078 type_t *result = typehash_insert(type);
4079 if(result != type) {
4087 * Creates a function type for some function like builtins.
4089 * @param symbol the symbol describing the builtin
4091 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4093 switch(symbol->ID) {
4094 case T___builtin_alloca:
4095 return make_function_1_type(type_void_ptr, type_size_t);
4096 case T___builtin_nan:
4097 return make_function_1_type(type_double, type_char_ptr);
4098 case T___builtin_nanf:
4099 return make_function_1_type(type_float, type_char_ptr);
4100 case T___builtin_nand:
4101 return make_function_1_type(type_long_double, type_char_ptr);
4102 case T___builtin_va_end:
4103 return make_function_1_type(type_void, type_valist);
4105 internal_errorf(HERE, "not implemented builtin symbol found");
4110 * Performs automatic type cast as described in § 6.3.2.1.
4112 * @param orig_type the original type
4114 static type_t *automatic_type_conversion(type_t *orig_type)
4116 type_t *type = skip_typeref(orig_type);
4117 if(is_type_array(type)) {
4118 array_type_t *array_type = &type->array;
4119 type_t *element_type = array_type->element_type;
4120 unsigned qualifiers = array_type->type.qualifiers;
4122 return make_pointer_type(element_type, qualifiers);
4125 if(is_type_function(type)) {
4126 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4133 * reverts the automatic casts of array to pointer types and function
4134 * to function-pointer types as defined § 6.3.2.1
4136 type_t *revert_automatic_type_conversion(const expression_t *expression)
4138 switch (expression->kind) {
4139 case EXPR_REFERENCE: return expression->reference.declaration->type;
4140 case EXPR_SELECT: return expression->select.compound_entry->type;
4142 case EXPR_UNARY_DEREFERENCE: {
4143 const expression_t *const value = expression->unary.value;
4144 type_t *const type = skip_typeref(value->base.type);
4145 assert(is_type_pointer(type));
4146 return type->pointer.points_to;
4149 case EXPR_BUILTIN_SYMBOL:
4150 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4152 case EXPR_ARRAY_ACCESS: {
4153 const expression_t *array_ref = expression->array_access.array_ref;
4154 type_t *type_left = skip_typeref(array_ref->base.type);
4155 if (!is_type_valid(type_left))
4157 assert(is_type_pointer(type_left));
4158 return type_left->pointer.points_to;
4161 case EXPR_STRING_LITERAL: {
4162 size_t size = expression->string.value.size;
4163 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4166 case EXPR_WIDE_STRING_LITERAL: {
4167 size_t size = expression->wide_string.value.size;
4168 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4171 case EXPR_COMPOUND_LITERAL:
4172 return expression->compound_literal.type;
4177 return expression->base.type;
4180 static expression_t *parse_reference(void)
4182 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4184 reference_expression_t *ref = &expression->reference;
4185 ref->symbol = token.v.symbol;
4187 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4189 source_position_t source_position = token.source_position;
4192 if(declaration == NULL) {
4193 if (! strict_mode && token.type == '(') {
4194 /* an implicitly defined function */
4195 if (warning.implicit_function_declaration) {
4196 warningf(HERE, "implicit declaration of function '%Y'",
4200 declaration = create_implicit_function(ref->symbol,
4203 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4204 return create_invalid_expression();
4208 type_t *type = declaration->type;
4210 /* we always do the auto-type conversions; the & and sizeof parser contains
4211 * code to revert this! */
4212 type = automatic_type_conversion(type);
4214 ref->declaration = declaration;
4215 ref->base.type = type;
4217 /* this declaration is used */
4218 declaration->used = true;
4223 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4227 /* TODO check if explicit cast is allowed and issue warnings/errors */
4230 static expression_t *parse_compound_literal(type_t *type)
4232 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4234 parse_initializer_env_t env;
4236 env.declaration = NULL;
4237 env.must_be_constant = false;
4238 initializer_t *initializer = parse_initializer(&env);
4241 expression->compound_literal.initializer = initializer;
4242 expression->compound_literal.type = type;
4243 expression->base.type = automatic_type_conversion(type);
4249 * Parse a cast expression.
4251 static expression_t *parse_cast(void)
4253 source_position_t source_position = token.source_position;
4255 type_t *type = parse_typename();
4257 /* matching add_anchor_token() is at call site */
4258 rem_anchor_token(')');
4261 if(token.type == '{') {
4262 return parse_compound_literal(type);
4265 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4266 cast->base.source_position = source_position;
4268 expression_t *value = parse_sub_expression(20);
4270 check_cast_allowed(value, type);
4272 cast->base.type = type;
4273 cast->unary.value = value;
4277 return create_invalid_expression();
4281 * Parse a statement expression.
4283 static expression_t *parse_statement_expression(void)
4285 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4287 statement_t *statement = parse_compound_statement();
4288 expression->statement.statement = statement;
4289 expression->base.source_position = statement->base.source_position;
4291 /* find last statement and use its type */
4292 type_t *type = type_void;
4293 const statement_t *stmt = statement->compound.statements;
4295 while (stmt->base.next != NULL)
4296 stmt = stmt->base.next;
4298 if (stmt->kind == STATEMENT_EXPRESSION) {
4299 type = stmt->expression.expression->base.type;
4302 warningf(expression->base.source_position, "empty statement expression ({})");
4304 expression->base.type = type;
4310 return create_invalid_expression();
4314 * Parse a braced expression.
4316 static expression_t *parse_brace_expression(void)
4319 add_anchor_token(')');
4321 switch(token.type) {
4323 /* gcc extension: a statement expression */
4324 return parse_statement_expression();
4328 return parse_cast();
4330 if(is_typedef_symbol(token.v.symbol)) {
4331 return parse_cast();
4335 expression_t *result = parse_expression();
4336 rem_anchor_token(')');
4341 return create_invalid_expression();
4344 static expression_t *parse_function_keyword(void)
4349 if (current_function == NULL) {
4350 errorf(HERE, "'__func__' used outside of a function");
4353 expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4354 expression->base.type = type_char_ptr;
4359 static expression_t *parse_pretty_function_keyword(void)
4361 eat(T___PRETTY_FUNCTION__);
4364 if (current_function == NULL) {
4365 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4368 expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4369 expression->base.type = type_char_ptr;
4374 static designator_t *parse_designator(void)
4376 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4377 result->source_position = HERE;
4379 if(token.type != T_IDENTIFIER) {
4380 parse_error_expected("while parsing member designator",
4384 result->symbol = token.v.symbol;
4387 designator_t *last_designator = result;
4389 if(token.type == '.') {
4391 if(token.type != T_IDENTIFIER) {
4392 parse_error_expected("while parsing member designator",
4396 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4397 designator->source_position = HERE;
4398 designator->symbol = token.v.symbol;
4401 last_designator->next = designator;
4402 last_designator = designator;
4405 if(token.type == '[') {
4407 add_anchor_token(']');
4408 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4409 designator->source_position = HERE;
4410 designator->array_index = parse_expression();
4411 rem_anchor_token(']');
4413 if(designator->array_index == NULL) {
4417 last_designator->next = designator;
4418 last_designator = designator;
4430 * Parse the __builtin_offsetof() expression.
4432 static expression_t *parse_offsetof(void)
4434 eat(T___builtin_offsetof);
4436 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4437 expression->base.type = type_size_t;
4440 add_anchor_token(',');
4441 type_t *type = parse_typename();
4442 rem_anchor_token(',');
4444 add_anchor_token(')');
4445 designator_t *designator = parse_designator();
4446 rem_anchor_token(')');
4449 expression->offsetofe.type = type;
4450 expression->offsetofe.designator = designator;
4453 memset(&path, 0, sizeof(path));
4454 path.top_type = type;
4455 path.path = NEW_ARR_F(type_path_entry_t, 0);
4457 descend_into_subtype(&path);
4459 if(!walk_designator(&path, designator, true)) {
4460 return create_invalid_expression();
4463 DEL_ARR_F(path.path);
4467 return create_invalid_expression();
4471 * Parses a _builtin_va_start() expression.
4473 static expression_t *parse_va_start(void)
4475 eat(T___builtin_va_start);
4477 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4480 add_anchor_token(',');
4481 expression->va_starte.ap = parse_assignment_expression();
4482 rem_anchor_token(',');
4484 expression_t *const expr = parse_assignment_expression();
4485 if (expr->kind == EXPR_REFERENCE) {
4486 declaration_t *const decl = expr->reference.declaration;
4488 return create_invalid_expression();
4489 if (decl->parent_scope == ¤t_function->scope &&
4490 decl->next == NULL) {
4491 expression->va_starte.parameter = decl;
4496 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4498 return create_invalid_expression();
4502 * Parses a _builtin_va_arg() expression.
4504 static expression_t *parse_va_arg(void)
4506 eat(T___builtin_va_arg);
4508 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4511 expression->va_arge.ap = parse_assignment_expression();
4513 expression->base.type = parse_typename();
4518 return create_invalid_expression();
4521 static expression_t *parse_builtin_symbol(void)
4523 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4525 symbol_t *symbol = token.v.symbol;
4527 expression->builtin_symbol.symbol = symbol;
4530 type_t *type = get_builtin_symbol_type(symbol);
4531 type = automatic_type_conversion(type);
4533 expression->base.type = type;
4538 * Parses a __builtin_constant() expression.
4540 static expression_t *parse_builtin_constant(void)
4542 eat(T___builtin_constant_p);
4544 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4547 add_anchor_token(')');
4548 expression->builtin_constant.value = parse_assignment_expression();
4549 rem_anchor_token(')');
4551 expression->base.type = type_int;
4555 return create_invalid_expression();
4559 * Parses a __builtin_prefetch() expression.
4561 static expression_t *parse_builtin_prefetch(void)
4563 eat(T___builtin_prefetch);
4565 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4568 add_anchor_token(')');
4569 expression->builtin_prefetch.adr = parse_assignment_expression();
4570 if (token.type == ',') {
4572 expression->builtin_prefetch.rw = parse_assignment_expression();
4574 if (token.type == ',') {
4576 expression->builtin_prefetch.locality = parse_assignment_expression();
4578 rem_anchor_token(')');
4580 expression->base.type = type_void;
4584 return create_invalid_expression();
4588 * Parses a __builtin_is_*() compare expression.
4590 static expression_t *parse_compare_builtin(void)
4592 expression_t *expression;
4594 switch(token.type) {
4595 case T___builtin_isgreater:
4596 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4598 case T___builtin_isgreaterequal:
4599 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4601 case T___builtin_isless:
4602 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4604 case T___builtin_islessequal:
4605 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4607 case T___builtin_islessgreater:
4608 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4610 case T___builtin_isunordered:
4611 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4614 internal_errorf(HERE, "invalid compare builtin found");
4617 expression->base.source_position = HERE;
4621 expression->binary.left = parse_assignment_expression();
4623 expression->binary.right = parse_assignment_expression();
4626 type_t *const orig_type_left = expression->binary.left->base.type;
4627 type_t *const orig_type_right = expression->binary.right->base.type;
4629 type_t *const type_left = skip_typeref(orig_type_left);
4630 type_t *const type_right = skip_typeref(orig_type_right);
4631 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4632 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4633 type_error_incompatible("invalid operands in comparison",
4634 expression->base.source_position, orig_type_left, orig_type_right);
4637 semantic_comparison(&expression->binary);
4642 return create_invalid_expression();
4646 * Parses a __builtin_expect() expression.
4648 static expression_t *parse_builtin_expect(void)
4650 eat(T___builtin_expect);
4652 expression_t *expression
4653 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4656 expression->binary.left = parse_assignment_expression();
4658 expression->binary.right = parse_constant_expression();
4661 expression->base.type = expression->binary.left->base.type;
4665 return create_invalid_expression();
4669 * Parses a MS assume() expression.
4671 static expression_t *parse_assume(void) {
4674 expression_t *expression
4675 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4678 add_anchor_token(')');
4679 expression->unary.value = parse_assignment_expression();
4680 rem_anchor_token(')');
4683 expression->base.type = type_void;
4686 return create_invalid_expression();
4690 * Parses a primary expression.
4692 static expression_t *parse_primary_expression(void)
4694 switch (token.type) {
4695 case T_INTEGER: return parse_int_const();
4696 case T_CHARACTER_CONSTANT: return parse_character_constant();
4697 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4698 case T_FLOATINGPOINT: return parse_float_const();
4699 case T_STRING_LITERAL:
4700 case T_WIDE_STRING_LITERAL: return parse_string_const();
4701 case T_IDENTIFIER: return parse_reference();
4702 case T___FUNCTION__:
4703 case T___func__: return parse_function_keyword();
4704 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4705 case T___builtin_offsetof: return parse_offsetof();
4706 case T___builtin_va_start: return parse_va_start();
4707 case T___builtin_va_arg: return parse_va_arg();
4708 case T___builtin_expect: return parse_builtin_expect();
4709 case T___builtin_alloca:
4710 case T___builtin_nan:
4711 case T___builtin_nand:
4712 case T___builtin_nanf:
4713 case T___builtin_va_end: return parse_builtin_symbol();
4714 case T___builtin_isgreater:
4715 case T___builtin_isgreaterequal:
4716 case T___builtin_isless:
4717 case T___builtin_islessequal:
4718 case T___builtin_islessgreater:
4719 case T___builtin_isunordered: return parse_compare_builtin();
4720 case T___builtin_constant_p: return parse_builtin_constant();
4721 case T___builtin_prefetch: return parse_builtin_prefetch();
4722 case T_assume: return parse_assume();
4724 case '(': return parse_brace_expression();
4727 errorf(HERE, "unexpected token %K, expected an expression", &token);
4728 return create_invalid_expression();
4732 * Check if the expression has the character type and issue a warning then.
4734 static void check_for_char_index_type(const expression_t *expression) {
4735 type_t *const type = expression->base.type;
4736 const type_t *const base_type = skip_typeref(type);
4738 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4739 warning.char_subscripts) {
4740 warningf(expression->base.source_position,
4741 "array subscript has type '%T'", type);
4745 static expression_t *parse_array_expression(unsigned precedence,
4751 add_anchor_token(']');
4753 expression_t *inside = parse_expression();
4755 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4757 array_access_expression_t *array_access = &expression->array_access;
4759 type_t *const orig_type_left = left->base.type;
4760 type_t *const orig_type_inside = inside->base.type;
4762 type_t *const type_left = skip_typeref(orig_type_left);
4763 type_t *const type_inside = skip_typeref(orig_type_inside);
4765 type_t *return_type;
4766 if (is_type_pointer(type_left)) {
4767 return_type = type_left->pointer.points_to;
4768 array_access->array_ref = left;
4769 array_access->index = inside;
4770 check_for_char_index_type(inside);
4771 } else if (is_type_pointer(type_inside)) {
4772 return_type = type_inside->pointer.points_to;
4773 array_access->array_ref = inside;
4774 array_access->index = left;
4775 array_access->flipped = true;
4776 check_for_char_index_type(left);
4778 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4780 "array access on object with non-pointer types '%T', '%T'",
4781 orig_type_left, orig_type_inside);
4783 return_type = type_error_type;
4784 array_access->array_ref = create_invalid_expression();
4787 rem_anchor_token(']');
4788 if(token.type != ']') {
4789 parse_error_expected("Problem while parsing array access", ']', 0);
4794 return_type = automatic_type_conversion(return_type);
4795 expression->base.type = return_type;
4800 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4802 expression_t *tp_expression = allocate_expression_zero(kind);
4803 tp_expression->base.type = type_size_t;
4805 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4807 add_anchor_token(')');
4808 tp_expression->typeprop.type = parse_typename();
4809 rem_anchor_token(')');
4812 expression_t *expression = parse_sub_expression(precedence);
4813 expression->base.type = revert_automatic_type_conversion(expression);
4815 tp_expression->typeprop.type = expression->base.type;
4816 tp_expression->typeprop.tp_expression = expression;
4819 return tp_expression;
4821 return create_invalid_expression();
4824 static expression_t *parse_sizeof(unsigned precedence)
4827 return parse_typeprop(EXPR_SIZEOF, precedence);
4830 static expression_t *parse_alignof(unsigned precedence)
4833 return parse_typeprop(EXPR_SIZEOF, precedence);
4836 static expression_t *parse_select_expression(unsigned precedence,
4837 expression_t *compound)
4840 assert(token.type == '.' || token.type == T_MINUSGREATER);
4842 bool is_pointer = (token.type == T_MINUSGREATER);
4845 expression_t *select = allocate_expression_zero(EXPR_SELECT);
4846 select->select.compound = compound;
4848 if(token.type != T_IDENTIFIER) {
4849 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4852 symbol_t *symbol = token.v.symbol;
4853 select->select.symbol = symbol;
4856 type_t *const orig_type = compound->base.type;
4857 type_t *const type = skip_typeref(orig_type);
4859 type_t *type_left = type;
4861 if (!is_type_pointer(type)) {
4862 if (is_type_valid(type)) {
4863 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4865 return create_invalid_expression();
4867 type_left = type->pointer.points_to;
4869 type_left = skip_typeref(type_left);
4871 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4872 type_left->kind != TYPE_COMPOUND_UNION) {
4873 if (is_type_valid(type_left)) {
4874 errorf(HERE, "request for member '%Y' in something not a struct or "
4875 "union, but '%T'", symbol, type_left);
4877 return create_invalid_expression();
4880 declaration_t *const declaration = type_left->compound.declaration;
4882 if(!declaration->init.is_defined) {
4883 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4885 return create_invalid_expression();
4888 declaration_t *iter = find_compound_entry(declaration, symbol);
4890 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4891 return create_invalid_expression();
4894 /* we always do the auto-type conversions; the & and sizeof parser contains
4895 * code to revert this! */
4896 type_t *expression_type = automatic_type_conversion(iter->type);
4898 select->select.compound_entry = iter;
4899 select->base.type = expression_type;
4901 if(expression_type->kind == TYPE_BITFIELD) {
4902 expression_t *extract
4903 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4904 extract->unary.value = select;
4905 extract->base.type = expression_type->bitfield.base;
4914 * Parse a call expression, ie. expression '( ... )'.
4916 * @param expression the function address
4918 static expression_t *parse_call_expression(unsigned precedence,
4919 expression_t *expression)
4922 expression_t *result = allocate_expression_zero(EXPR_CALL);
4924 call_expression_t *call = &result->call;
4925 call->function = expression;
4927 type_t *const orig_type = expression->base.type;
4928 type_t *const type = skip_typeref(orig_type);
4930 function_type_t *function_type = NULL;
4931 if (is_type_pointer(type)) {
4932 type_t *const to_type = skip_typeref(type->pointer.points_to);
4934 if (is_type_function(to_type)) {
4935 function_type = &to_type->function;
4936 call->base.type = function_type->return_type;
4940 if (function_type == NULL && is_type_valid(type)) {
4941 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4944 /* parse arguments */
4946 add_anchor_token(')');
4947 add_anchor_token(',');
4949 if(token.type != ')') {
4950 call_argument_t *last_argument = NULL;
4953 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4955 argument->expression = parse_assignment_expression();
4956 if(last_argument == NULL) {
4957 call->arguments = argument;
4959 last_argument->next = argument;
4961 last_argument = argument;
4963 if(token.type != ',')
4968 rem_anchor_token(',');
4969 rem_anchor_token(')');
4972 if(function_type != NULL) {
4973 function_parameter_t *parameter = function_type->parameters;
4974 call_argument_t *argument = call->arguments;
4975 for( ; parameter != NULL && argument != NULL;
4976 parameter = parameter->next, argument = argument->next) {
4977 type_t *expected_type = parameter->type;
4978 /* TODO report scope in error messages */
4979 expression_t *const arg_expr = argument->expression;
4980 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4981 if (res_type == NULL) {
4982 /* TODO improve error message */
4983 errorf(arg_expr->base.source_position,
4984 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4985 arg_expr, arg_expr->base.type, expected_type);
4987 argument->expression = create_implicit_cast(argument->expression, expected_type);
4990 /* too few parameters */
4991 if(parameter != NULL) {
4992 errorf(HERE, "too few arguments to function '%E'", expression);
4993 } else if(argument != NULL) {
4994 /* too many parameters */
4995 if(!function_type->variadic
4996 && !function_type->unspecified_parameters) {
4997 errorf(HERE, "too many arguments to function '%E'", expression);
4999 /* do default promotion */
5000 for( ; argument != NULL; argument = argument->next) {
5001 type_t *type = argument->expression->base.type;
5003 type = skip_typeref(type);
5004 if(is_type_integer(type)) {
5005 type = promote_integer(type);
5006 } else if(type == type_float) {
5010 argument->expression
5011 = create_implicit_cast(argument->expression, type);
5014 check_format(&result->call);
5017 check_format(&result->call);
5023 return create_invalid_expression();
5026 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5028 static bool same_compound_type(const type_t *type1, const type_t *type2)
5031 is_type_compound(type1) &&
5032 type1->kind == type2->kind &&
5033 type1->compound.declaration == type2->compound.declaration;
5037 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5039 * @param expression the conditional expression
5041 static expression_t *parse_conditional_expression(unsigned precedence,
5042 expression_t *expression)
5045 add_anchor_token(':');
5047 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5049 conditional_expression_t *conditional = &result->conditional;
5050 conditional->condition = expression;
5053 type_t *const condition_type_orig = expression->base.type;
5054 type_t *const condition_type = skip_typeref(condition_type_orig);
5055 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5056 type_error("expected a scalar type in conditional condition",
5057 expression->base.source_position, condition_type_orig);
5060 expression_t *true_expression = parse_expression();
5061 rem_anchor_token(':');
5063 expression_t *false_expression = parse_sub_expression(precedence);
5065 type_t *const orig_true_type = true_expression->base.type;
5066 type_t *const orig_false_type = false_expression->base.type;
5067 type_t *const true_type = skip_typeref(orig_true_type);
5068 type_t *const false_type = skip_typeref(orig_false_type);
5071 type_t *result_type;
5072 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
5073 result_type = semantic_arithmetic(true_type, false_type);
5075 true_expression = create_implicit_cast(true_expression, result_type);
5076 false_expression = create_implicit_cast(false_expression, result_type);
5078 conditional->true_expression = true_expression;
5079 conditional->false_expression = false_expression;
5080 conditional->base.type = result_type;
5081 } else if (same_compound_type(true_type, false_type) || (
5082 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
5083 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
5085 /* just take 1 of the 2 types */
5086 result_type = true_type;
5087 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
5088 && pointers_compatible(true_type, false_type)) {
5090 result_type = true_type;
5091 } else if (is_type_pointer(true_type)
5092 && is_null_pointer_constant(false_expression)) {
5093 result_type = true_type;
5094 } else if (is_type_pointer(false_type)
5095 && is_null_pointer_constant(true_expression)) {
5096 result_type = false_type;
5098 /* TODO: one pointer to void*, other some pointer */
5100 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5101 type_error_incompatible("while parsing conditional",
5102 expression->base.source_position, true_type,
5105 result_type = type_error_type;
5108 conditional->true_expression
5109 = create_implicit_cast(true_expression, result_type);
5110 conditional->false_expression
5111 = create_implicit_cast(false_expression, result_type);
5112 conditional->base.type = result_type;
5115 return create_invalid_expression();
5119 * Parse an extension expression.
5121 static expression_t *parse_extension(unsigned precedence)
5123 eat(T___extension__);
5125 /* TODO enable extensions */
5126 expression_t *expression = parse_sub_expression(precedence);
5127 /* TODO disable extensions */
5132 * Parse a __builtin_classify_type() expression.
5134 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5136 eat(T___builtin_classify_type);
5138 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5139 result->base.type = type_int;
5142 add_anchor_token(')');
5143 expression_t *expression = parse_sub_expression(precedence);
5144 rem_anchor_token(')');
5146 result->classify_type.type_expression = expression;
5150 return create_invalid_expression();
5153 static void semantic_incdec(unary_expression_t *expression)
5155 type_t *const orig_type = expression->value->base.type;
5156 type_t *const type = skip_typeref(orig_type);
5157 /* TODO !is_type_real && !is_type_pointer */
5158 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5159 if (is_type_valid(type)) {
5160 /* TODO: improve error message */
5161 errorf(HERE, "operation needs an arithmetic or pointer type");
5166 expression->base.type = orig_type;
5169 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5171 type_t *const orig_type = expression->value->base.type;
5172 type_t *const type = skip_typeref(orig_type);
5173 if(!is_type_arithmetic(type)) {
5174 if (is_type_valid(type)) {
5175 /* TODO: improve error message */
5176 errorf(HERE, "operation needs an arithmetic type");
5181 expression->base.type = orig_type;
5184 static void semantic_unexpr_scalar(unary_expression_t *expression)
5186 type_t *const orig_type = expression->value->base.type;
5187 type_t *const type = skip_typeref(orig_type);
5188 if (!is_type_scalar(type)) {
5189 if (is_type_valid(type)) {
5190 errorf(HERE, "operand of ! must be of scalar type");
5195 expression->base.type = orig_type;
5198 static void semantic_unexpr_integer(unary_expression_t *expression)
5200 type_t *const orig_type = expression->value->base.type;
5201 type_t *const type = skip_typeref(orig_type);
5202 if (!is_type_integer(type)) {
5203 if (is_type_valid(type)) {
5204 errorf(HERE, "operand of ~ must be of integer type");
5209 expression->base.type = orig_type;
5212 static void semantic_dereference(unary_expression_t *expression)
5214 type_t *const orig_type = expression->value->base.type;
5215 type_t *const type = skip_typeref(orig_type);
5216 if(!is_type_pointer(type)) {
5217 if (is_type_valid(type)) {
5218 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5223 type_t *result_type = type->pointer.points_to;
5224 result_type = automatic_type_conversion(result_type);
5225 expression->base.type = result_type;
5229 * Check the semantic of the address taken expression.
5231 static void semantic_take_addr(unary_expression_t *expression)
5233 expression_t *value = expression->value;
5234 value->base.type = revert_automatic_type_conversion(value);
5236 type_t *orig_type = value->base.type;
5237 if(!is_type_valid(orig_type))
5240 if(value->kind == EXPR_REFERENCE) {
5241 declaration_t *const declaration = value->reference.declaration;
5242 if(declaration != NULL) {
5243 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5244 errorf(expression->base.source_position,
5245 "address of register variable '%Y' requested",
5246 declaration->symbol);
5248 declaration->address_taken = 1;
5252 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5255 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5256 static expression_t *parse_##unexpression_type(unsigned precedence) \
5260 expression_t *unary_expression \
5261 = allocate_expression_zero(unexpression_type); \
5262 unary_expression->base.source_position = HERE; \
5263 unary_expression->unary.value = parse_sub_expression(precedence); \
5265 sfunc(&unary_expression->unary); \
5267 return unary_expression; \
5270 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5271 semantic_unexpr_arithmetic)
5272 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5273 semantic_unexpr_arithmetic)
5274 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5275 semantic_unexpr_scalar)
5276 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5277 semantic_dereference)
5278 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5280 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5281 semantic_unexpr_integer)
5282 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5284 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5287 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5289 static expression_t *parse_##unexpression_type(unsigned precedence, \
5290 expression_t *left) \
5292 (void) precedence; \
5295 expression_t *unary_expression \
5296 = allocate_expression_zero(unexpression_type); \
5297 unary_expression->unary.value = left; \
5299 sfunc(&unary_expression->unary); \
5301 return unary_expression; \
5304 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5305 EXPR_UNARY_POSTFIX_INCREMENT,
5307 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5308 EXPR_UNARY_POSTFIX_DECREMENT,
5311 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5313 /* TODO: handle complex + imaginary types */
5315 /* § 6.3.1.8 Usual arithmetic conversions */
5316 if(type_left == type_long_double || type_right == type_long_double) {
5317 return type_long_double;
5318 } else if(type_left == type_double || type_right == type_double) {
5320 } else if(type_left == type_float || type_right == type_float) {
5324 type_right = promote_integer(type_right);
5325 type_left = promote_integer(type_left);
5327 if(type_left == type_right)
5330 bool signed_left = is_type_signed(type_left);
5331 bool signed_right = is_type_signed(type_right);
5332 int rank_left = get_rank(type_left);
5333 int rank_right = get_rank(type_right);
5334 if(rank_left < rank_right) {
5335 if(signed_left == signed_right || !signed_right) {
5341 if(signed_left == signed_right || !signed_left) {
5350 * Check the semantic restrictions for a binary expression.
5352 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5354 expression_t *const left = expression->left;
5355 expression_t *const right = expression->right;
5356 type_t *const orig_type_left = left->base.type;
5357 type_t *const orig_type_right = right->base.type;
5358 type_t *const type_left = skip_typeref(orig_type_left);
5359 type_t *const type_right = skip_typeref(orig_type_right);
5361 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5362 /* TODO: improve error message */
5363 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5364 errorf(HERE, "operation needs arithmetic types");
5369 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5370 expression->left = create_implicit_cast(left, arithmetic_type);
5371 expression->right = create_implicit_cast(right, arithmetic_type);
5372 expression->base.type = arithmetic_type;
5375 static void semantic_shift_op(binary_expression_t *expression)
5377 expression_t *const left = expression->left;
5378 expression_t *const right = expression->right;
5379 type_t *const orig_type_left = left->base.type;
5380 type_t *const orig_type_right = right->base.type;
5381 type_t * type_left = skip_typeref(orig_type_left);
5382 type_t * type_right = skip_typeref(orig_type_right);
5384 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5385 /* TODO: improve error message */
5386 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5387 errorf(HERE, "operation needs integer types");
5392 type_left = promote_integer(type_left);
5393 type_right = promote_integer(type_right);
5395 expression->left = create_implicit_cast(left, type_left);
5396 expression->right = create_implicit_cast(right, type_right);
5397 expression->base.type = type_left;
5400 static void semantic_add(binary_expression_t *expression)
5402 expression_t *const left = expression->left;
5403 expression_t *const right = expression->right;
5404 type_t *const orig_type_left = left->base.type;
5405 type_t *const orig_type_right = right->base.type;
5406 type_t *const type_left = skip_typeref(orig_type_left);
5407 type_t *const type_right = skip_typeref(orig_type_right);
5410 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5411 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5412 expression->left = create_implicit_cast(left, arithmetic_type);
5413 expression->right = create_implicit_cast(right, arithmetic_type);
5414 expression->base.type = arithmetic_type;
5416 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5417 expression->base.type = type_left;
5418 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5419 expression->base.type = type_right;
5420 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5421 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5425 static void semantic_sub(binary_expression_t *expression)
5427 expression_t *const left = expression->left;
5428 expression_t *const right = expression->right;
5429 type_t *const orig_type_left = left->base.type;
5430 type_t *const orig_type_right = right->base.type;
5431 type_t *const type_left = skip_typeref(orig_type_left);
5432 type_t *const type_right = skip_typeref(orig_type_right);
5435 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5436 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5437 expression->left = create_implicit_cast(left, arithmetic_type);
5438 expression->right = create_implicit_cast(right, arithmetic_type);
5439 expression->base.type = arithmetic_type;
5441 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5442 expression->base.type = type_left;
5443 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5444 if(!pointers_compatible(type_left, type_right)) {
5446 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5447 orig_type_left, orig_type_right);
5449 expression->base.type = type_ptrdiff_t;
5451 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5452 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5453 orig_type_left, orig_type_right);
5458 * Check the semantics of comparison expressions.
5460 * @param expression The expression to check.
5462 static void semantic_comparison(binary_expression_t *expression)
5464 expression_t *left = expression->left;
5465 expression_t *right = expression->right;
5466 type_t *orig_type_left = left->base.type;
5467 type_t *orig_type_right = right->base.type;
5469 type_t *type_left = skip_typeref(orig_type_left);
5470 type_t *type_right = skip_typeref(orig_type_right);
5472 /* TODO non-arithmetic types */
5473 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5474 if (warning.sign_compare &&
5475 (expression->base.kind != EXPR_BINARY_EQUAL &&
5476 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5477 (is_type_signed(type_left) != is_type_signed(type_right))) {
5478 warningf(expression->base.source_position,
5479 "comparison between signed and unsigned");
5481 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5482 expression->left = create_implicit_cast(left, arithmetic_type);
5483 expression->right = create_implicit_cast(right, arithmetic_type);
5484 expression->base.type = arithmetic_type;
5485 if (warning.float_equal &&
5486 (expression->base.kind == EXPR_BINARY_EQUAL ||
5487 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5488 is_type_float(arithmetic_type)) {
5489 warningf(expression->base.source_position,
5490 "comparing floating point with == or != is unsafe");
5492 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5493 /* TODO check compatibility */
5494 } else if (is_type_pointer(type_left)) {
5495 expression->right = create_implicit_cast(right, type_left);
5496 } else if (is_type_pointer(type_right)) {
5497 expression->left = create_implicit_cast(left, type_right);
5498 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5499 type_error_incompatible("invalid operands in comparison",
5500 expression->base.source_position,
5501 type_left, type_right);
5503 expression->base.type = type_int;
5506 static void semantic_arithmetic_assign(binary_expression_t *expression)
5508 expression_t *left = expression->left;
5509 expression_t *right = expression->right;
5510 type_t *orig_type_left = left->base.type;
5511 type_t *orig_type_right = right->base.type;
5513 type_t *type_left = skip_typeref(orig_type_left);
5514 type_t *type_right = skip_typeref(orig_type_right);
5516 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5517 /* TODO: improve error message */
5518 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5519 errorf(HERE, "operation needs arithmetic types");
5524 /* combined instructions are tricky. We can't create an implicit cast on
5525 * the left side, because we need the uncasted form for the store.
5526 * The ast2firm pass has to know that left_type must be right_type
5527 * for the arithmetic operation and create a cast by itself */
5528 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5529 expression->right = create_implicit_cast(right, arithmetic_type);
5530 expression->base.type = type_left;
5533 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5535 expression_t *const left = expression->left;
5536 expression_t *const right = expression->right;
5537 type_t *const orig_type_left = left->base.type;
5538 type_t *const orig_type_right = right->base.type;
5539 type_t *const type_left = skip_typeref(orig_type_left);
5540 type_t *const type_right = skip_typeref(orig_type_right);
5542 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5543 /* combined instructions are tricky. We can't create an implicit cast on
5544 * the left side, because we need the uncasted form for the store.
5545 * The ast2firm pass has to know that left_type must be right_type
5546 * for the arithmetic operation and create a cast by itself */
5547 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5548 expression->right = create_implicit_cast(right, arithmetic_type);
5549 expression->base.type = type_left;
5550 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5551 expression->base.type = type_left;
5552 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5553 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5558 * Check the semantic restrictions of a logical expression.
5560 static void semantic_logical_op(binary_expression_t *expression)
5562 expression_t *const left = expression->left;
5563 expression_t *const right = expression->right;
5564 type_t *const orig_type_left = left->base.type;
5565 type_t *const orig_type_right = right->base.type;
5566 type_t *const type_left = skip_typeref(orig_type_left);
5567 type_t *const type_right = skip_typeref(orig_type_right);
5569 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5570 /* TODO: improve error message */
5571 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5572 errorf(HERE, "operation needs scalar types");
5577 expression->base.type = type_int;
5581 * Checks if a compound type has constant fields.
5583 static bool has_const_fields(const compound_type_t *type)
5585 const scope_t *scope = &type->declaration->scope;
5586 const declaration_t *declaration = scope->declarations;
5588 for (; declaration != NULL; declaration = declaration->next) {
5589 if (declaration->namespc != NAMESPACE_NORMAL)
5592 const type_t *decl_type = skip_typeref(declaration->type);
5593 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5601 * Check the semantic restrictions of a binary assign expression.
5603 static void semantic_binexpr_assign(binary_expression_t *expression)
5605 expression_t *left = expression->left;
5606 type_t *orig_type_left = left->base.type;
5608 type_t *type_left = revert_automatic_type_conversion(left);
5609 type_left = skip_typeref(orig_type_left);
5611 /* must be a modifiable lvalue */
5612 if (is_type_array(type_left)) {
5613 errorf(HERE, "cannot assign to arrays ('%E')", left);
5616 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5617 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5621 if(is_type_incomplete(type_left)) {
5623 "left-hand side of assignment '%E' has incomplete type '%T'",
5624 left, orig_type_left);
5627 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5628 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5629 left, orig_type_left);
5633 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5635 if (res_type == NULL) {
5636 errorf(expression->base.source_position,
5637 "cannot assign to '%T' from '%T'",
5638 orig_type_left, expression->right->base.type);
5640 expression->right = create_implicit_cast(expression->right, res_type);
5643 expression->base.type = orig_type_left;
5647 * Determine if the outermost operation (or parts thereof) of the given
5648 * expression has no effect in order to generate a warning about this fact.
5649 * Therefore in some cases this only examines some of the operands of the
5650 * expression (see comments in the function and examples below).
5652 * f() + 23; // warning, because + has no effect
5653 * x || f(); // no warning, because x controls execution of f()
5654 * x ? y : f(); // warning, because y has no effect
5655 * (void)x; // no warning to be able to suppress the warning
5656 * This function can NOT be used for an "expression has definitely no effect"-
5658 static bool expression_has_effect(const expression_t *const expr)
5660 switch (expr->kind) {
5661 case EXPR_UNKNOWN: break;
5662 case EXPR_INVALID: return true; /* do NOT warn */
5663 case EXPR_REFERENCE: return false;
5664 case EXPR_CONST: return false;
5665 case EXPR_CHARACTER_CONSTANT: return false;
5666 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5667 case EXPR_STRING_LITERAL: return false;
5668 case EXPR_WIDE_STRING_LITERAL: return false;
5671 const call_expression_t *const call = &expr->call;
5672 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5675 switch (call->function->builtin_symbol.symbol->ID) {
5676 case T___builtin_va_end: return true;
5677 default: return false;
5681 /* Generate the warning if either the left or right hand side of a
5682 * conditional expression has no effect */
5683 case EXPR_CONDITIONAL: {
5684 const conditional_expression_t *const cond = &expr->conditional;
5686 expression_has_effect(cond->true_expression) &&
5687 expression_has_effect(cond->false_expression);
5690 case EXPR_SELECT: return false;
5691 case EXPR_ARRAY_ACCESS: return false;
5692 case EXPR_SIZEOF: return false;
5693 case EXPR_CLASSIFY_TYPE: return false;
5694 case EXPR_ALIGNOF: return false;
5696 case EXPR_FUNCTION: return false;
5697 case EXPR_PRETTY_FUNCTION: return false;
5698 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5699 case EXPR_BUILTIN_CONSTANT_P: return false;
5700 case EXPR_BUILTIN_PREFETCH: return true;
5701 case EXPR_OFFSETOF: return false;
5702 case EXPR_VA_START: return true;
5703 case EXPR_VA_ARG: return true;
5704 case EXPR_STATEMENT: return true; // TODO
5705 case EXPR_COMPOUND_LITERAL: return false;
5707 case EXPR_UNARY_NEGATE: return false;
5708 case EXPR_UNARY_PLUS: return false;
5709 case EXPR_UNARY_BITWISE_NEGATE: return false;
5710 case EXPR_UNARY_NOT: return false;
5711 case EXPR_UNARY_DEREFERENCE: return false;
5712 case EXPR_UNARY_TAKE_ADDRESS: return false;
5713 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5714 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5715 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5716 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5718 /* Treat void casts as if they have an effect in order to being able to
5719 * suppress the warning */
5720 case EXPR_UNARY_CAST: {
5721 type_t *const type = skip_typeref(expr->base.type);
5722 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5725 case EXPR_UNARY_CAST_IMPLICIT: return true;
5726 case EXPR_UNARY_ASSUME: return true;
5727 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5729 case EXPR_BINARY_ADD: return false;
5730 case EXPR_BINARY_SUB: return false;
5731 case EXPR_BINARY_MUL: return false;
5732 case EXPR_BINARY_DIV: return false;
5733 case EXPR_BINARY_MOD: return false;
5734 case EXPR_BINARY_EQUAL: return false;
5735 case EXPR_BINARY_NOTEQUAL: return false;
5736 case EXPR_BINARY_LESS: return false;
5737 case EXPR_BINARY_LESSEQUAL: return false;
5738 case EXPR_BINARY_GREATER: return false;
5739 case EXPR_BINARY_GREATEREQUAL: return false;
5740 case EXPR_BINARY_BITWISE_AND: return false;
5741 case EXPR_BINARY_BITWISE_OR: return false;
5742 case EXPR_BINARY_BITWISE_XOR: return false;
5743 case EXPR_BINARY_SHIFTLEFT: return false;
5744 case EXPR_BINARY_SHIFTRIGHT: return false;
5745 case EXPR_BINARY_ASSIGN: return true;
5746 case EXPR_BINARY_MUL_ASSIGN: return true;
5747 case EXPR_BINARY_DIV_ASSIGN: return true;
5748 case EXPR_BINARY_MOD_ASSIGN: return true;
5749 case EXPR_BINARY_ADD_ASSIGN: return true;
5750 case EXPR_BINARY_SUB_ASSIGN: return true;
5751 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5752 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5753 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5754 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5755 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5757 /* Only examine the right hand side of && and ||, because the left hand
5758 * side already has the effect of controlling the execution of the right
5760 case EXPR_BINARY_LOGICAL_AND:
5761 case EXPR_BINARY_LOGICAL_OR:
5762 /* Only examine the right hand side of a comma expression, because the left
5763 * hand side has a separate warning */
5764 case EXPR_BINARY_COMMA:
5765 return expression_has_effect(expr->binary.right);
5767 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5768 case EXPR_BINARY_ISGREATER: return false;
5769 case EXPR_BINARY_ISGREATEREQUAL: return false;
5770 case EXPR_BINARY_ISLESS: return false;
5771 case EXPR_BINARY_ISLESSEQUAL: return false;
5772 case EXPR_BINARY_ISLESSGREATER: return false;
5773 case EXPR_BINARY_ISUNORDERED: return false;
5776 internal_errorf(HERE, "unexpected expression");
5779 static void semantic_comma(binary_expression_t *expression)
5781 if (warning.unused_value) {
5782 const expression_t *const left = expression->left;
5783 if (!expression_has_effect(left)) {
5784 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5787 expression->base.type = expression->right->base.type;
5790 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5791 static expression_t *parse_##binexpression_type(unsigned precedence, \
5792 expression_t *left) \
5795 source_position_t pos = HERE; \
5797 expression_t *right = parse_sub_expression(precedence + lr); \
5799 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5800 binexpr->base.source_position = pos; \
5801 binexpr->binary.left = left; \
5802 binexpr->binary.right = right; \
5803 sfunc(&binexpr->binary); \
5808 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5809 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5810 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5811 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5812 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5813 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5814 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5815 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5816 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5818 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5819 semantic_comparison, 1)
5820 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5821 semantic_comparison, 1)
5822 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5823 semantic_comparison, 1)
5824 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5825 semantic_comparison, 1)
5827 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5828 semantic_binexpr_arithmetic, 1)
5829 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5830 semantic_binexpr_arithmetic, 1)
5831 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5832 semantic_binexpr_arithmetic, 1)
5833 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5834 semantic_logical_op, 1)
5835 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5836 semantic_logical_op, 1)
5837 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5838 semantic_shift_op, 1)
5839 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5840 semantic_shift_op, 1)
5841 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5842 semantic_arithmetic_addsubb_assign, 0)
5843 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5844 semantic_arithmetic_addsubb_assign, 0)
5845 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5846 semantic_arithmetic_assign, 0)
5847 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5848 semantic_arithmetic_assign, 0)
5849 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5850 semantic_arithmetic_assign, 0)
5851 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5852 semantic_arithmetic_assign, 0)
5853 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5854 semantic_arithmetic_assign, 0)
5855 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5856 semantic_arithmetic_assign, 0)
5857 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5858 semantic_arithmetic_assign, 0)
5859 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5860 semantic_arithmetic_assign, 0)
5862 static expression_t *parse_sub_expression(unsigned precedence)
5864 if(token.type < 0) {
5865 return expected_expression_error();
5868 expression_parser_function_t *parser
5869 = &expression_parsers[token.type];
5870 source_position_t source_position = token.source_position;
5873 if(parser->parser != NULL) {
5874 left = parser->parser(parser->precedence);
5876 left = parse_primary_expression();
5878 assert(left != NULL);
5879 left->base.source_position = source_position;
5882 if(token.type < 0) {
5883 return expected_expression_error();
5886 parser = &expression_parsers[token.type];
5887 if(parser->infix_parser == NULL)
5889 if(parser->infix_precedence < precedence)
5892 left = parser->infix_parser(parser->infix_precedence, left);
5894 assert(left != NULL);
5895 assert(left->kind != EXPR_UNKNOWN);
5896 left->base.source_position = source_position;
5903 * Parse an expression.
5905 static expression_t *parse_expression(void)
5907 return parse_sub_expression(1);
5911 * Register a parser for a prefix-like operator with given precedence.
5913 * @param parser the parser function
5914 * @param token_type the token type of the prefix token
5915 * @param precedence the precedence of the operator
5917 static void register_expression_parser(parse_expression_function parser,
5918 int token_type, unsigned precedence)
5920 expression_parser_function_t *entry = &expression_parsers[token_type];
5922 if(entry->parser != NULL) {
5923 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5924 panic("trying to register multiple expression parsers for a token");
5926 entry->parser = parser;
5927 entry->precedence = precedence;
5931 * Register a parser for an infix operator with given precedence.
5933 * @param parser the parser function
5934 * @param token_type the token type of the infix operator
5935 * @param precedence the precedence of the operator
5937 static void register_infix_parser(parse_expression_infix_function parser,
5938 int token_type, unsigned precedence)
5940 expression_parser_function_t *entry = &expression_parsers[token_type];
5942 if(entry->infix_parser != NULL) {
5943 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5944 panic("trying to register multiple infix expression parsers for a "
5947 entry->infix_parser = parser;
5948 entry->infix_precedence = precedence;
5952 * Initialize the expression parsers.
5954 static void init_expression_parsers(void)
5956 memset(&expression_parsers, 0, sizeof(expression_parsers));
5958 register_infix_parser(parse_array_expression, '[', 30);
5959 register_infix_parser(parse_call_expression, '(', 30);
5960 register_infix_parser(parse_select_expression, '.', 30);
5961 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
5962 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5964 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5967 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
5968 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
5969 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
5970 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
5971 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
5972 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
5973 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
5974 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
5975 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
5976 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
5977 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
5978 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
5979 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5980 T_EXCLAMATIONMARKEQUAL, 13);
5981 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
5982 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
5983 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
5984 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
5985 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
5986 register_infix_parser(parse_conditional_expression, '?', 7);
5987 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
5988 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
5989 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
5990 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
5991 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
5992 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
5993 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5994 T_LESSLESSEQUAL, 2);
5995 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5996 T_GREATERGREATEREQUAL, 2);
5997 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5999 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6001 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6004 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6006 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6007 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6008 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6009 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6010 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6011 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6012 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6014 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6016 register_expression_parser(parse_sizeof, T_sizeof, 25);
6017 register_expression_parser(parse_alignof, T___alignof__, 25);
6018 register_expression_parser(parse_extension, T___extension__, 25);
6019 register_expression_parser(parse_builtin_classify_type,
6020 T___builtin_classify_type, 25);
6024 * Parse a asm statement constraints specification.
6026 static asm_constraint_t *parse_asm_constraints(void)
6028 asm_constraint_t *result = NULL;
6029 asm_constraint_t *last = NULL;
6031 while(token.type == T_STRING_LITERAL || token.type == '[') {
6032 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6033 memset(constraint, 0, sizeof(constraint[0]));
6035 if(token.type == '[') {
6037 if(token.type != T_IDENTIFIER) {
6038 parse_error_expected("while parsing asm constraint",
6042 constraint->symbol = token.v.symbol;
6047 constraint->constraints = parse_string_literals();
6049 constraint->expression = parse_expression();
6053 last->next = constraint;
6055 result = constraint;
6059 if(token.type != ',')
6070 * Parse a asm statement clobber specification.
6072 static asm_clobber_t *parse_asm_clobbers(void)
6074 asm_clobber_t *result = NULL;
6075 asm_clobber_t *last = NULL;
6077 while(token.type == T_STRING_LITERAL) {
6078 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6079 clobber->clobber = parse_string_literals();
6082 last->next = clobber;
6088 if(token.type != ',')
6097 * Parse an asm statement.
6099 static statement_t *parse_asm_statement(void)
6103 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6104 statement->base.source_position = token.source_position;
6106 asm_statement_t *asm_statement = &statement->asms;
6108 if(token.type == T_volatile) {
6110 asm_statement->is_volatile = true;
6114 add_anchor_token(')');
6115 add_anchor_token(':');
6116 asm_statement->asm_text = parse_string_literals();
6118 if(token.type != ':') {
6119 rem_anchor_token(':');
6124 asm_statement->inputs = parse_asm_constraints();
6125 if(token.type != ':') {
6126 rem_anchor_token(':');
6131 asm_statement->outputs = parse_asm_constraints();
6132 if(token.type != ':') {
6133 rem_anchor_token(':');
6136 rem_anchor_token(':');
6139 asm_statement->clobbers = parse_asm_clobbers();
6142 rem_anchor_token(')');
6147 return create_invalid_statement();
6151 * Parse a case statement.
6153 static statement_t *parse_case_statement(void)
6157 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6159 statement->base.source_position = token.source_position;
6160 statement->case_label.expression = parse_expression();
6162 if (c_mode & _GNUC) {
6163 if (token.type == T_DOTDOTDOT) {
6165 statement->case_label.end_range = parse_expression();
6171 if (! is_constant_expression(statement->case_label.expression)) {
6172 errorf(statement->base.source_position,
6173 "case label does not reduce to an integer constant");
6175 /* TODO: check if the case label is already known */
6176 if (current_switch != NULL) {
6177 /* link all cases into the switch statement */
6178 if (current_switch->last_case == NULL) {
6179 current_switch->first_case =
6180 current_switch->last_case = &statement->case_label;
6182 current_switch->last_case->next = &statement->case_label;
6185 errorf(statement->base.source_position,
6186 "case label not within a switch statement");
6189 statement->case_label.statement = parse_statement();
6193 return create_invalid_statement();
6197 * Finds an existing default label of a switch statement.
6199 static case_label_statement_t *
6200 find_default_label(const switch_statement_t *statement)
6202 case_label_statement_t *label = statement->first_case;
6203 for ( ; label != NULL; label = label->next) {
6204 if (label->expression == NULL)
6211 * Parse a default statement.
6213 static statement_t *parse_default_statement(void)
6217 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6219 statement->base.source_position = token.source_position;
6222 if (current_switch != NULL) {
6223 const case_label_statement_t *def_label = find_default_label(current_switch);
6224 if (def_label != NULL) {
6225 errorf(HERE, "multiple default labels in one switch");
6226 errorf(def_label->base.source_position,
6227 "this is the first default label");
6229 /* link all cases into the switch statement */
6230 if (current_switch->last_case == NULL) {
6231 current_switch->first_case =
6232 current_switch->last_case = &statement->case_label;
6234 current_switch->last_case->next = &statement->case_label;
6238 errorf(statement->base.source_position,
6239 "'default' label not within a switch statement");
6241 statement->case_label.statement = parse_statement();
6245 return create_invalid_statement();
6249 * Return the declaration for a given label symbol or create a new one.
6251 static declaration_t *get_label(symbol_t *symbol)
6253 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6254 assert(current_function != NULL);
6255 /* if we found a label in the same function, then we already created the
6257 if(candidate != NULL
6258 && candidate->parent_scope == ¤t_function->scope) {
6262 /* otherwise we need to create a new one */
6263 declaration_t *const declaration = allocate_declaration_zero();
6264 declaration->namespc = NAMESPACE_LABEL;
6265 declaration->symbol = symbol;
6267 label_push(declaration);
6273 * Parse a label statement.
6275 static statement_t *parse_label_statement(void)
6277 assert(token.type == T_IDENTIFIER);
6278 symbol_t *symbol = token.v.symbol;
6281 declaration_t *label = get_label(symbol);
6283 /* if source position is already set then the label is defined twice,
6284 * otherwise it was just mentioned in a goto so far */
6285 if(label->source_position.input_name != NULL) {
6286 errorf(HERE, "duplicate label '%Y'", symbol);
6287 errorf(label->source_position, "previous definition of '%Y' was here",
6290 label->source_position = token.source_position;
6293 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6295 statement->base.source_position = token.source_position;
6296 statement->label.label = label;
6300 if(token.type == '}') {
6301 /* TODO only warn? */
6303 warningf(HERE, "label at end of compound statement");
6304 statement->label.statement = create_empty_statement();
6306 errorf(HERE, "label at end of compound statement");
6307 statement->label.statement = create_invalid_statement();
6311 if (token.type == ';') {
6312 /* eat an empty statement here, to avoid the warning about an empty
6313 * after a label. label:; is commonly used to have a label before
6315 statement->label.statement = create_empty_statement();
6318 statement->label.statement = parse_statement();
6322 /* remember the labels's in a list for later checking */
6323 if (label_last == NULL) {
6324 label_first = &statement->label;
6326 label_last->next = &statement->label;
6328 label_last = &statement->label;
6334 * Parse an if statement.
6336 static statement_t *parse_if(void)
6340 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6341 statement->base.source_position = token.source_position;
6344 add_anchor_token(')');
6345 statement->ifs.condition = parse_expression();
6346 rem_anchor_token(')');
6349 add_anchor_token(T_else);
6350 statement->ifs.true_statement = parse_statement();
6351 rem_anchor_token(T_else);
6353 if(token.type == T_else) {
6355 statement->ifs.false_statement = parse_statement();
6360 return create_invalid_statement();
6364 * Parse a switch statement.
6366 static statement_t *parse_switch(void)
6370 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6371 statement->base.source_position = token.source_position;
6374 expression_t *const expr = parse_expression();
6375 type_t * type = skip_typeref(expr->base.type);
6376 if (is_type_integer(type)) {
6377 type = promote_integer(type);
6378 } else if (is_type_valid(type)) {
6379 errorf(expr->base.source_position,
6380 "switch quantity is not an integer, but '%T'", type);
6381 type = type_error_type;
6383 statement->switchs.expression = create_implicit_cast(expr, type);
6386 switch_statement_t *rem = current_switch;
6387 current_switch = &statement->switchs;
6388 statement->switchs.body = parse_statement();
6389 current_switch = rem;
6391 if (warning.switch_default
6392 && find_default_label(&statement->switchs) == NULL) {
6393 warningf(statement->base.source_position, "switch has no default case");
6398 return create_invalid_statement();
6401 static statement_t *parse_loop_body(statement_t *const loop)
6403 statement_t *const rem = current_loop;
6404 current_loop = loop;
6406 statement_t *const body = parse_statement();
6413 * Parse a while statement.
6415 static statement_t *parse_while(void)
6419 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6420 statement->base.source_position = token.source_position;
6423 add_anchor_token(')');
6424 statement->whiles.condition = parse_expression();
6425 rem_anchor_token(')');
6428 statement->whiles.body = parse_loop_body(statement);
6432 return create_invalid_statement();
6436 * Parse a do statement.
6438 static statement_t *parse_do(void)
6442 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6444 statement->base.source_position = token.source_position;
6446 add_anchor_token(T_while);
6447 statement->do_while.body = parse_loop_body(statement);
6448 rem_anchor_token(T_while);
6452 add_anchor_token(')');
6453 statement->do_while.condition = parse_expression();
6454 rem_anchor_token(')');
6460 return create_invalid_statement();
6464 * Parse a for statement.
6466 static statement_t *parse_for(void)
6470 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6471 statement->base.source_position = token.source_position;
6473 int top = environment_top();
6474 scope_t *last_scope = scope;
6475 set_scope(&statement->fors.scope);
6478 add_anchor_token(')');
6480 if(token.type != ';') {
6481 if(is_declaration_specifier(&token, false)) {
6482 parse_declaration(record_declaration);
6484 expression_t *const init = parse_expression();
6485 statement->fors.initialisation = init;
6486 if (warning.unused_value && !expression_has_effect(init)) {
6487 warningf(init->base.source_position,
6488 "initialisation of 'for'-statement has no effect");
6496 if(token.type != ';') {
6497 statement->fors.condition = parse_expression();
6500 if(token.type != ')') {
6501 expression_t *const step = parse_expression();
6502 statement->fors.step = step;
6503 if (warning.unused_value && !expression_has_effect(step)) {
6504 warningf(step->base.source_position,
6505 "step of 'for'-statement has no effect");
6508 rem_anchor_token(')');
6510 statement->fors.body = parse_loop_body(statement);
6512 assert(scope == &statement->fors.scope);
6513 set_scope(last_scope);
6514 environment_pop_to(top);
6519 rem_anchor_token(')');
6520 assert(scope == &statement->fors.scope);
6521 set_scope(last_scope);
6522 environment_pop_to(top);
6524 return create_invalid_statement();
6528 * Parse a goto statement.
6530 static statement_t *parse_goto(void)
6534 if(token.type != T_IDENTIFIER) {
6535 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6539 symbol_t *symbol = token.v.symbol;
6542 declaration_t *label = get_label(symbol);
6544 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6545 statement->base.source_position = token.source_position;
6547 statement->gotos.label = label;
6549 /* remember the goto's in a list for later checking */
6550 if (goto_last == NULL) {
6551 goto_first = &statement->gotos;
6553 goto_last->next = &statement->gotos;
6555 goto_last = &statement->gotos;
6561 return create_invalid_statement();
6565 * Parse a continue statement.
6567 static statement_t *parse_continue(void)
6569 statement_t *statement;
6570 if (current_loop == NULL) {
6571 errorf(HERE, "continue statement not within loop");
6574 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6576 statement->base.source_position = token.source_position;
6584 return create_invalid_statement();
6588 * Parse a break statement.
6590 static statement_t *parse_break(void)
6592 statement_t *statement;
6593 if (current_switch == NULL && current_loop == NULL) {
6594 errorf(HERE, "break statement not within loop or switch");
6597 statement = allocate_statement_zero(STATEMENT_BREAK);
6599 statement->base.source_position = token.source_position;
6607 return create_invalid_statement();
6611 * Check if a given declaration represents a local variable.
6613 static bool is_local_var_declaration(const declaration_t *declaration) {
6614 switch ((storage_class_tag_t) declaration->storage_class) {
6615 case STORAGE_CLASS_AUTO:
6616 case STORAGE_CLASS_REGISTER: {
6617 const type_t *type = skip_typeref(declaration->type);
6618 if(is_type_function(type)) {
6630 * Check if a given declaration represents a variable.
6632 static bool is_var_declaration(const declaration_t *declaration) {
6633 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6636 const type_t *type = skip_typeref(declaration->type);
6637 return !is_type_function(type);
6641 * Check if a given expression represents a local variable.
6643 static bool is_local_variable(const expression_t *expression)
6645 if (expression->base.kind != EXPR_REFERENCE) {
6648 const declaration_t *declaration = expression->reference.declaration;
6649 return is_local_var_declaration(declaration);
6653 * Check if a given expression represents a local variable and
6654 * return its declaration then, else return NULL.
6656 declaration_t *expr_is_variable(const expression_t *expression)
6658 if (expression->base.kind != EXPR_REFERENCE) {
6661 declaration_t *declaration = expression->reference.declaration;
6662 if (is_var_declaration(declaration))
6668 * Parse a return statement.
6670 static statement_t *parse_return(void)
6674 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6675 statement->base.source_position = token.source_position;
6677 expression_t *return_value = NULL;
6678 if(token.type != ';') {
6679 return_value = parse_expression();
6683 const type_t *const func_type = current_function->type;
6684 assert(is_type_function(func_type));
6685 type_t *const return_type = skip_typeref(func_type->function.return_type);
6687 if(return_value != NULL) {
6688 type_t *return_value_type = skip_typeref(return_value->base.type);
6690 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6691 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6692 warningf(statement->base.source_position,
6693 "'return' with a value, in function returning void");
6694 return_value = NULL;
6696 type_t *const res_type = semantic_assign(return_type,
6697 return_value, "'return'");
6698 if (res_type == NULL) {
6699 errorf(statement->base.source_position,
6700 "cannot return something of type '%T' in function returning '%T'",
6701 return_value->base.type, return_type);
6703 return_value = create_implicit_cast(return_value, res_type);
6706 /* check for returning address of a local var */
6707 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6708 const expression_t *expression = return_value->unary.value;
6709 if (is_local_variable(expression)) {
6710 warningf(statement->base.source_position,
6711 "function returns address of local variable");
6715 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6716 warningf(statement->base.source_position,
6717 "'return' without value, in function returning non-void");
6720 statement->returns.value = return_value;
6724 return create_invalid_statement();
6728 * Parse a declaration statement.
6730 static statement_t *parse_declaration_statement(void)
6732 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6734 statement->base.source_position = token.source_position;
6736 declaration_t *before = last_declaration;
6737 parse_declaration(record_declaration);
6739 if(before == NULL) {
6740 statement->declaration.declarations_begin = scope->declarations;
6742 statement->declaration.declarations_begin = before->next;
6744 statement->declaration.declarations_end = last_declaration;
6750 * Parse an expression statement, ie. expr ';'.
6752 static statement_t *parse_expression_statement(void)
6754 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6756 statement->base.source_position = token.source_position;
6757 expression_t *const expr = parse_expression();
6758 statement->expression.expression = expr;
6760 if (warning.unused_value && !expression_has_effect(expr)) {
6761 warningf(expr->base.source_position, "statement has no effect");
6768 return create_invalid_statement();
6772 * Parse a statement.
6774 static statement_t *parse_statement(void)
6776 statement_t *statement = NULL;
6778 /* declaration or statement */
6779 add_anchor_token(';');
6780 switch(token.type) {
6782 statement = parse_asm_statement();
6786 statement = parse_case_statement();
6790 statement = parse_default_statement();
6794 statement = parse_compound_statement();
6798 statement = parse_if();
6802 statement = parse_switch();
6806 statement = parse_while();
6810 statement = parse_do();
6814 statement = parse_for();
6818 statement = parse_goto();
6822 statement = parse_continue();
6826 statement = parse_break();
6830 statement = parse_return();
6834 if(warning.empty_statement) {
6835 warningf(HERE, "statement is empty");
6837 statement = create_empty_statement();
6842 if(look_ahead(1)->type == ':') {
6843 statement = parse_label_statement();
6847 if(is_typedef_symbol(token.v.symbol)) {
6848 statement = parse_declaration_statement();
6852 statement = parse_expression_statement();
6855 case T___extension__:
6856 /* this can be a prefix to a declaration or an expression statement */
6857 /* we simply eat it now and parse the rest with tail recursion */
6860 } while(token.type == T___extension__);
6861 statement = parse_statement();
6865 statement = parse_declaration_statement();
6869 statement = parse_expression_statement();
6872 rem_anchor_token(';');
6874 assert(statement != NULL
6875 && statement->base.source_position.input_name != NULL);
6881 * Parse a compound statement.
6883 static statement_t *parse_compound_statement(void)
6885 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6887 statement->base.source_position = token.source_position;
6890 add_anchor_token('}');
6892 int top = environment_top();
6893 scope_t *last_scope = scope;
6894 set_scope(&statement->compound.scope);
6896 statement_t *last_statement = NULL;
6898 while(token.type != '}' && token.type != T_EOF) {
6899 statement_t *sub_statement = parse_statement();
6900 if(is_invalid_statement(sub_statement)) {
6901 /* an error occurred. if we are at an anchor, return */
6907 if(last_statement != NULL) {
6908 last_statement->base.next = sub_statement;
6910 statement->compound.statements = sub_statement;
6913 while(sub_statement->base.next != NULL)
6914 sub_statement = sub_statement->base.next;
6916 last_statement = sub_statement;
6919 if(token.type == '}') {
6922 errorf(statement->base.source_position,
6923 "end of file while looking for closing '}'");
6927 rem_anchor_token('}');
6928 assert(scope == &statement->compound.scope);
6929 set_scope(last_scope);
6930 environment_pop_to(top);
6936 * Initialize builtin types.
6938 static void initialize_builtin_types(void)
6940 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
6941 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
6942 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
6943 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
6944 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
6945 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6946 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
6947 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
6949 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
6950 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6951 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
6952 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
6956 * Check for unused global static functions and variables
6958 static void check_unused_globals(void)
6960 if (!warning.unused_function && !warning.unused_variable)
6963 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6964 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6967 type_t *const type = decl->type;
6969 if (is_type_function(skip_typeref(type))) {
6970 if (!warning.unused_function || decl->is_inline)
6973 s = (decl->init.statement != NULL ? "defined" : "declared");
6975 if (!warning.unused_variable)
6981 warningf(decl->source_position, "'%#T' %s but not used",
6982 type, decl->symbol, s);
6987 * Parse a translation unit.
6989 static translation_unit_t *parse_translation_unit(void)
6991 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6993 assert(global_scope == NULL);
6994 global_scope = &unit->scope;
6996 assert(scope == NULL);
6997 set_scope(&unit->scope);
6999 initialize_builtin_types();
7001 while(token.type != T_EOF) {
7002 if (token.type == ';') {
7003 /* TODO error in strict mode */
7004 warningf(HERE, "stray ';' outside of function");
7007 parse_external_declaration();
7011 assert(scope == &unit->scope);
7013 last_declaration = NULL;
7015 assert(global_scope == &unit->scope);
7016 check_unused_globals();
7017 global_scope = NULL;
7025 * @return the translation unit or NULL if errors occurred.
7027 translation_unit_t *parse(void)
7029 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7030 label_stack = NEW_ARR_F(stack_entry_t, 0);
7031 diagnostic_count = 0;
7035 type_set_output(stderr);
7036 ast_set_output(stderr);
7038 lookahead_bufpos = 0;
7039 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7042 translation_unit_t *unit = parse_translation_unit();
7044 DEL_ARR_F(environment_stack);
7045 DEL_ARR_F(label_stack);
7051 * Initialize the parser.
7053 void init_parser(void)
7056 /* add predefined symbols for extended-decl-modifier */
7057 sym_align = symbol_table_insert("align");
7058 sym_allocate = symbol_table_insert("allocate");
7059 sym_dllimport = symbol_table_insert("dllimport");
7060 sym_dllexport = symbol_table_insert("dllexport");
7061 sym_naked = symbol_table_insert("naked");
7062 sym_noinline = symbol_table_insert("noinline");
7063 sym_noreturn = symbol_table_insert("noreturn");
7064 sym_nothrow = symbol_table_insert("nothrow");
7065 sym_novtable = symbol_table_insert("novtable");
7066 sym_property = symbol_table_insert("property");
7067 sym_get = symbol_table_insert("get");
7068 sym_put = symbol_table_insert("put");
7069 sym_selectany = symbol_table_insert("selectany");
7070 sym_thread = symbol_table_insert("thread");
7071 sym_uuid = symbol_table_insert("uuid");
7072 sym_deprecated = symbol_table_insert("deprecated");
7073 sym_restrict = symbol_table_insert("restrict");
7074 sym_noalias = symbol_table_insert("noalias");
7076 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7078 init_expression_parsers();
7079 obstack_init(&temp_obst);
7081 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7082 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7086 * Terminate the parser.
7088 void exit_parser(void)
7090 obstack_free(&temp_obst, NULL);