2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 //#define PRINT_TOKENS
43 #define MAX_LOOKAHEAD 2
46 declaration_t *old_declaration;
48 unsigned short namespc;
51 typedef struct declaration_specifiers_t declaration_specifiers_t;
52 struct declaration_specifiers_t {
53 source_position_t source_position;
54 unsigned char declared_storage_class;
55 unsigned char alignment; /**< Alignment, 0 if not set. */
56 unsigned int is_inline : 1;
57 unsigned int deprecated : 1;
58 decl_modifiers_t decl_modifiers; /**< MS __declspec extended modifier mask */
59 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
60 symbol_t *get_property_sym; /**< the name of the get property if set. */
61 symbol_t *put_property_sym; /**< the name of the put property if set. */
66 * An environment for parsing initializers (and compound literals).
68 typedef struct parse_initializer_env_t {
69 type_t *type; /**< the type of the initializer. In case of an
70 array type with unspecified size this gets
71 adjusted to the actual size. */
72 declaration_t *declaration; /**< the declaration that is initialized if any */
73 bool must_be_constant;
74 } parse_initializer_env_t;
76 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
79 static token_t lookahead_buffer[MAX_LOOKAHEAD];
80 static int lookahead_bufpos;
81 static stack_entry_t *environment_stack = NULL;
82 static stack_entry_t *label_stack = NULL;
83 static scope_t *global_scope = NULL;
84 static scope_t *scope = NULL;
85 static declaration_t *last_declaration = NULL;
86 static declaration_t *current_function = NULL;
87 static switch_statement_t *current_switch = NULL;
88 static statement_t *current_loop = NULL;
89 static goto_statement_t *goto_first = NULL;
90 static goto_statement_t *goto_last = NULL;
91 static label_statement_t *label_first = NULL;
92 static label_statement_t *label_last = NULL;
93 static struct obstack temp_obst;
95 /* symbols for Microsoft extended-decl-modifier */
96 static const symbol_t *sym_align = NULL;
97 static const symbol_t *sym_allocate = NULL;
98 static const symbol_t *sym_dllimport = NULL;
99 static const symbol_t *sym_dllexport = NULL;
100 static const symbol_t *sym_naked = NULL;
101 static const symbol_t *sym_noinline = NULL;
102 static const symbol_t *sym_noreturn = NULL;
103 static const symbol_t *sym_nothrow = NULL;
104 static const symbol_t *sym_novtable = NULL;
105 static const symbol_t *sym_property = NULL;
106 static const symbol_t *sym_get = NULL;
107 static const symbol_t *sym_put = NULL;
108 static const symbol_t *sym_selectany = NULL;
109 static const symbol_t *sym_thread = NULL;
110 static const symbol_t *sym_uuid = NULL;
111 static const symbol_t *sym_deprecated = NULL;
112 static const symbol_t *sym_restrict = NULL;
113 static const symbol_t *sym_noalias = NULL;
115 /** The token anchor set */
116 static unsigned char token_anchor_set[T_LAST_TOKEN];
118 /** The current source position. */
119 #define HERE token.source_position
121 static type_t *type_valist;
123 static statement_t *parse_compound_statement(void);
124 static statement_t *parse_statement(void);
126 static expression_t *parse_sub_expression(unsigned precedence);
127 static expression_t *parse_expression(void);
128 static type_t *parse_typename(void);
130 static void parse_compound_type_entries(declaration_t *compound_declaration);
131 static declaration_t *parse_declarator(
132 const declaration_specifiers_t *specifiers, bool may_be_abstract);
133 static declaration_t *record_declaration(declaration_t *declaration);
135 static void semantic_comparison(binary_expression_t *expression);
137 #define STORAGE_CLASSES \
144 #define TYPE_QUALIFIERS \
151 #ifdef PROVIDE_COMPLEX
152 #define COMPLEX_SPECIFIERS \
154 #define IMAGINARY_SPECIFIERS \
157 #define COMPLEX_SPECIFIERS
158 #define IMAGINARY_SPECIFIERS
161 #define TYPE_SPECIFIERS \
176 case T___builtin_va_list: \
181 #define DECLARATION_START \
186 #define TYPENAME_START \
191 * Allocate an AST node with given size and
192 * initialize all fields with zero.
194 static void *allocate_ast_zero(size_t size)
196 void *res = allocate_ast(size);
197 memset(res, 0, size);
201 static declaration_t *allocate_declaration_zero(void)
203 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
204 declaration->type = type_error_type;
205 declaration->alignment = 0;
210 * Returns the size of a statement node.
212 * @param kind the statement kind
214 static size_t get_statement_struct_size(statement_kind_t kind)
216 static const size_t sizes[] = {
217 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
218 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
219 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
220 [STATEMENT_RETURN] = sizeof(return_statement_t),
221 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
222 [STATEMENT_IF] = sizeof(if_statement_t),
223 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
224 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
225 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
226 [STATEMENT_BREAK] = sizeof(statement_base_t),
227 [STATEMENT_GOTO] = sizeof(goto_statement_t),
228 [STATEMENT_LABEL] = sizeof(label_statement_t),
229 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
230 [STATEMENT_WHILE] = sizeof(while_statement_t),
231 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
232 [STATEMENT_FOR] = sizeof(for_statement_t),
233 [STATEMENT_ASM] = sizeof(asm_statement_t)
235 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
236 assert(sizes[kind] != 0);
241 * Allocate a statement node of given kind and initialize all
244 static statement_t *allocate_statement_zero(statement_kind_t kind)
246 size_t size = get_statement_struct_size(kind);
247 statement_t *res = allocate_ast_zero(size);
249 res->base.kind = kind;
254 * Creates a new invalid statement.
256 static statement_t *create_invalid_statement(void)
258 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
259 statement->base.source_position = token.source_position;
264 * Allocate a new empty statement.
266 static statement_t *create_empty_statement(void)
268 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
269 statement->base.source_position = token.source_position;
274 * Returns the size of an expression node.
276 * @param kind the expression kind
278 static size_t get_expression_struct_size(expression_kind_t kind)
280 static const size_t sizes[] = {
281 [EXPR_INVALID] = sizeof(expression_base_t),
282 [EXPR_REFERENCE] = sizeof(reference_expression_t),
283 [EXPR_CONST] = sizeof(const_expression_t),
284 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
285 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
286 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
287 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
288 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
289 [EXPR_CALL] = sizeof(call_expression_t),
290 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
291 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
292 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
293 [EXPR_SELECT] = sizeof(select_expression_t),
294 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
295 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
296 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
297 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
298 [EXPR_FUNCTION] = sizeof(string_literal_expression_t),
299 [EXPR_PRETTY_FUNCTION] = sizeof(string_literal_expression_t),
300 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
301 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
302 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
303 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
304 [EXPR_VA_START] = sizeof(va_start_expression_t),
305 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
306 [EXPR_STATEMENT] = sizeof(statement_expression_t),
308 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
309 return sizes[EXPR_UNARY_FIRST];
311 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
312 return sizes[EXPR_BINARY_FIRST];
314 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
315 assert(sizes[kind] != 0);
320 * Allocate an expression node of given kind and initialize all
323 static expression_t *allocate_expression_zero(expression_kind_t kind)
325 size_t size = get_expression_struct_size(kind);
326 expression_t *res = allocate_ast_zero(size);
328 res->base.kind = kind;
329 res->base.type = type_error_type;
334 * Returns the size of a type node.
336 * @param kind the type kind
338 static size_t get_type_struct_size(type_kind_t kind)
340 static const size_t sizes[] = {
341 [TYPE_ATOMIC] = sizeof(atomic_type_t),
342 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
343 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
344 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
345 [TYPE_ENUM] = sizeof(enum_type_t),
346 [TYPE_FUNCTION] = sizeof(function_type_t),
347 [TYPE_POINTER] = sizeof(pointer_type_t),
348 [TYPE_ARRAY] = sizeof(array_type_t),
349 [TYPE_BUILTIN] = sizeof(builtin_type_t),
350 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
351 [TYPE_TYPEOF] = sizeof(typeof_type_t),
353 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
354 assert(kind <= TYPE_TYPEOF);
355 assert(sizes[kind] != 0);
360 * Allocate a type node of given kind and initialize all
363 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
365 size_t size = get_type_struct_size(kind);
366 type_t *res = obstack_alloc(type_obst, size);
367 memset(res, 0, size);
369 res->base.kind = kind;
370 res->base.source_position = source_position;
375 * Returns the size of an initializer node.
377 * @param kind the initializer kind
379 static size_t get_initializer_size(initializer_kind_t kind)
381 static const size_t sizes[] = {
382 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
383 [INITIALIZER_STRING] = sizeof(initializer_string_t),
384 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
385 [INITIALIZER_LIST] = sizeof(initializer_list_t),
386 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
388 assert(kind < sizeof(sizes) / sizeof(*sizes));
389 assert(sizes[kind] != 0);
394 * Allocate an initializer node of given kind and initialize all
397 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
399 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
406 * Free a type from the type obstack.
408 static void free_type(void *type)
410 obstack_free(type_obst, type);
414 * Returns the index of the top element of the environment stack.
416 static size_t environment_top(void)
418 return ARR_LEN(environment_stack);
422 * Returns the index of the top element of the label stack.
424 static size_t label_top(void)
426 return ARR_LEN(label_stack);
430 * Return the next token.
432 static inline void next_token(void)
434 token = lookahead_buffer[lookahead_bufpos];
435 lookahead_buffer[lookahead_bufpos] = lexer_token;
438 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
441 print_token(stderr, &token);
442 fprintf(stderr, "\n");
447 * Return the next token with a given lookahead.
449 static inline const token_t *look_ahead(int num)
451 assert(num > 0 && num <= MAX_LOOKAHEAD);
452 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
453 return &lookahead_buffer[pos];
457 * Adds a token to the token anchor set (a multi-set).
459 static void add_anchor_token(int token_type) {
460 assert(0 <= token_type && token_type < T_LAST_TOKEN);
461 ++token_anchor_set[token_type];
465 * Remove a token from the token anchor set (a multi-set).
467 static void rem_anchor_token(int token_type) {
468 assert(0 <= token_type && token_type < T_LAST_TOKEN);
469 --token_anchor_set[token_type];
472 static bool at_anchor(void) {
475 return token_anchor_set[token.type];
479 * Eat tokens until a matching token is found.
481 static void eat_until_matching_token(int type) {
482 unsigned parenthesis_count = 0;
483 unsigned brace_count = 0;
484 unsigned bracket_count = 0;
485 int end_token = type;
494 while(token.type != end_token ||
495 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
499 case '(': ++parenthesis_count; break;
500 case '{': ++brace_count; break;
501 case '[': ++bracket_count; break;
503 if(parenthesis_count > 0)
511 if(bracket_count > 0)
522 * Eat input tokens until an anchor is found.
524 static void eat_until_anchor(void) {
525 if(token.type == T_EOF)
527 while(token_anchor_set[token.type] == 0) {
528 if(token.type == '(' || token.type == '{' || token.type == '[')
529 eat_until_matching_token(token.type);
530 if(token.type == T_EOF)
536 static void eat_block(void) {
537 eat_until_matching_token('{');
538 if(token.type == '}')
543 * eat all token until a ';' is reached
544 * or a stop token is found.
546 static void eat_statement(void) {
547 eat_until_matching_token(';');
548 if(token.type == ';')
552 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
555 * Report a parse error because an expected token was not found.
557 static void parse_error_expected(const char *message, ...)
559 if(message != NULL) {
560 errorf(HERE, "%s", message);
563 va_start(ap, message);
564 errorf(HERE, "got %K, expected %#k", &token, &ap, "a ");
569 * Report a type error.
571 static void type_error(const char *msg, const source_position_t source_position,
574 errorf(source_position, "%s, but found type '%T'", msg, type);
578 * Report an incompatible type.
580 static void type_error_incompatible(const char *msg,
581 const source_position_t source_position, type_t *type1, type_t *type2)
583 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
587 * Expect the the current token is the expected token.
588 * If not, generate an error, eat the current statement,
589 * and goto the end_error label.
591 #define expect(expected) \
593 if(UNLIKELY(token.type != (expected))) { \
594 parse_error_expected(NULL, (expected), 0); \
595 add_anchor_token(expected); \
596 eat_until_anchor(); \
597 rem_anchor_token(expected); \
603 static void set_scope(scope_t *new_scope)
606 scope->last_declaration = last_declaration;
610 last_declaration = new_scope->last_declaration;
614 * Search a symbol in a given namespace and returns its declaration or
615 * NULL if this symbol was not found.
617 static declaration_t *get_declaration(const symbol_t *const symbol,
618 const namespace_t namespc)
620 declaration_t *declaration = symbol->declaration;
621 for( ; declaration != NULL; declaration = declaration->symbol_next) {
622 if(declaration->namespc == namespc)
630 * pushs an environment_entry on the environment stack and links the
631 * corresponding symbol to the new entry
633 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
635 symbol_t *symbol = declaration->symbol;
636 namespace_t namespc = (namespace_t) declaration->namespc;
638 /* replace/add declaration into declaration list of the symbol */
639 declaration_t *iter = symbol->declaration;
641 symbol->declaration = declaration;
643 declaration_t *iter_last = NULL;
644 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
645 /* replace an entry? */
646 if(iter->namespc == namespc) {
647 if(iter_last == NULL) {
648 symbol->declaration = declaration;
650 iter_last->symbol_next = declaration;
652 declaration->symbol_next = iter->symbol_next;
657 assert(iter_last->symbol_next == NULL);
658 iter_last->symbol_next = declaration;
662 /* remember old declaration */
664 entry.symbol = symbol;
665 entry.old_declaration = iter;
666 entry.namespc = (unsigned short) namespc;
667 ARR_APP1(stack_entry_t, *stack_ptr, entry);
670 static void environment_push(declaration_t *declaration)
672 assert(declaration->source_position.input_name != NULL);
673 assert(declaration->parent_scope != NULL);
674 stack_push(&environment_stack, declaration);
677 static void label_push(declaration_t *declaration)
679 declaration->parent_scope = ¤t_function->scope;
680 stack_push(&label_stack, declaration);
684 * pops symbols from the environment stack until @p new_top is the top element
686 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
688 stack_entry_t *stack = *stack_ptr;
689 size_t top = ARR_LEN(stack);
692 assert(new_top <= top);
696 for(i = top; i > new_top; --i) {
697 stack_entry_t *entry = &stack[i - 1];
699 declaration_t *old_declaration = entry->old_declaration;
700 symbol_t *symbol = entry->symbol;
701 namespace_t namespc = (namespace_t)entry->namespc;
703 /* replace/remove declaration */
704 declaration_t *declaration = symbol->declaration;
705 assert(declaration != NULL);
706 if(declaration->namespc == namespc) {
707 if(old_declaration == NULL) {
708 symbol->declaration = declaration->symbol_next;
710 symbol->declaration = old_declaration;
713 declaration_t *iter_last = declaration;
714 declaration_t *iter = declaration->symbol_next;
715 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
716 /* replace an entry? */
717 if(iter->namespc == namespc) {
718 assert(iter_last != NULL);
719 iter_last->symbol_next = old_declaration;
720 if(old_declaration != NULL) {
721 old_declaration->symbol_next = iter->symbol_next;
726 assert(iter != NULL);
730 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
733 static void environment_pop_to(size_t new_top)
735 stack_pop_to(&environment_stack, new_top);
738 static void label_pop_to(size_t new_top)
740 stack_pop_to(&label_stack, new_top);
744 static int get_rank(const type_t *type)
746 assert(!is_typeref(type));
747 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
748 * and esp. footnote 108). However we can't fold constants (yet), so we
749 * can't decide whether unsigned int is possible, while int always works.
750 * (unsigned int would be preferable when possible... for stuff like
751 * struct { enum { ... } bla : 4; } ) */
752 if(type->kind == TYPE_ENUM)
753 return ATOMIC_TYPE_INT;
755 assert(type->kind == TYPE_ATOMIC);
756 return type->atomic.akind;
759 static type_t *promote_integer(type_t *type)
761 if(type->kind == TYPE_BITFIELD)
762 type = type->bitfield.base;
764 if(get_rank(type) < ATOMIC_TYPE_INT)
771 * Create a cast expression.
773 * @param expression the expression to cast
774 * @param dest_type the destination type
776 static expression_t *create_cast_expression(expression_t *expression,
779 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
781 cast->unary.value = expression;
782 cast->base.type = dest_type;
788 * Check if a given expression represents the 0 pointer constant.
790 static bool is_null_pointer_constant(const expression_t *expression)
792 /* skip void* cast */
793 if(expression->kind == EXPR_UNARY_CAST
794 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
795 expression = expression->unary.value;
798 /* TODO: not correct yet, should be any constant integer expression
799 * which evaluates to 0 */
800 if (expression->kind != EXPR_CONST)
803 type_t *const type = skip_typeref(expression->base.type);
804 if (!is_type_integer(type))
807 return expression->conste.v.int_value == 0;
811 * Create an implicit cast expression.
813 * @param expression the expression to cast
814 * @param dest_type the destination type
816 static expression_t *create_implicit_cast(expression_t *expression,
819 type_t *const source_type = expression->base.type;
821 if (source_type == dest_type)
824 return create_cast_expression(expression, dest_type);
827 /** Implements the rules from § 6.5.16.1 */
828 static type_t *semantic_assign(type_t *orig_type_left,
829 const expression_t *const right,
832 type_t *const orig_type_right = right->base.type;
833 type_t *const type_left = skip_typeref(orig_type_left);
834 type_t *const type_right = skip_typeref(orig_type_right);
836 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
837 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
838 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
839 && is_type_pointer(type_right))) {
840 return orig_type_left;
843 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
844 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
845 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
847 /* the left type has all qualifiers from the right type */
848 unsigned missing_qualifiers
849 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
850 if(missing_qualifiers != 0) {
851 errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
852 return orig_type_left;
855 points_to_left = get_unqualified_type(points_to_left);
856 points_to_right = get_unqualified_type(points_to_right);
858 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
859 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
860 return orig_type_left;
863 if (!types_compatible(points_to_left, points_to_right)) {
864 warningf(right->base.source_position,
865 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
866 orig_type_left, context, right, orig_type_right);
869 return orig_type_left;
872 if ((is_type_compound(type_left) && is_type_compound(type_right))
873 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
874 type_t *const unqual_type_left = get_unqualified_type(type_left);
875 type_t *const unqual_type_right = get_unqualified_type(type_right);
876 if (types_compatible(unqual_type_left, unqual_type_right)) {
877 return orig_type_left;
881 if (!is_type_valid(type_left))
884 if (!is_type_valid(type_right))
885 return orig_type_right;
890 static expression_t *parse_constant_expression(void)
892 /* start parsing at precedence 7 (conditional expression) */
893 expression_t *result = parse_sub_expression(7);
895 if(!is_constant_expression(result)) {
896 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
902 static expression_t *parse_assignment_expression(void)
904 /* start parsing at precedence 2 (assignment expression) */
905 return parse_sub_expression(2);
908 static type_t *make_global_typedef(const char *name, type_t *type)
910 symbol_t *const symbol = symbol_table_insert(name);
912 declaration_t *const declaration = allocate_declaration_zero();
913 declaration->namespc = NAMESPACE_NORMAL;
914 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
915 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
916 declaration->type = type;
917 declaration->symbol = symbol;
918 declaration->source_position = builtin_source_position;
920 record_declaration(declaration);
922 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
923 typedef_type->typedeft.declaration = declaration;
928 static string_t parse_string_literals(void)
930 assert(token.type == T_STRING_LITERAL);
931 string_t result = token.v.string;
935 while (token.type == T_STRING_LITERAL) {
936 result = concat_strings(&result, &token.v.string);
944 * Parse one GNU attribute.
946 static void parse_gnu_attribute(void)
948 eat(T___attribute__);
952 if(token.type != T_IDENTIFIER)
954 symbol_t *symbol = token.v.symbol;
956 if(token.type == '(')
957 eat_until_matching_token('(');
958 if(token.type != ',')
969 * Parse GNU attributes.
971 static void parse_attributes(void)
975 case T___attribute__: {
976 parse_gnu_attribute();
982 if(token.type != T_STRING_LITERAL) {
983 parse_error_expected("while parsing assembler attribute",
985 eat_until_matching_token('(');
988 parse_string_literals();
993 goto attributes_finished;
1002 static designator_t *parse_designation(void)
1004 designator_t *result = NULL;
1005 designator_t *last = NULL;
1008 designator_t *designator;
1009 switch(token.type) {
1011 designator = allocate_ast_zero(sizeof(designator[0]));
1012 designator->source_position = token.source_position;
1014 add_anchor_token(']');
1015 designator->array_index = parse_constant_expression();
1016 rem_anchor_token(']');
1020 designator = allocate_ast_zero(sizeof(designator[0]));
1021 designator->source_position = token.source_position;
1023 if(token.type != T_IDENTIFIER) {
1024 parse_error_expected("while parsing designator",
1028 designator->symbol = token.v.symbol;
1036 assert(designator != NULL);
1038 last->next = designator;
1040 result = designator;
1048 static initializer_t *initializer_from_string(array_type_t *type,
1049 const string_t *const string)
1051 /* TODO: check len vs. size of array type */
1054 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1055 initializer->string.string = *string;
1060 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1061 wide_string_t *const string)
1063 /* TODO: check len vs. size of array type */
1066 initializer_t *const initializer =
1067 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1068 initializer->wide_string.string = *string;
1074 * Build an initializer from a given expression.
1076 static initializer_t *initializer_from_expression(type_t *orig_type,
1077 expression_t *expression)
1079 /* TODO check that expression is a constant expression */
1081 /* § 6.7.8.14/15 char array may be initialized by string literals */
1082 type_t *type = skip_typeref(orig_type);
1083 type_t *expr_type_orig = expression->base.type;
1084 type_t *expr_type = skip_typeref(expr_type_orig);
1085 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1086 array_type_t *const array_type = &type->array;
1087 type_t *const element_type = skip_typeref(array_type->element_type);
1089 if (element_type->kind == TYPE_ATOMIC) {
1090 atomic_type_kind_t akind = element_type->atomic.akind;
1091 switch (expression->kind) {
1092 case EXPR_STRING_LITERAL:
1093 if (akind == ATOMIC_TYPE_CHAR
1094 || akind == ATOMIC_TYPE_SCHAR
1095 || akind == ATOMIC_TYPE_UCHAR) {
1096 return initializer_from_string(array_type,
1097 &expression->string.value);
1100 case EXPR_WIDE_STRING_LITERAL: {
1101 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1102 if (get_unqualified_type(element_type) == bare_wchar_type) {
1103 return initializer_from_wide_string(array_type,
1104 &expression->wide_string.value);
1114 type_t *const res_type = semantic_assign(type, expression, "initializer");
1115 if (res_type == NULL)
1118 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1119 result->value.value = create_implicit_cast(expression, res_type);
1125 * Checks if a given expression can be used as an constant initializer.
1127 static bool is_initializer_constant(const expression_t *expression)
1129 return is_constant_expression(expression)
1130 || is_address_constant(expression);
1134 * Parses an scalar initializer.
1136 * § 6.7.8.11; eat {} without warning
1138 static initializer_t *parse_scalar_initializer(type_t *type,
1139 bool must_be_constant)
1141 /* there might be extra {} hierarchies */
1143 while(token.type == '{') {
1146 warningf(HERE, "extra curly braces around scalar initializer");
1151 expression_t *expression = parse_assignment_expression();
1152 if(must_be_constant && !is_initializer_constant(expression)) {
1153 errorf(expression->base.source_position,
1154 "Initialisation expression '%E' is not constant\n",
1158 initializer_t *initializer = initializer_from_expression(type, expression);
1160 if(initializer == NULL) {
1161 errorf(expression->base.source_position,
1162 "expression '%E' doesn't match expected type '%T'",
1168 bool additional_warning_displayed = false;
1170 if(token.type == ',') {
1173 if(token.type != '}') {
1174 if(!additional_warning_displayed) {
1175 warningf(HERE, "additional elements in scalar initializer");
1176 additional_warning_displayed = true;
1187 * An entry in the type path.
1189 typedef struct type_path_entry_t type_path_entry_t;
1190 struct type_path_entry_t {
1191 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1193 size_t index; /**< For array types: the current index. */
1194 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1199 * A type path expression a position inside compound or array types.
1201 typedef struct type_path_t type_path_t;
1202 struct type_path_t {
1203 type_path_entry_t *path; /**< An flexible array containing the current path. */
1204 type_t *top_type; /**< type of the element the path points */
1205 size_t max_index; /**< largest index in outermost array */
1209 * Prints a type path for debugging.
1211 static __attribute__((unused)) void debug_print_type_path(
1212 const type_path_t *path)
1214 size_t len = ARR_LEN(path->path);
1216 for(size_t i = 0; i < len; ++i) {
1217 const type_path_entry_t *entry = & path->path[i];
1219 type_t *type = skip_typeref(entry->type);
1220 if(is_type_compound(type)) {
1221 /* in gcc mode structs can have no members */
1222 if(entry->v.compound_entry == NULL) {
1226 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1227 } else if(is_type_array(type)) {
1228 fprintf(stderr, "[%u]", entry->v.index);
1230 fprintf(stderr, "-INVALID-");
1233 if(path->top_type != NULL) {
1234 fprintf(stderr, " (");
1235 print_type(path->top_type);
1236 fprintf(stderr, ")");
1241 * Return the top type path entry, ie. in a path
1242 * (type).a.b returns the b.
1244 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1246 size_t len = ARR_LEN(path->path);
1248 return &path->path[len-1];
1252 * Enlarge the type path by an (empty) element.
1254 static type_path_entry_t *append_to_type_path(type_path_t *path)
1256 size_t len = ARR_LEN(path->path);
1257 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1259 type_path_entry_t *result = & path->path[len];
1260 memset(result, 0, sizeof(result[0]));
1265 * Descending into a sub-type. Enter the scope of the current
1268 static void descend_into_subtype(type_path_t *path)
1270 type_t *orig_top_type = path->top_type;
1271 type_t *top_type = skip_typeref(orig_top_type);
1273 assert(is_type_compound(top_type) || is_type_array(top_type));
1275 type_path_entry_t *top = append_to_type_path(path);
1276 top->type = top_type;
1278 if(is_type_compound(top_type)) {
1279 declaration_t *declaration = top_type->compound.declaration;
1280 declaration_t *entry = declaration->scope.declarations;
1281 top->v.compound_entry = entry;
1284 path->top_type = entry->type;
1286 path->top_type = NULL;
1289 assert(is_type_array(top_type));
1292 path->top_type = top_type->array.element_type;
1297 * Pop an entry from the given type path, ie. returning from
1298 * (type).a.b to (type).a
1300 static void ascend_from_subtype(type_path_t *path)
1302 type_path_entry_t *top = get_type_path_top(path);
1304 path->top_type = top->type;
1306 size_t len = ARR_LEN(path->path);
1307 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1311 * Pop entries from the given type path until the given
1312 * path level is reached.
1314 static void ascend_to(type_path_t *path, size_t top_path_level)
1316 size_t len = ARR_LEN(path->path);
1318 while(len > top_path_level) {
1319 ascend_from_subtype(path);
1320 len = ARR_LEN(path->path);
1324 static bool walk_designator(type_path_t *path, const designator_t *designator,
1325 bool used_in_offsetof)
1327 for( ; designator != NULL; designator = designator->next) {
1328 type_path_entry_t *top = get_type_path_top(path);
1329 type_t *orig_type = top->type;
1331 type_t *type = skip_typeref(orig_type);
1333 if(designator->symbol != NULL) {
1334 symbol_t *symbol = designator->symbol;
1335 if(!is_type_compound(type)) {
1336 if(is_type_valid(type)) {
1337 errorf(designator->source_position,
1338 "'.%Y' designator used for non-compound type '%T'",
1344 declaration_t *declaration = type->compound.declaration;
1345 declaration_t *iter = declaration->scope.declarations;
1346 for( ; iter != NULL; iter = iter->next) {
1347 if(iter->symbol == symbol) {
1352 errorf(designator->source_position,
1353 "'%T' has no member named '%Y'", orig_type, symbol);
1356 if(used_in_offsetof) {
1357 type_t *real_type = skip_typeref(iter->type);
1358 if(real_type->kind == TYPE_BITFIELD) {
1359 errorf(designator->source_position,
1360 "offsetof designator '%Y' may not specify bitfield",
1366 top->type = orig_type;
1367 top->v.compound_entry = iter;
1368 orig_type = iter->type;
1370 expression_t *array_index = designator->array_index;
1371 assert(designator->array_index != NULL);
1373 if(!is_type_array(type)) {
1374 if(is_type_valid(type)) {
1375 errorf(designator->source_position,
1376 "[%E] designator used for non-array type '%T'",
1377 array_index, orig_type);
1381 if(!is_type_valid(array_index->base.type)) {
1385 long index = fold_constant(array_index);
1386 if(!used_in_offsetof) {
1388 errorf(designator->source_position,
1389 "array index [%E] must be positive", array_index);
1392 if(type->array.size_constant == true) {
1393 long array_size = type->array.size;
1394 if(index >= array_size) {
1395 errorf(designator->source_position,
1396 "designator [%E] (%d) exceeds array size %d",
1397 array_index, index, array_size);
1403 top->type = orig_type;
1404 top->v.index = (size_t) index;
1405 orig_type = type->array.element_type;
1407 path->top_type = orig_type;
1409 if(designator->next != NULL) {
1410 descend_into_subtype(path);
1419 static void advance_current_object(type_path_t *path, size_t top_path_level)
1421 type_path_entry_t *top = get_type_path_top(path);
1423 type_t *type = skip_typeref(top->type);
1424 if(is_type_union(type)) {
1425 /* in unions only the first element is initialized */
1426 top->v.compound_entry = NULL;
1427 } else if(is_type_struct(type)) {
1428 declaration_t *entry = top->v.compound_entry;
1430 entry = entry->next;
1431 top->v.compound_entry = entry;
1433 path->top_type = entry->type;
1437 assert(is_type_array(type));
1441 if(!type->array.size_constant || top->v.index < type->array.size) {
1446 /* we're past the last member of the current sub-aggregate, try if we
1447 * can ascend in the type hierarchy and continue with another subobject */
1448 size_t len = ARR_LEN(path->path);
1450 if(len > top_path_level) {
1451 ascend_from_subtype(path);
1452 advance_current_object(path, top_path_level);
1454 path->top_type = NULL;
1459 * skip until token is found.
1461 static void skip_until(int type) {
1462 while(token.type != type) {
1463 if(token.type == T_EOF)
1470 * skip any {...} blocks until a closing braket is reached.
1472 static void skip_initializers(void)
1474 if(token.type == '{')
1477 while(token.type != '}') {
1478 if(token.type == T_EOF)
1480 if(token.type == '{') {
1488 static initializer_t *create_empty_initializer(void)
1490 static initializer_t empty_initializer
1491 = { .list = { { INITIALIZER_LIST }, 0 } };
1492 return &empty_initializer;
1496 * Parse a part of an initialiser for a struct or union,
1498 static initializer_t *parse_sub_initializer(type_path_t *path,
1499 type_t *outer_type, size_t top_path_level,
1500 parse_initializer_env_t *env)
1502 if(token.type == '}') {
1503 /* empty initializer */
1504 return create_empty_initializer();
1507 type_t *orig_type = path->top_type;
1508 type_t *type = NULL;
1510 if (orig_type == NULL) {
1511 /* We are initializing an empty compound. */
1513 type = skip_typeref(orig_type);
1515 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1516 * initializers in this case. */
1517 if(!is_type_valid(type)) {
1518 skip_initializers();
1519 return create_empty_initializer();
1523 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1526 designator_t *designator = NULL;
1527 if(token.type == '.' || token.type == '[') {
1528 designator = parse_designation();
1530 /* reset path to toplevel, evaluate designator from there */
1531 ascend_to(path, top_path_level);
1532 if(!walk_designator(path, designator, false)) {
1533 /* can't continue after designation error */
1537 initializer_t *designator_initializer
1538 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1539 designator_initializer->designator.designator = designator;
1540 ARR_APP1(initializer_t*, initializers, designator_initializer);
1545 if(token.type == '{') {
1546 if(type != NULL && is_type_scalar(type)) {
1547 sub = parse_scalar_initializer(type, env->must_be_constant);
1551 if (env->declaration != NULL)
1552 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1553 env->declaration->symbol);
1555 errorf(HERE, "extra brace group at end of initializer");
1557 descend_into_subtype(path);
1559 add_anchor_token('}');
1560 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1562 rem_anchor_token('}');
1565 ascend_from_subtype(path);
1569 goto error_parse_next;
1573 /* must be an expression */
1574 expression_t *expression = parse_assignment_expression();
1576 if(env->must_be_constant && !is_initializer_constant(expression)) {
1577 errorf(expression->base.source_position,
1578 "Initialisation expression '%E' is not constant\n",
1583 /* we are already outside, ... */
1587 /* handle { "string" } special case */
1588 if((expression->kind == EXPR_STRING_LITERAL
1589 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1590 && outer_type != NULL) {
1591 sub = initializer_from_expression(outer_type, expression);
1593 if(token.type == ',') {
1596 if(token.type != '}') {
1597 warningf(HERE, "excessive elements in initializer for type '%T'",
1600 /* TODO: eat , ... */
1605 /* descend into subtypes until expression matches type */
1607 orig_type = path->top_type;
1608 type = skip_typeref(orig_type);
1610 sub = initializer_from_expression(orig_type, expression);
1614 if(!is_type_valid(type)) {
1617 if(is_type_scalar(type)) {
1618 errorf(expression->base.source_position,
1619 "expression '%E' doesn't match expected type '%T'",
1620 expression, orig_type);
1624 descend_into_subtype(path);
1628 /* update largest index of top array */
1629 const type_path_entry_t *first = &path->path[0];
1630 type_t *first_type = first->type;
1631 first_type = skip_typeref(first_type);
1632 if(is_type_array(first_type)) {
1633 size_t index = first->v.index;
1634 if(index > path->max_index)
1635 path->max_index = index;
1639 /* append to initializers list */
1640 ARR_APP1(initializer_t*, initializers, sub);
1643 if(env->declaration != NULL)
1644 warningf(HERE, "excess elements in struct initializer for '%Y'",
1645 env->declaration->symbol);
1647 warningf(HERE, "excess elements in struct initializer");
1651 if(token.type == '}') {
1655 if(token.type == '}') {
1660 /* advance to the next declaration if we are not at the end */
1661 advance_current_object(path, top_path_level);
1662 orig_type = path->top_type;
1663 if(orig_type != NULL)
1664 type = skip_typeref(orig_type);
1670 size_t len = ARR_LEN(initializers);
1671 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1672 initializer_t *result = allocate_ast_zero(size);
1673 result->kind = INITIALIZER_LIST;
1674 result->list.len = len;
1675 memcpy(&result->list.initializers, initializers,
1676 len * sizeof(initializers[0]));
1678 DEL_ARR_F(initializers);
1679 ascend_to(path, top_path_level);
1684 skip_initializers();
1685 DEL_ARR_F(initializers);
1686 ascend_to(path, top_path_level);
1691 * Parses an initializer. Parsers either a compound literal
1692 * (env->declaration == NULL) or an initializer of a declaration.
1694 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1696 type_t *type = skip_typeref(env->type);
1697 initializer_t *result = NULL;
1700 if(is_type_scalar(type)) {
1701 result = parse_scalar_initializer(type, env->must_be_constant);
1702 } else if(token.type == '{') {
1706 memset(&path, 0, sizeof(path));
1707 path.top_type = env->type;
1708 path.path = NEW_ARR_F(type_path_entry_t, 0);
1710 descend_into_subtype(&path);
1712 add_anchor_token('}');
1713 result = parse_sub_initializer(&path, env->type, 1, env);
1714 rem_anchor_token('}');
1716 max_index = path.max_index;
1717 DEL_ARR_F(path.path);
1721 /* parse_scalar_initializer() also works in this case: we simply
1722 * have an expression without {} around it */
1723 result = parse_scalar_initializer(type, env->must_be_constant);
1726 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1727 * the array type size */
1728 if(is_type_array(type) && type->array.size_expression == NULL
1729 && result != NULL) {
1731 switch (result->kind) {
1732 case INITIALIZER_LIST:
1733 size = max_index + 1;
1736 case INITIALIZER_STRING:
1737 size = result->string.string.size;
1740 case INITIALIZER_WIDE_STRING:
1741 size = result->wide_string.string.size;
1745 internal_errorf(HERE, "invalid initializer type");
1748 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1749 cnst->base.type = type_size_t;
1750 cnst->conste.v.int_value = size;
1752 type_t *new_type = duplicate_type(type);
1754 new_type->array.size_expression = cnst;
1755 new_type->array.size_constant = true;
1756 new_type->array.size = size;
1757 env->type = new_type;
1765 static declaration_t *append_declaration(declaration_t *declaration);
1767 static declaration_t *parse_compound_type_specifier(bool is_struct)
1775 symbol_t *symbol = NULL;
1776 declaration_t *declaration = NULL;
1778 if (token.type == T___attribute__) {
1783 if(token.type == T_IDENTIFIER) {
1784 symbol = token.v.symbol;
1788 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1790 declaration = get_declaration(symbol, NAMESPACE_UNION);
1792 } else if(token.type != '{') {
1794 parse_error_expected("while parsing struct type specifier",
1795 T_IDENTIFIER, '{', 0);
1797 parse_error_expected("while parsing union type specifier",
1798 T_IDENTIFIER, '{', 0);
1804 if(declaration == NULL) {
1805 declaration = allocate_declaration_zero();
1806 declaration->namespc =
1807 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1808 declaration->source_position = token.source_position;
1809 declaration->symbol = symbol;
1810 declaration->parent_scope = scope;
1811 if (symbol != NULL) {
1812 environment_push(declaration);
1814 append_declaration(declaration);
1817 if(token.type == '{') {
1818 if(declaration->init.is_defined) {
1819 assert(symbol != NULL);
1820 errorf(HERE, "multiple definitions of '%s %Y'",
1821 is_struct ? "struct" : "union", symbol);
1822 declaration->scope.declarations = NULL;
1824 declaration->init.is_defined = true;
1826 parse_compound_type_entries(declaration);
1833 static void parse_enum_entries(type_t *const enum_type)
1837 if(token.type == '}') {
1839 errorf(HERE, "empty enum not allowed");
1843 add_anchor_token('}');
1845 if(token.type != T_IDENTIFIER) {
1846 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1848 rem_anchor_token('}');
1852 declaration_t *const entry = allocate_declaration_zero();
1853 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1854 entry->type = enum_type;
1855 entry->symbol = token.v.symbol;
1856 entry->source_position = token.source_position;
1859 if(token.type == '=') {
1861 expression_t *value = parse_constant_expression();
1863 value = create_implicit_cast(value, enum_type);
1864 entry->init.enum_value = value;
1869 record_declaration(entry);
1871 if(token.type != ',')
1874 } while(token.type != '}');
1875 rem_anchor_token('}');
1883 static type_t *parse_enum_specifier(void)
1887 declaration_t *declaration;
1890 if(token.type == T_IDENTIFIER) {
1891 symbol = token.v.symbol;
1894 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1895 } else if(token.type != '{') {
1896 parse_error_expected("while parsing enum type specifier",
1897 T_IDENTIFIER, '{', 0);
1904 if(declaration == NULL) {
1905 declaration = allocate_declaration_zero();
1906 declaration->namespc = NAMESPACE_ENUM;
1907 declaration->source_position = token.source_position;
1908 declaration->symbol = symbol;
1909 declaration->parent_scope = scope;
1912 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1913 type->enumt.declaration = declaration;
1915 if(token.type == '{') {
1916 if(declaration->init.is_defined) {
1917 errorf(HERE, "multiple definitions of enum %Y", symbol);
1919 if (symbol != NULL) {
1920 environment_push(declaration);
1922 append_declaration(declaration);
1923 declaration->init.is_defined = 1;
1925 parse_enum_entries(type);
1933 * if a symbol is a typedef to another type, return true
1935 static bool is_typedef_symbol(symbol_t *symbol)
1937 const declaration_t *const declaration =
1938 get_declaration(symbol, NAMESPACE_NORMAL);
1940 declaration != NULL &&
1941 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1944 static type_t *parse_typeof(void)
1951 add_anchor_token(')');
1953 expression_t *expression = NULL;
1956 switch(token.type) {
1957 case T___extension__:
1958 /* this can be a prefix to a typename or an expression */
1959 /* we simply eat it now. */
1962 } while(token.type == T___extension__);
1966 if(is_typedef_symbol(token.v.symbol)) {
1967 type = parse_typename();
1969 expression = parse_expression();
1970 type = expression->base.type;
1975 type = parse_typename();
1979 expression = parse_expression();
1980 type = expression->base.type;
1984 rem_anchor_token(')');
1987 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1988 typeof_type->typeoft.expression = expression;
1989 typeof_type->typeoft.typeof_type = type;
1997 SPECIFIER_SIGNED = 1 << 0,
1998 SPECIFIER_UNSIGNED = 1 << 1,
1999 SPECIFIER_LONG = 1 << 2,
2000 SPECIFIER_INT = 1 << 3,
2001 SPECIFIER_DOUBLE = 1 << 4,
2002 SPECIFIER_CHAR = 1 << 5,
2003 SPECIFIER_SHORT = 1 << 6,
2004 SPECIFIER_LONG_LONG = 1 << 7,
2005 SPECIFIER_FLOAT = 1 << 8,
2006 SPECIFIER_BOOL = 1 << 9,
2007 SPECIFIER_VOID = 1 << 10,
2008 SPECIFIER_INT8 = 1 << 11,
2009 SPECIFIER_INT16 = 1 << 12,
2010 SPECIFIER_INT32 = 1 << 13,
2011 SPECIFIER_INT64 = 1 << 14,
2012 SPECIFIER_INT128 = 1 << 15,
2013 #ifdef PROVIDE_COMPLEX
2014 SPECIFIER_COMPLEX = 1 << 16,
2015 SPECIFIER_IMAGINARY = 1 << 17,
2019 static type_t *create_builtin_type(symbol_t *const symbol,
2020 type_t *const real_type)
2022 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
2023 type->builtin.symbol = symbol;
2024 type->builtin.real_type = real_type;
2026 type_t *result = typehash_insert(type);
2027 if (type != result) {
2034 static type_t *get_typedef_type(symbol_t *symbol)
2036 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2037 if(declaration == NULL
2038 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2041 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
2042 type->typedeft.declaration = declaration;
2048 * check for the allowed MS alignment values.
2050 static bool check_elignment_value(long long intvalue) {
2051 if(intvalue < 1 || intvalue > 8192) {
2052 errorf(HERE, "illegal alignment value");
2055 unsigned v = (unsigned)intvalue;
2056 for(unsigned i = 1; i <= 8192; i += i) {
2060 errorf(HERE, "alignment must be power of two");
2064 #define DET_MOD(name, tag) do { \
2065 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2066 *modifiers |= tag; \
2069 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2071 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2074 if(token.type == T_restrict) {
2076 DET_MOD(restrict, DM_RESTRICT);
2078 } else if(token.type != T_IDENTIFIER)
2080 symbol_t *symbol = token.v.symbol;
2081 if(symbol == sym_align) {
2084 if(token.type != T_INTEGER)
2086 if(check_elignment_value(token.v.intvalue)) {
2087 if(specifiers->alignment != 0)
2088 warningf(HERE, "align used more than once");
2089 specifiers->alignment = (unsigned char)token.v.intvalue;
2093 } else if(symbol == sym_allocate) {
2096 if(token.type != T_IDENTIFIER)
2098 (void)token.v.symbol;
2100 } else if(symbol == sym_dllimport) {
2102 DET_MOD(dllimport, DM_DLLIMPORT);
2103 } else if(symbol == sym_dllexport) {
2105 DET_MOD(dllexport, DM_DLLEXPORT);
2106 } else if(symbol == sym_thread) {
2108 DET_MOD(thread, DM_THREAD);
2109 } else if(symbol == sym_naked) {
2111 DET_MOD(naked, DM_NAKED);
2112 } else if(symbol == sym_noinline) {
2114 DET_MOD(noinline, DM_NOINLINE);
2115 } else if(symbol == sym_noreturn) {
2117 DET_MOD(noreturn, DM_NORETURN);
2118 } else if(symbol == sym_nothrow) {
2120 DET_MOD(nothrow, DM_NOTHROW);
2121 } else if(symbol == sym_novtable) {
2123 DET_MOD(novtable, DM_NOVTABLE);
2124 } else if(symbol == sym_property) {
2128 bool is_get = false;
2129 if(token.type != T_IDENTIFIER)
2131 if(token.v.symbol == sym_get) {
2133 } else if(token.v.symbol == sym_put) {
2135 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2140 if(token.type != T_IDENTIFIER)
2143 if(specifiers->get_property_sym != NULL) {
2144 errorf(HERE, "get property name already specified");
2146 specifiers->get_property_sym = token.v.symbol;
2149 if(specifiers->put_property_sym != NULL) {
2150 errorf(HERE, "put property name already specified");
2152 specifiers->put_property_sym = token.v.symbol;
2156 if(token.type == ',') {
2163 } else if(symbol == sym_selectany) {
2165 DET_MOD(selectany, DM_SELECTANY);
2166 } else if(symbol == sym_uuid) {
2169 if(token.type != T_STRING_LITERAL)
2173 } else if(symbol == sym_deprecated) {
2175 if(specifiers->deprecated != 0)
2176 warningf(HERE, "deprecated used more than once");
2177 specifiers->deprecated = 1;
2178 if(token.type == '(') {
2180 if(token.type == T_STRING_LITERAL) {
2181 specifiers->deprecated_string = token.v.string.begin;
2184 errorf(HERE, "string literal expected");
2188 } else if(symbol == sym_noalias) {
2190 DET_MOD(noalias, DM_NOALIAS);
2192 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2194 if(token.type == '(')
2198 if (token.type == ',')
2205 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2207 type_t *type = NULL;
2208 unsigned type_qualifiers = 0;
2209 unsigned type_specifiers = 0;
2212 specifiers->source_position = token.source_position;
2215 switch(token.type) {
2218 #define MATCH_STORAGE_CLASS(token, class) \
2220 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2221 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2223 specifiers->declared_storage_class = class; \
2227 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2228 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2229 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2230 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2231 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2236 add_anchor_token(')');
2237 parse_microsoft_extended_decl_modifier(specifiers);
2238 rem_anchor_token(')');
2243 switch (specifiers->declared_storage_class) {
2244 case STORAGE_CLASS_NONE:
2245 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2248 case STORAGE_CLASS_EXTERN:
2249 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2252 case STORAGE_CLASS_STATIC:
2253 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2257 errorf(HERE, "multiple storage classes in declaration specifiers");
2263 /* type qualifiers */
2264 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2266 type_qualifiers |= qualifier; \
2270 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2271 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2272 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2273 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2274 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2275 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2276 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2277 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2279 case T___extension__:
2284 /* type specifiers */
2285 #define MATCH_SPECIFIER(token, specifier, name) \
2288 if(type_specifiers & specifier) { \
2289 errorf(HERE, "multiple " name " type specifiers given"); \
2291 type_specifiers |= specifier; \
2295 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2296 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2297 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2298 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2299 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2300 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2301 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2302 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2303 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2304 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
2305 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
2306 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
2307 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
2308 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
2309 #ifdef PROVIDE_COMPLEX
2310 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2311 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2313 case T__forceinline:
2314 /* only in microsoft mode */
2315 specifiers->decl_modifiers |= DM_FORCEINLINE;
2319 specifiers->is_inline = true;
2324 if(type_specifiers & SPECIFIER_LONG_LONG) {
2325 errorf(HERE, "multiple type specifiers given");
2326 } else if(type_specifiers & SPECIFIER_LONG) {
2327 type_specifiers |= SPECIFIER_LONG_LONG;
2329 type_specifiers |= SPECIFIER_LONG;
2334 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2336 type->compound.declaration = parse_compound_type_specifier(true);
2340 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2342 type->compound.declaration = parse_compound_type_specifier(false);
2346 type = parse_enum_specifier();
2349 type = parse_typeof();
2351 case T___builtin_va_list:
2352 type = duplicate_type(type_valist);
2356 case T___attribute__:
2360 case T_IDENTIFIER: {
2361 /* only parse identifier if we haven't found a type yet */
2362 if(type != NULL || type_specifiers != 0)
2363 goto finish_specifiers;
2365 type_t *typedef_type = get_typedef_type(token.v.symbol);
2367 if(typedef_type == NULL)
2368 goto finish_specifiers;
2371 type = typedef_type;
2375 /* function specifier */
2377 goto finish_specifiers;
2384 atomic_type_kind_t atomic_type;
2386 /* match valid basic types */
2387 switch(type_specifiers) {
2388 case SPECIFIER_VOID:
2389 atomic_type = ATOMIC_TYPE_VOID;
2391 case SPECIFIER_CHAR:
2392 atomic_type = ATOMIC_TYPE_CHAR;
2394 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2395 atomic_type = ATOMIC_TYPE_SCHAR;
2397 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2398 atomic_type = ATOMIC_TYPE_UCHAR;
2400 case SPECIFIER_SHORT:
2401 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2402 case SPECIFIER_SHORT | SPECIFIER_INT:
2403 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2404 atomic_type = ATOMIC_TYPE_SHORT;
2406 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2407 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2408 atomic_type = ATOMIC_TYPE_USHORT;
2411 case SPECIFIER_SIGNED:
2412 case SPECIFIER_SIGNED | SPECIFIER_INT:
2413 atomic_type = ATOMIC_TYPE_INT;
2415 case SPECIFIER_UNSIGNED:
2416 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2417 atomic_type = ATOMIC_TYPE_UINT;
2419 case SPECIFIER_LONG:
2420 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2421 case SPECIFIER_LONG | SPECIFIER_INT:
2422 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2423 atomic_type = ATOMIC_TYPE_LONG;
2425 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2426 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2427 atomic_type = ATOMIC_TYPE_ULONG;
2429 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2430 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2431 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2432 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2434 atomic_type = ATOMIC_TYPE_LONGLONG;
2436 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2437 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2439 atomic_type = ATOMIC_TYPE_ULONGLONG;
2442 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2443 atomic_type = unsigned_int8_type_kind;
2446 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2447 atomic_type = unsigned_int16_type_kind;
2450 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2451 atomic_type = unsigned_int32_type_kind;
2454 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2455 atomic_type = unsigned_int64_type_kind;
2458 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2459 atomic_type = unsigned_int128_type_kind;
2462 case SPECIFIER_INT8:
2463 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2464 atomic_type = int8_type_kind;
2467 case SPECIFIER_INT16:
2468 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2469 atomic_type = int16_type_kind;
2472 case SPECIFIER_INT32:
2473 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2474 atomic_type = int32_type_kind;
2477 case SPECIFIER_INT64:
2478 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2479 atomic_type = int64_type_kind;
2482 case SPECIFIER_INT128:
2483 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2484 atomic_type = int128_type_kind;
2487 case SPECIFIER_FLOAT:
2488 atomic_type = ATOMIC_TYPE_FLOAT;
2490 case SPECIFIER_DOUBLE:
2491 atomic_type = ATOMIC_TYPE_DOUBLE;
2493 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2494 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2496 case SPECIFIER_BOOL:
2497 atomic_type = ATOMIC_TYPE_BOOL;
2499 #ifdef PROVIDE_COMPLEX
2500 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2501 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2503 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2504 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2506 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2507 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2509 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2510 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2512 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2513 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2515 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2516 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2520 /* invalid specifier combination, give an error message */
2521 if(type_specifiers == 0) {
2522 if (! strict_mode) {
2523 if (warning.implicit_int) {
2524 warningf(HERE, "no type specifiers in declaration, using 'int'");
2526 atomic_type = ATOMIC_TYPE_INT;
2529 errorf(HERE, "no type specifiers given in declaration");
2531 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2532 (type_specifiers & SPECIFIER_UNSIGNED)) {
2533 errorf(HERE, "signed and unsigned specifiers gives");
2534 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2535 errorf(HERE, "only integer types can be signed or unsigned");
2537 errorf(HERE, "multiple datatypes in declaration");
2539 atomic_type = ATOMIC_TYPE_INVALID;
2542 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2543 type->atomic.akind = atomic_type;
2546 if(type_specifiers != 0) {
2547 errorf(HERE, "multiple datatypes in declaration");
2551 type->base.qualifiers = type_qualifiers;
2552 /* FIXME: check type qualifiers here */
2554 type_t *result = typehash_insert(type);
2555 if(newtype && result != type) {
2559 specifiers->type = result;
2564 static type_qualifiers_t parse_type_qualifiers(void)
2566 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2569 switch(token.type) {
2570 /* type qualifiers */
2571 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2572 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2573 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2574 /* microsoft extended type modifiers */
2575 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2576 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2577 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2578 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2579 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2582 return type_qualifiers;
2587 static declaration_t *parse_identifier_list(void)
2589 declaration_t *declarations = NULL;
2590 declaration_t *last_declaration = NULL;
2592 declaration_t *const declaration = allocate_declaration_zero();
2593 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2594 declaration->source_position = token.source_position;
2595 declaration->symbol = token.v.symbol;
2598 if(last_declaration != NULL) {
2599 last_declaration->next = declaration;
2601 declarations = declaration;
2603 last_declaration = declaration;
2605 if(token.type != ',')
2608 } while(token.type == T_IDENTIFIER);
2610 return declarations;
2613 static void semantic_parameter(declaration_t *declaration)
2615 /* TODO: improve error messages */
2617 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2618 errorf(HERE, "typedef not allowed in parameter list");
2619 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2620 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2621 errorf(HERE, "parameter may only have none or register storage class");
2624 type_t *const orig_type = declaration->type;
2625 type_t * type = skip_typeref(orig_type);
2627 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2628 * into a pointer. § 6.7.5.3 (7) */
2629 if (is_type_array(type)) {
2630 type_t *const element_type = type->array.element_type;
2632 type = make_pointer_type(element_type, type->base.qualifiers);
2634 declaration->type = type;
2637 if(is_type_incomplete(type)) {
2638 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2639 orig_type, declaration->symbol);
2643 static declaration_t *parse_parameter(void)
2645 declaration_specifiers_t specifiers;
2646 memset(&specifiers, 0, sizeof(specifiers));
2648 parse_declaration_specifiers(&specifiers);
2650 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2652 semantic_parameter(declaration);
2657 static declaration_t *parse_parameters(function_type_t *type)
2659 if(token.type == T_IDENTIFIER) {
2660 symbol_t *symbol = token.v.symbol;
2661 if(!is_typedef_symbol(symbol)) {
2662 type->kr_style_parameters = true;
2663 return parse_identifier_list();
2667 if(token.type == ')') {
2668 type->unspecified_parameters = 1;
2671 if(token.type == T_void && look_ahead(1)->type == ')') {
2676 declaration_t *declarations = NULL;
2677 declaration_t *declaration;
2678 declaration_t *last_declaration = NULL;
2679 function_parameter_t *parameter;
2680 function_parameter_t *last_parameter = NULL;
2683 switch(token.type) {
2687 return declarations;
2690 case T___extension__:
2692 declaration = parse_parameter();
2694 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2695 memset(parameter, 0, sizeof(parameter[0]));
2696 parameter->type = declaration->type;
2698 if(last_parameter != NULL) {
2699 last_declaration->next = declaration;
2700 last_parameter->next = parameter;
2702 type->parameters = parameter;
2703 declarations = declaration;
2705 last_parameter = parameter;
2706 last_declaration = declaration;
2710 return declarations;
2712 if(token.type != ',')
2713 return declarations;
2723 } construct_type_kind_t;
2725 typedef struct construct_type_t construct_type_t;
2726 struct construct_type_t {
2727 construct_type_kind_t kind;
2728 construct_type_t *next;
2731 typedef struct parsed_pointer_t parsed_pointer_t;
2732 struct parsed_pointer_t {
2733 construct_type_t construct_type;
2734 type_qualifiers_t type_qualifiers;
2737 typedef struct construct_function_type_t construct_function_type_t;
2738 struct construct_function_type_t {
2739 construct_type_t construct_type;
2740 type_t *function_type;
2743 typedef struct parsed_array_t parsed_array_t;
2744 struct parsed_array_t {
2745 construct_type_t construct_type;
2746 type_qualifiers_t type_qualifiers;
2752 typedef struct construct_base_type_t construct_base_type_t;
2753 struct construct_base_type_t {
2754 construct_type_t construct_type;
2758 static construct_type_t *parse_pointer_declarator(void)
2762 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2763 memset(pointer, 0, sizeof(pointer[0]));
2764 pointer->construct_type.kind = CONSTRUCT_POINTER;
2765 pointer->type_qualifiers = parse_type_qualifiers();
2767 return (construct_type_t*) pointer;
2770 static construct_type_t *parse_array_declarator(void)
2773 add_anchor_token(']');
2775 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2776 memset(array, 0, sizeof(array[0]));
2777 array->construct_type.kind = CONSTRUCT_ARRAY;
2779 if(token.type == T_static) {
2780 array->is_static = true;
2784 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2785 if(type_qualifiers != 0) {
2786 if(token.type == T_static) {
2787 array->is_static = true;
2791 array->type_qualifiers = type_qualifiers;
2793 if(token.type == '*' && look_ahead(1)->type == ']') {
2794 array->is_variable = true;
2796 } else if(token.type != ']') {
2797 array->size = parse_assignment_expression();
2800 rem_anchor_token(']');
2803 return (construct_type_t*) array;
2808 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2811 add_anchor_token(')');
2814 if(declaration != NULL) {
2815 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2817 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2820 declaration_t *parameters = parse_parameters(&type->function);
2821 if(declaration != NULL) {
2822 declaration->scope.declarations = parameters;
2825 construct_function_type_t *construct_function_type =
2826 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2827 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2828 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2829 construct_function_type->function_type = type;
2831 rem_anchor_token(')');
2835 return (construct_type_t*) construct_function_type;
2838 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2839 bool may_be_abstract)
2841 /* construct a single linked list of construct_type_t's which describe
2842 * how to construct the final declarator type */
2843 construct_type_t *first = NULL;
2844 construct_type_t *last = NULL;
2847 while(token.type == '*') {
2848 construct_type_t *type = parse_pointer_declarator();
2859 /* TODO: find out if this is correct */
2862 construct_type_t *inner_types = NULL;
2864 switch(token.type) {
2866 if(declaration == NULL) {
2867 errorf(HERE, "no identifier expected in typename");
2869 declaration->symbol = token.v.symbol;
2870 declaration->source_position = token.source_position;
2876 add_anchor_token(')');
2877 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2878 rem_anchor_token(')');
2884 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2885 /* avoid a loop in the outermost scope, because eat_statement doesn't
2887 if(token.type == '}' && current_function == NULL) {
2895 construct_type_t *p = last;
2898 construct_type_t *type;
2899 switch(token.type) {
2901 type = parse_function_declarator(declaration);
2904 type = parse_array_declarator();
2907 goto declarator_finished;
2910 /* insert in the middle of the list (behind p) */
2912 type->next = p->next;
2923 declarator_finished:
2926 /* append inner_types at the end of the list, we don't to set last anymore
2927 * as it's not needed anymore */
2929 assert(first == NULL);
2930 first = inner_types;
2932 last->next = inner_types;
2940 static type_t *construct_declarator_type(construct_type_t *construct_list,
2943 construct_type_t *iter = construct_list;
2944 for( ; iter != NULL; iter = iter->next) {
2945 switch(iter->kind) {
2946 case CONSTRUCT_INVALID:
2947 internal_errorf(HERE, "invalid type construction found");
2948 case CONSTRUCT_FUNCTION: {
2949 construct_function_type_t *construct_function_type
2950 = (construct_function_type_t*) iter;
2952 type_t *function_type = construct_function_type->function_type;
2954 function_type->function.return_type = type;
2956 type_t *skipped_return_type = skip_typeref(type);
2957 if (is_type_function(skipped_return_type)) {
2958 errorf(HERE, "function returning function is not allowed");
2959 type = type_error_type;
2960 } else if (is_type_array(skipped_return_type)) {
2961 errorf(HERE, "function returning array is not allowed");
2962 type = type_error_type;
2964 type = function_type;
2969 case CONSTRUCT_POINTER: {
2970 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2971 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2972 pointer_type->pointer.points_to = type;
2973 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2975 type = pointer_type;
2979 case CONSTRUCT_ARRAY: {
2980 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2981 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2983 expression_t *size_expression = parsed_array->size;
2984 if(size_expression != NULL) {
2986 = create_implicit_cast(size_expression, type_size_t);
2989 array_type->base.qualifiers = parsed_array->type_qualifiers;
2990 array_type->array.element_type = type;
2991 array_type->array.is_static = parsed_array->is_static;
2992 array_type->array.is_variable = parsed_array->is_variable;
2993 array_type->array.size_expression = size_expression;
2995 if(size_expression != NULL) {
2996 if(is_constant_expression(size_expression)) {
2997 array_type->array.size_constant = true;
2998 array_type->array.size
2999 = fold_constant(size_expression);
3001 array_type->array.is_vla = true;
3005 type_t *skipped_type = skip_typeref(type);
3006 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3007 errorf(HERE, "array of void is not allowed");
3008 type = type_error_type;
3016 type_t *hashed_type = typehash_insert(type);
3017 if(hashed_type != type) {
3018 /* the function type was constructed earlier freeing it here will
3019 * destroy other types... */
3020 if(iter->kind != CONSTRUCT_FUNCTION) {
3030 static declaration_t *parse_declarator(
3031 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3033 declaration_t *const declaration = allocate_declaration_zero();
3034 declaration->declared_storage_class = specifiers->declared_storage_class;
3035 declaration->modifiers = specifiers->decl_modifiers;
3036 declaration->deprecated = specifiers->deprecated;
3037 declaration->deprecated_string = specifiers->deprecated_string;
3038 declaration->get_property_sym = specifiers->get_property_sym;
3039 declaration->put_property_sym = specifiers->put_property_sym;
3040 declaration->is_inline = specifiers->is_inline;
3042 declaration->storage_class = specifiers->declared_storage_class;
3043 if(declaration->storage_class == STORAGE_CLASS_NONE
3044 && scope != global_scope) {
3045 declaration->storage_class = STORAGE_CLASS_AUTO;
3048 if(specifiers->alignment != 0) {
3049 /* TODO: add checks here */
3050 declaration->alignment = specifiers->alignment;
3053 construct_type_t *construct_type
3054 = parse_inner_declarator(declaration, may_be_abstract);
3055 type_t *const type = specifiers->type;
3056 declaration->type = construct_declarator_type(construct_type, type);
3058 if(construct_type != NULL) {
3059 obstack_free(&temp_obst, construct_type);
3065 static type_t *parse_abstract_declarator(type_t *base_type)
3067 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3069 type_t *result = construct_declarator_type(construct_type, base_type);
3070 if(construct_type != NULL) {
3071 obstack_free(&temp_obst, construct_type);
3077 static declaration_t *append_declaration(declaration_t* const declaration)
3079 if (last_declaration != NULL) {
3080 last_declaration->next = declaration;
3082 scope->declarations = declaration;
3084 last_declaration = declaration;
3089 * Check if the declaration of main is suspicious. main should be a
3090 * function with external linkage, returning int, taking either zero
3091 * arguments, two, or three arguments of appropriate types, ie.
3093 * int main([ int argc, char **argv [, char **env ] ]).
3095 * @param decl the declaration to check
3096 * @param type the function type of the declaration
3098 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3100 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3101 warningf(decl->source_position, "'main' is normally a non-static function");
3103 if (skip_typeref(func_type->return_type) != type_int) {
3104 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
3106 const function_parameter_t *parm = func_type->parameters;
3108 type_t *const first_type = parm->type;
3109 if (!types_compatible(skip_typeref(first_type), type_int)) {
3110 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
3114 type_t *const second_type = parm->type;
3115 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3116 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
3120 type_t *const third_type = parm->type;
3121 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3122 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
3126 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3130 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
3136 * Check if a symbol is the equal to "main".
3138 static bool is_sym_main(const symbol_t *const sym)
3140 return strcmp(sym->string, "main") == 0;
3143 static declaration_t *internal_record_declaration(
3144 declaration_t *const declaration,
3145 const bool is_function_definition)
3147 const symbol_t *const symbol = declaration->symbol;
3148 const namespace_t namespc = (namespace_t)declaration->namespc;
3150 type_t *const orig_type = declaration->type;
3151 type_t *const type = skip_typeref(orig_type);
3152 if (is_type_function(type) &&
3153 type->function.unspecified_parameters &&
3154 warning.strict_prototypes) {
3155 warningf(declaration->source_position,
3156 "function declaration '%#T' is not a prototype",
3157 orig_type, declaration->symbol);
3160 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3161 check_type_of_main(declaration, &type->function);
3164 assert(declaration->symbol != NULL);
3165 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3167 assert(declaration != previous_declaration);
3168 if (previous_declaration != NULL) {
3169 if (previous_declaration->parent_scope == scope) {
3170 /* can happen for K&R style declarations */
3171 if(previous_declaration->type == NULL) {
3172 previous_declaration->type = declaration->type;
3175 const type_t *prev_type = skip_typeref(previous_declaration->type);
3176 if (!types_compatible(type, prev_type)) {
3177 errorf(declaration->source_position,
3178 "declaration '%#T' is incompatible with "
3179 "previous declaration '%#T'",
3180 orig_type, symbol, previous_declaration->type, symbol);
3181 errorf(previous_declaration->source_position,
3182 "previous declaration of '%Y' was here", symbol);
3184 unsigned old_storage_class = previous_declaration->storage_class;
3185 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3186 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3187 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3188 return previous_declaration;
3191 unsigned new_storage_class = declaration->storage_class;
3193 if(is_type_incomplete(prev_type)) {
3194 previous_declaration->type = type;
3198 /* pretend no storage class means extern for function
3199 * declarations (except if the previous declaration is neither
3200 * none nor extern) */
3201 if (is_type_function(type)) {
3202 switch (old_storage_class) {
3203 case STORAGE_CLASS_NONE:
3204 old_storage_class = STORAGE_CLASS_EXTERN;
3206 case STORAGE_CLASS_EXTERN:
3207 if (is_function_definition) {
3208 if (warning.missing_prototypes &&
3209 prev_type->function.unspecified_parameters &&
3210 !is_sym_main(symbol)) {
3211 warningf(declaration->source_position,
3212 "no previous prototype for '%#T'",
3215 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3216 new_storage_class = STORAGE_CLASS_EXTERN;
3224 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3225 new_storage_class == STORAGE_CLASS_EXTERN) {
3226 warn_redundant_declaration:
3227 if (warning.redundant_decls) {
3228 warningf(declaration->source_position,
3229 "redundant declaration for '%Y'", symbol);
3230 warningf(previous_declaration->source_position,
3231 "previous declaration of '%Y' was here",
3234 } else if (current_function == NULL) {
3235 if (old_storage_class != STORAGE_CLASS_STATIC &&
3236 new_storage_class == STORAGE_CLASS_STATIC) {
3237 errorf(declaration->source_position,
3238 "static declaration of '%Y' follows non-static declaration",
3240 errorf(previous_declaration->source_position,
3241 "previous declaration of '%Y' was here", symbol);
3243 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3244 goto warn_redundant_declaration;
3246 if (new_storage_class == STORAGE_CLASS_NONE) {
3247 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3248 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3252 if (old_storage_class == new_storage_class) {
3253 errorf(declaration->source_position,
3254 "redeclaration of '%Y'", symbol);
3256 errorf(declaration->source_position,
3257 "redeclaration of '%Y' with different linkage",
3260 errorf(previous_declaration->source_position,
3261 "previous declaration of '%Y' was here", symbol);
3264 return previous_declaration;
3266 } else if (is_function_definition) {
3267 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3268 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3269 warningf(declaration->source_position,
3270 "no previous prototype for '%#T'", orig_type, symbol);
3271 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3272 warningf(declaration->source_position,
3273 "no previous declaration for '%#T'", orig_type,
3277 } else if (warning.missing_declarations &&
3278 scope == global_scope &&
3279 !is_type_function(type) && (
3280 declaration->storage_class == STORAGE_CLASS_NONE ||
3281 declaration->storage_class == STORAGE_CLASS_THREAD
3283 warningf(declaration->source_position,
3284 "no previous declaration for '%#T'", orig_type, symbol);
3287 assert(declaration->parent_scope == NULL);
3288 assert(scope != NULL);
3290 declaration->parent_scope = scope;
3292 environment_push(declaration);
3293 return append_declaration(declaration);
3296 static declaration_t *record_declaration(declaration_t *declaration)
3298 return internal_record_declaration(declaration, false);
3301 static declaration_t *record_function_definition(declaration_t *declaration)
3303 return internal_record_declaration(declaration, true);
3306 static void parser_error_multiple_definition(declaration_t *declaration,
3307 const source_position_t source_position)
3309 errorf(source_position, "multiple definition of symbol '%Y'",
3310 declaration->symbol);
3311 errorf(declaration->source_position,
3312 "this is the location of the previous definition.");
3315 static bool is_declaration_specifier(const token_t *token,
3316 bool only_type_specifiers)
3318 switch(token->type) {
3322 return is_typedef_symbol(token->v.symbol);
3324 case T___extension__:
3327 return !only_type_specifiers;
3334 static void parse_init_declarator_rest(declaration_t *declaration)
3338 type_t *orig_type = declaration->type;
3339 type_t *type = skip_typeref(orig_type);
3341 if(declaration->init.initializer != NULL) {
3342 parser_error_multiple_definition(declaration, token.source_position);
3345 bool must_be_constant = false;
3346 if(declaration->storage_class == STORAGE_CLASS_STATIC
3347 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3348 || declaration->parent_scope == global_scope) {
3349 must_be_constant = true;
3352 parse_initializer_env_t env;
3353 env.type = orig_type;
3354 env.must_be_constant = must_be_constant;
3355 env.declaration = declaration;
3357 initializer_t *initializer = parse_initializer(&env);
3359 if(env.type != orig_type) {
3360 orig_type = env.type;
3361 type = skip_typeref(orig_type);
3362 declaration->type = env.type;
3365 if(is_type_function(type)) {
3366 errorf(declaration->source_position,
3367 "initializers not allowed for function types at declator '%Y' (type '%T')",
3368 declaration->symbol, orig_type);
3370 declaration->init.initializer = initializer;
3374 /* parse rest of a declaration without any declarator */
3375 static void parse_anonymous_declaration_rest(
3376 const declaration_specifiers_t *specifiers,
3377 parsed_declaration_func finished_declaration)
3381 declaration_t *const declaration = allocate_declaration_zero();
3382 declaration->type = specifiers->type;
3383 declaration->declared_storage_class = specifiers->declared_storage_class;
3384 declaration->source_position = specifiers->source_position;
3385 declaration->modifiers = specifiers->decl_modifiers;
3387 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3388 warningf(declaration->source_position, "useless storage class in empty declaration");
3390 declaration->storage_class = STORAGE_CLASS_NONE;
3392 type_t *type = declaration->type;
3393 switch (type->kind) {
3394 case TYPE_COMPOUND_STRUCT:
3395 case TYPE_COMPOUND_UNION: {
3396 if (type->compound.declaration->symbol == NULL) {
3397 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3406 warningf(declaration->source_position, "empty declaration");
3410 finished_declaration(declaration);
3413 static void parse_declaration_rest(declaration_t *ndeclaration,
3414 const declaration_specifiers_t *specifiers,
3415 parsed_declaration_func finished_declaration)
3417 add_anchor_token(';');
3418 add_anchor_token('=');
3419 add_anchor_token(',');
3421 declaration_t *declaration = finished_declaration(ndeclaration);
3423 type_t *orig_type = declaration->type;
3424 type_t *type = skip_typeref(orig_type);
3426 if (type->kind != TYPE_FUNCTION &&
3427 declaration->is_inline &&
3428 is_type_valid(type)) {
3429 warningf(declaration->source_position,
3430 "variable '%Y' declared 'inline'\n", declaration->symbol);
3433 if(token.type == '=') {
3434 parse_init_declarator_rest(declaration);
3437 if(token.type != ',')
3441 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3446 rem_anchor_token(';');
3447 rem_anchor_token('=');
3448 rem_anchor_token(',');
3451 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3453 symbol_t *symbol = declaration->symbol;
3454 if(symbol == NULL) {
3455 errorf(HERE, "anonymous declaration not valid as function parameter");
3458 namespace_t namespc = (namespace_t) declaration->namespc;
3459 if(namespc != NAMESPACE_NORMAL) {
3460 return record_declaration(declaration);
3463 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3464 if(previous_declaration == NULL ||
3465 previous_declaration->parent_scope != scope) {
3466 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3471 if(previous_declaration->type == NULL) {
3472 previous_declaration->type = declaration->type;
3473 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3474 previous_declaration->storage_class = declaration->storage_class;
3475 previous_declaration->parent_scope = scope;
3476 return previous_declaration;
3478 return record_declaration(declaration);
3482 static void parse_declaration(parsed_declaration_func finished_declaration)
3484 declaration_specifiers_t specifiers;
3485 memset(&specifiers, 0, sizeof(specifiers));
3486 parse_declaration_specifiers(&specifiers);
3488 if(token.type == ';') {
3489 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3491 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3492 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3496 static void parse_kr_declaration_list(declaration_t *declaration)
3498 type_t *type = skip_typeref(declaration->type);
3499 if(!is_type_function(type))
3502 if(!type->function.kr_style_parameters)
3505 /* push function parameters */
3506 int top = environment_top();
3507 scope_t *last_scope = scope;
3508 set_scope(&declaration->scope);
3510 declaration_t *parameter = declaration->scope.declarations;
3511 for( ; parameter != NULL; parameter = parameter->next) {
3512 assert(parameter->parent_scope == NULL);
3513 parameter->parent_scope = scope;
3514 environment_push(parameter);
3517 /* parse declaration list */
3518 while(is_declaration_specifier(&token, false)) {
3519 parse_declaration(finished_kr_declaration);
3522 /* pop function parameters */
3523 assert(scope == &declaration->scope);
3524 set_scope(last_scope);
3525 environment_pop_to(top);
3527 /* update function type */
3528 type_t *new_type = duplicate_type(type);
3529 new_type->function.kr_style_parameters = false;
3531 function_parameter_t *parameters = NULL;
3532 function_parameter_t *last_parameter = NULL;
3534 declaration_t *parameter_declaration = declaration->scope.declarations;
3535 for( ; parameter_declaration != NULL;
3536 parameter_declaration = parameter_declaration->next) {
3537 type_t *parameter_type = parameter_declaration->type;
3538 if(parameter_type == NULL) {
3540 errorf(HERE, "no type specified for function parameter '%Y'",
3541 parameter_declaration->symbol);
3543 if (warning.implicit_int) {
3544 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3545 parameter_declaration->symbol);
3547 parameter_type = type_int;
3548 parameter_declaration->type = parameter_type;
3552 semantic_parameter(parameter_declaration);
3553 parameter_type = parameter_declaration->type;
3555 function_parameter_t *function_parameter
3556 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3557 memset(function_parameter, 0, sizeof(function_parameter[0]));
3559 function_parameter->type = parameter_type;
3560 if(last_parameter != NULL) {
3561 last_parameter->next = function_parameter;
3563 parameters = function_parameter;
3565 last_parameter = function_parameter;
3567 new_type->function.parameters = parameters;
3569 type = typehash_insert(new_type);
3570 if(type != new_type) {
3571 obstack_free(type_obst, new_type);
3574 declaration->type = type;
3577 static bool first_err = true;
3580 * When called with first_err set, prints the name of the current function,
3583 static void print_in_function(void) {
3586 diagnosticf("%s: In function '%Y':\n",
3587 current_function->source_position.input_name,
3588 current_function->symbol);
3593 * Check if all labels are defined in the current function.
3594 * Check if all labels are used in the current function.
3596 static void check_labels(void)
3598 for (const goto_statement_t *goto_statement = goto_first;
3599 goto_statement != NULL;
3600 goto_statement = goto_statement->next) {
3601 declaration_t *label = goto_statement->label;
3604 if (label->source_position.input_name == NULL) {
3605 print_in_function();
3606 errorf(goto_statement->base.source_position,
3607 "label '%Y' used but not defined", label->symbol);
3610 goto_first = goto_last = NULL;
3612 if (warning.unused_label) {
3613 for (const label_statement_t *label_statement = label_first;
3614 label_statement != NULL;
3615 label_statement = label_statement->next) {
3616 const declaration_t *label = label_statement->label;
3618 if (! label->used) {
3619 print_in_function();
3620 warningf(label_statement->base.source_position,
3621 "label '%Y' defined but not used", label->symbol);
3625 label_first = label_last = NULL;
3629 * Check declarations of current_function for unused entities.
3631 static void check_declarations(void)
3633 if (warning.unused_parameter) {
3634 const scope_t *scope = ¤t_function->scope;
3636 const declaration_t *parameter = scope->declarations;
3637 for (; parameter != NULL; parameter = parameter->next) {
3638 if (! parameter->used) {
3639 print_in_function();
3640 warningf(parameter->source_position,
3641 "unused parameter '%Y'", parameter->symbol);
3645 if (warning.unused_variable) {
3649 static void parse_external_declaration(void)
3651 /* function-definitions and declarations both start with declaration
3653 declaration_specifiers_t specifiers;
3654 memset(&specifiers, 0, sizeof(specifiers));
3656 add_anchor_token(';');
3657 parse_declaration_specifiers(&specifiers);
3658 rem_anchor_token(';');
3660 /* must be a declaration */
3661 if(token.type == ';') {
3662 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3666 add_anchor_token(',');
3667 add_anchor_token('=');
3668 rem_anchor_token(';');
3670 /* declarator is common to both function-definitions and declarations */
3671 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3673 rem_anchor_token(',');
3674 rem_anchor_token('=');
3675 rem_anchor_token(';');
3677 /* must be a declaration */
3678 if(token.type == ',' || token.type == '=' || token.type == ';') {
3679 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3683 /* must be a function definition */
3684 parse_kr_declaration_list(ndeclaration);
3686 if(token.type != '{') {
3687 parse_error_expected("while parsing function definition", '{', 0);
3688 eat_until_matching_token(';');
3692 type_t *type = ndeclaration->type;
3694 /* note that we don't skip typerefs: the standard doesn't allow them here
3695 * (so we can't use is_type_function here) */
3696 if(type->kind != TYPE_FUNCTION) {
3697 if (is_type_valid(type)) {
3698 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3699 type, ndeclaration->symbol);
3705 /* § 6.7.5.3 (14) a function definition with () means no
3706 * parameters (and not unspecified parameters) */
3707 if(type->function.unspecified_parameters) {
3708 type_t *duplicate = duplicate_type(type);
3709 duplicate->function.unspecified_parameters = false;
3711 type = typehash_insert(duplicate);
3712 if(type != duplicate) {
3713 obstack_free(type_obst, duplicate);
3715 ndeclaration->type = type;
3718 declaration_t *const declaration = record_function_definition(ndeclaration);
3719 if(ndeclaration != declaration) {
3720 declaration->scope = ndeclaration->scope;
3722 type = skip_typeref(declaration->type);
3724 /* push function parameters and switch scope */
3725 int top = environment_top();
3726 scope_t *last_scope = scope;
3727 set_scope(&declaration->scope);
3729 declaration_t *parameter = declaration->scope.declarations;
3730 for( ; parameter != NULL; parameter = parameter->next) {
3731 if(parameter->parent_scope == &ndeclaration->scope) {
3732 parameter->parent_scope = scope;
3734 assert(parameter->parent_scope == NULL
3735 || parameter->parent_scope == scope);
3736 parameter->parent_scope = scope;
3737 environment_push(parameter);
3740 if(declaration->init.statement != NULL) {
3741 parser_error_multiple_definition(declaration, token.source_position);
3743 goto end_of_parse_external_declaration;
3745 /* parse function body */
3746 int label_stack_top = label_top();
3747 declaration_t *old_current_function = current_function;
3748 current_function = declaration;
3750 declaration->init.statement = parse_compound_statement();
3753 check_declarations();
3755 assert(current_function == declaration);
3756 current_function = old_current_function;
3757 label_pop_to(label_stack_top);
3760 end_of_parse_external_declaration:
3761 assert(scope == &declaration->scope);
3762 set_scope(last_scope);
3763 environment_pop_to(top);
3766 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3767 source_position_t source_position)
3769 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3770 type->bitfield.base = base;
3771 type->bitfield.size = size;
3776 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3779 declaration_t *iter = compound_declaration->scope.declarations;
3780 for( ; iter != NULL; iter = iter->next) {
3781 if(iter->namespc != NAMESPACE_NORMAL)
3784 if(iter->symbol == NULL) {
3785 type_t *type = skip_typeref(iter->type);
3786 if(is_type_compound(type)) {
3787 declaration_t *result
3788 = find_compound_entry(type->compound.declaration, symbol);
3795 if(iter->symbol == symbol) {
3803 static void parse_compound_declarators(declaration_t *struct_declaration,
3804 const declaration_specifiers_t *specifiers)
3806 declaration_t *last_declaration = struct_declaration->scope.declarations;
3807 if(last_declaration != NULL) {
3808 while(last_declaration->next != NULL) {
3809 last_declaration = last_declaration->next;
3814 declaration_t *declaration;
3816 if(token.type == ':') {
3817 source_position_t source_position = HERE;
3820 type_t *base_type = specifiers->type;
3821 expression_t *size = parse_constant_expression();
3823 if(!is_type_integer(skip_typeref(base_type))) {
3824 errorf(HERE, "bitfield base type '%T' is not an integer type",
3828 type_t *type = make_bitfield_type(base_type, size, source_position);
3830 declaration = allocate_declaration_zero();
3831 declaration->namespc = NAMESPACE_NORMAL;
3832 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3833 declaration->storage_class = STORAGE_CLASS_NONE;
3834 declaration->source_position = source_position;
3835 declaration->modifiers = specifiers->decl_modifiers;
3836 declaration->type = type;
3838 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3840 type_t *orig_type = declaration->type;
3841 type_t *type = skip_typeref(orig_type);
3843 if(token.type == ':') {
3844 source_position_t source_position = HERE;
3846 expression_t *size = parse_constant_expression();
3848 if(!is_type_integer(type)) {
3849 errorf(HERE, "bitfield base type '%T' is not an "
3850 "integer type", orig_type);
3853 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3854 declaration->type = bitfield_type;
3856 /* TODO we ignore arrays for now... what is missing is a check
3857 * that they're at the end of the struct */
3858 if(is_type_incomplete(type) && !is_type_array(type)) {
3860 "compound member '%Y' has incomplete type '%T'",
3861 declaration->symbol, orig_type);
3862 } else if(is_type_function(type)) {
3863 errorf(HERE, "compound member '%Y' must not have function "
3864 "type '%T'", declaration->symbol, orig_type);
3869 /* make sure we don't define a symbol multiple times */
3870 symbol_t *symbol = declaration->symbol;
3871 if(symbol != NULL) {
3872 declaration_t *prev_decl
3873 = find_compound_entry(struct_declaration, symbol);
3875 if(prev_decl != NULL) {
3876 assert(prev_decl->symbol == symbol);
3877 errorf(declaration->source_position,
3878 "multiple declarations of symbol '%Y'", symbol);
3879 errorf(prev_decl->source_position,
3880 "previous declaration of '%Y' was here", symbol);
3884 /* append declaration */
3885 if(last_declaration != NULL) {
3886 last_declaration->next = declaration;
3888 struct_declaration->scope.declarations = declaration;
3890 last_declaration = declaration;
3892 if(token.type != ',')
3902 static void parse_compound_type_entries(declaration_t *compound_declaration)
3905 add_anchor_token('}');
3907 while(token.type != '}' && token.type != T_EOF) {
3908 declaration_specifiers_t specifiers;
3909 memset(&specifiers, 0, sizeof(specifiers));
3910 parse_declaration_specifiers(&specifiers);
3912 parse_compound_declarators(compound_declaration, &specifiers);
3914 rem_anchor_token('}');
3916 if(token.type == T_EOF) {
3917 errorf(HERE, "EOF while parsing struct");
3922 static type_t *parse_typename(void)
3924 declaration_specifiers_t specifiers;
3925 memset(&specifiers, 0, sizeof(specifiers));
3926 parse_declaration_specifiers(&specifiers);
3927 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3928 /* TODO: improve error message, user does probably not know what a
3929 * storage class is...
3931 errorf(HERE, "typename may not have a storage class");
3934 type_t *result = parse_abstract_declarator(specifiers.type);
3942 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3943 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3944 expression_t *left);
3946 typedef struct expression_parser_function_t expression_parser_function_t;
3947 struct expression_parser_function_t {
3948 unsigned precedence;
3949 parse_expression_function parser;
3950 unsigned infix_precedence;
3951 parse_expression_infix_function infix_parser;
3954 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3957 * Creates a new invalid expression.
3959 static expression_t *create_invalid_expression(void)
3961 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3962 expression->base.source_position = token.source_position;
3967 * Prints an error message if an expression was expected but not read
3969 static expression_t *expected_expression_error(void)
3971 /* skip the error message if the error token was read */
3972 if (token.type != T_ERROR) {
3973 errorf(HERE, "expected expression, got token '%K'", &token);
3977 return create_invalid_expression();
3981 * Parse a string constant.
3983 static expression_t *parse_string_const(void)
3986 if (token.type == T_STRING_LITERAL) {
3987 string_t res = token.v.string;
3989 while (token.type == T_STRING_LITERAL) {
3990 res = concat_strings(&res, &token.v.string);
3993 if (token.type != T_WIDE_STRING_LITERAL) {
3994 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3995 /* note: that we use type_char_ptr here, which is already the
3996 * automatic converted type. revert_automatic_type_conversion
3997 * will construct the array type */
3998 cnst->base.type = type_char_ptr;
3999 cnst->string.value = res;
4003 wres = concat_string_wide_string(&res, &token.v.wide_string);
4005 wres = token.v.wide_string;
4010 switch (token.type) {
4011 case T_WIDE_STRING_LITERAL:
4012 wres = concat_wide_strings(&wres, &token.v.wide_string);
4015 case T_STRING_LITERAL:
4016 wres = concat_wide_string_string(&wres, &token.v.string);
4020 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4021 cnst->base.type = type_wchar_t_ptr;
4022 cnst->wide_string.value = wres;
4031 * Parse an integer constant.
4033 static expression_t *parse_int_const(void)
4035 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4036 cnst->base.source_position = HERE;
4037 cnst->base.type = token.datatype;
4038 cnst->conste.v.int_value = token.v.intvalue;
4046 * Parse a character constant.
4048 static expression_t *parse_character_constant(void)
4050 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4052 cnst->base.source_position = HERE;
4053 cnst->base.type = token.datatype;
4054 cnst->conste.v.character = token.v.string;
4056 if (cnst->conste.v.character.size != 1) {
4057 if (warning.multichar && (c_mode & _GNUC)) {
4059 warningf(HERE, "multi-character character constant");
4061 errorf(HERE, "more than 1 characters in character constant");
4070 * Parse a wide character constant.
4072 static expression_t *parse_wide_character_constant(void)
4074 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4076 cnst->base.source_position = HERE;
4077 cnst->base.type = token.datatype;
4078 cnst->conste.v.wide_character = token.v.wide_string;
4080 if (cnst->conste.v.wide_character.size != 1) {
4081 if (warning.multichar && (c_mode & _GNUC)) {
4083 warningf(HERE, "multi-character character constant");
4085 errorf(HERE, "more than 1 characters in character constant");
4094 * Parse a float constant.
4096 static expression_t *parse_float_const(void)
4098 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4099 cnst->base.type = token.datatype;
4100 cnst->conste.v.float_value = token.v.floatvalue;
4107 static declaration_t *create_implicit_function(symbol_t *symbol,
4108 const source_position_t source_position)
4110 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4111 ntype->function.return_type = type_int;
4112 ntype->function.unspecified_parameters = true;
4114 type_t *type = typehash_insert(ntype);
4119 declaration_t *const declaration = allocate_declaration_zero();
4120 declaration->storage_class = STORAGE_CLASS_EXTERN;
4121 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4122 declaration->type = type;
4123 declaration->symbol = symbol;
4124 declaration->source_position = source_position;
4125 declaration->parent_scope = global_scope;
4127 scope_t *old_scope = scope;
4128 set_scope(global_scope);
4130 environment_push(declaration);
4131 /* prepends the declaration to the global declarations list */
4132 declaration->next = scope->declarations;
4133 scope->declarations = declaration;
4135 assert(scope == global_scope);
4136 set_scope(old_scope);
4142 * Creates a return_type (func)(argument_type) function type if not
4145 * @param return_type the return type
4146 * @param argument_type the argument type
4148 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
4150 function_parameter_t *parameter
4151 = obstack_alloc(type_obst, sizeof(parameter[0]));
4152 memset(parameter, 0, sizeof(parameter[0]));
4153 parameter->type = argument_type;
4155 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4156 type->function.return_type = return_type;
4157 type->function.parameters = parameter;
4159 type_t *result = typehash_insert(type);
4160 if(result != type) {
4168 * Creates a function type for some function like builtins.
4170 * @param symbol the symbol describing the builtin
4172 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4174 switch(symbol->ID) {
4175 case T___builtin_alloca:
4176 return make_function_1_type(type_void_ptr, type_size_t);
4177 case T___builtin_nan:
4178 return make_function_1_type(type_double, type_char_ptr);
4179 case T___builtin_nanf:
4180 return make_function_1_type(type_float, type_char_ptr);
4181 case T___builtin_nand:
4182 return make_function_1_type(type_long_double, type_char_ptr);
4183 case T___builtin_va_end:
4184 return make_function_1_type(type_void, type_valist);
4186 internal_errorf(HERE, "not implemented builtin symbol found");
4191 * Performs automatic type cast as described in § 6.3.2.1.
4193 * @param orig_type the original type
4195 static type_t *automatic_type_conversion(type_t *orig_type)
4197 type_t *type = skip_typeref(orig_type);
4198 if(is_type_array(type)) {
4199 array_type_t *array_type = &type->array;
4200 type_t *element_type = array_type->element_type;
4201 unsigned qualifiers = array_type->type.qualifiers;
4203 return make_pointer_type(element_type, qualifiers);
4206 if(is_type_function(type)) {
4207 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4214 * reverts the automatic casts of array to pointer types and function
4215 * to function-pointer types as defined § 6.3.2.1
4217 type_t *revert_automatic_type_conversion(const expression_t *expression)
4219 switch (expression->kind) {
4220 case EXPR_REFERENCE: return expression->reference.declaration->type;
4221 case EXPR_SELECT: return expression->select.compound_entry->type;
4223 case EXPR_UNARY_DEREFERENCE: {
4224 const expression_t *const value = expression->unary.value;
4225 type_t *const type = skip_typeref(value->base.type);
4226 assert(is_type_pointer(type));
4227 return type->pointer.points_to;
4230 case EXPR_BUILTIN_SYMBOL:
4231 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4233 case EXPR_ARRAY_ACCESS: {
4234 const expression_t *array_ref = expression->array_access.array_ref;
4235 type_t *type_left = skip_typeref(array_ref->base.type);
4236 if (!is_type_valid(type_left))
4238 assert(is_type_pointer(type_left));
4239 return type_left->pointer.points_to;
4242 case EXPR_STRING_LITERAL: {
4243 size_t size = expression->string.value.size;
4244 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4247 case EXPR_WIDE_STRING_LITERAL: {
4248 size_t size = expression->wide_string.value.size;
4249 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4252 case EXPR_COMPOUND_LITERAL:
4253 return expression->compound_literal.type;
4258 return expression->base.type;
4261 static expression_t *parse_reference(void)
4263 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4265 reference_expression_t *ref = &expression->reference;
4266 ref->symbol = token.v.symbol;
4268 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4270 source_position_t source_position = token.source_position;
4273 if(declaration == NULL) {
4274 if (! strict_mode && token.type == '(') {
4275 /* an implicitly defined function */
4276 if (warning.implicit_function_declaration) {
4277 warningf(HERE, "implicit declaration of function '%Y'",
4281 declaration = create_implicit_function(ref->symbol,
4284 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4285 return create_invalid_expression();
4289 type_t *type = declaration->type;
4291 /* we always do the auto-type conversions; the & and sizeof parser contains
4292 * code to revert this! */
4293 type = automatic_type_conversion(type);
4295 ref->declaration = declaration;
4296 ref->base.type = type;
4298 /* this declaration is used */
4299 declaration->used = true;
4301 /* check for deprecated functions */
4302 if(declaration->deprecated != 0) {
4303 const char *prefix = "";
4304 if (is_type_function(declaration->type))
4305 prefix = "function ";
4307 if (declaration->deprecated_string != NULL) {
4308 warningf(source_position,
4309 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
4310 declaration->deprecated_string);
4312 warningf(source_position,
4313 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
4320 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4324 /* TODO check if explicit cast is allowed and issue warnings/errors */
4327 static expression_t *parse_compound_literal(type_t *type)
4329 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4331 parse_initializer_env_t env;
4333 env.declaration = NULL;
4334 env.must_be_constant = false;
4335 initializer_t *initializer = parse_initializer(&env);
4338 expression->compound_literal.initializer = initializer;
4339 expression->compound_literal.type = type;
4340 expression->base.type = automatic_type_conversion(type);
4346 * Parse a cast expression.
4348 static expression_t *parse_cast(void)
4350 source_position_t source_position = token.source_position;
4352 type_t *type = parse_typename();
4354 /* matching add_anchor_token() is at call site */
4355 rem_anchor_token(')');
4358 if(token.type == '{') {
4359 return parse_compound_literal(type);
4362 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4363 cast->base.source_position = source_position;
4365 expression_t *value = parse_sub_expression(20);
4367 check_cast_allowed(value, type);
4369 cast->base.type = type;
4370 cast->unary.value = value;
4374 return create_invalid_expression();
4378 * Parse a statement expression.
4380 static expression_t *parse_statement_expression(void)
4382 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4384 statement_t *statement = parse_compound_statement();
4385 expression->statement.statement = statement;
4386 expression->base.source_position = statement->base.source_position;
4388 /* find last statement and use its type */
4389 type_t *type = type_void;
4390 const statement_t *stmt = statement->compound.statements;
4392 while (stmt->base.next != NULL)
4393 stmt = stmt->base.next;
4395 if (stmt->kind == STATEMENT_EXPRESSION) {
4396 type = stmt->expression.expression->base.type;
4399 warningf(expression->base.source_position, "empty statement expression ({})");
4401 expression->base.type = type;
4407 return create_invalid_expression();
4411 * Parse a braced expression.
4413 static expression_t *parse_brace_expression(void)
4416 add_anchor_token(')');
4418 switch(token.type) {
4420 /* gcc extension: a statement expression */
4421 return parse_statement_expression();
4425 return parse_cast();
4427 if(is_typedef_symbol(token.v.symbol)) {
4428 return parse_cast();
4432 expression_t *result = parse_expression();
4433 rem_anchor_token(')');
4438 return create_invalid_expression();
4441 static expression_t *parse_function_keyword(void)
4446 if (current_function == NULL) {
4447 errorf(HERE, "'__func__' used outside of a function");
4450 expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4451 expression->base.type = type_char_ptr;
4456 static expression_t *parse_pretty_function_keyword(void)
4458 eat(T___PRETTY_FUNCTION__);
4461 if (current_function == NULL) {
4462 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4465 expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4466 expression->base.type = type_char_ptr;
4471 static designator_t *parse_designator(void)
4473 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4474 result->source_position = HERE;
4476 if(token.type != T_IDENTIFIER) {
4477 parse_error_expected("while parsing member designator",
4481 result->symbol = token.v.symbol;
4484 designator_t *last_designator = result;
4486 if(token.type == '.') {
4488 if(token.type != T_IDENTIFIER) {
4489 parse_error_expected("while parsing member designator",
4493 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4494 designator->source_position = HERE;
4495 designator->symbol = token.v.symbol;
4498 last_designator->next = designator;
4499 last_designator = designator;
4502 if(token.type == '[') {
4504 add_anchor_token(']');
4505 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4506 designator->source_position = HERE;
4507 designator->array_index = parse_expression();
4508 rem_anchor_token(']');
4510 if(designator->array_index == NULL) {
4514 last_designator->next = designator;
4515 last_designator = designator;
4527 * Parse the __builtin_offsetof() expression.
4529 static expression_t *parse_offsetof(void)
4531 eat(T___builtin_offsetof);
4533 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4534 expression->base.type = type_size_t;
4537 add_anchor_token(',');
4538 type_t *type = parse_typename();
4539 rem_anchor_token(',');
4541 add_anchor_token(')');
4542 designator_t *designator = parse_designator();
4543 rem_anchor_token(')');
4546 expression->offsetofe.type = type;
4547 expression->offsetofe.designator = designator;
4550 memset(&path, 0, sizeof(path));
4551 path.top_type = type;
4552 path.path = NEW_ARR_F(type_path_entry_t, 0);
4554 descend_into_subtype(&path);
4556 if(!walk_designator(&path, designator, true)) {
4557 return create_invalid_expression();
4560 DEL_ARR_F(path.path);
4564 return create_invalid_expression();
4568 * Parses a _builtin_va_start() expression.
4570 static expression_t *parse_va_start(void)
4572 eat(T___builtin_va_start);
4574 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4577 add_anchor_token(',');
4578 expression->va_starte.ap = parse_assignment_expression();
4579 rem_anchor_token(',');
4581 expression_t *const expr = parse_assignment_expression();
4582 if (expr->kind == EXPR_REFERENCE) {
4583 declaration_t *const decl = expr->reference.declaration;
4585 return create_invalid_expression();
4586 if (decl->parent_scope == ¤t_function->scope &&
4587 decl->next == NULL) {
4588 expression->va_starte.parameter = decl;
4593 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4595 return create_invalid_expression();
4599 * Parses a _builtin_va_arg() expression.
4601 static expression_t *parse_va_arg(void)
4603 eat(T___builtin_va_arg);
4605 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4608 expression->va_arge.ap = parse_assignment_expression();
4610 expression->base.type = parse_typename();
4615 return create_invalid_expression();
4618 static expression_t *parse_builtin_symbol(void)
4620 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4622 symbol_t *symbol = token.v.symbol;
4624 expression->builtin_symbol.symbol = symbol;
4627 type_t *type = get_builtin_symbol_type(symbol);
4628 type = automatic_type_conversion(type);
4630 expression->base.type = type;
4635 * Parses a __builtin_constant() expression.
4637 static expression_t *parse_builtin_constant(void)
4639 eat(T___builtin_constant_p);
4641 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4644 add_anchor_token(')');
4645 expression->builtin_constant.value = parse_assignment_expression();
4646 rem_anchor_token(')');
4648 expression->base.type = type_int;
4652 return create_invalid_expression();
4656 * Parses a __builtin_prefetch() expression.
4658 static expression_t *parse_builtin_prefetch(void)
4660 eat(T___builtin_prefetch);
4662 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4665 add_anchor_token(')');
4666 expression->builtin_prefetch.adr = parse_assignment_expression();
4667 if (token.type == ',') {
4669 expression->builtin_prefetch.rw = parse_assignment_expression();
4671 if (token.type == ',') {
4673 expression->builtin_prefetch.locality = parse_assignment_expression();
4675 rem_anchor_token(')');
4677 expression->base.type = type_void;
4681 return create_invalid_expression();
4685 * Parses a __builtin_is_*() compare expression.
4687 static expression_t *parse_compare_builtin(void)
4689 expression_t *expression;
4691 switch(token.type) {
4692 case T___builtin_isgreater:
4693 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4695 case T___builtin_isgreaterequal:
4696 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4698 case T___builtin_isless:
4699 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4701 case T___builtin_islessequal:
4702 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4704 case T___builtin_islessgreater:
4705 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4707 case T___builtin_isunordered:
4708 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4711 internal_errorf(HERE, "invalid compare builtin found");
4714 expression->base.source_position = HERE;
4718 expression->binary.left = parse_assignment_expression();
4720 expression->binary.right = parse_assignment_expression();
4723 type_t *const orig_type_left = expression->binary.left->base.type;
4724 type_t *const orig_type_right = expression->binary.right->base.type;
4726 type_t *const type_left = skip_typeref(orig_type_left);
4727 type_t *const type_right = skip_typeref(orig_type_right);
4728 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4729 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4730 type_error_incompatible("invalid operands in comparison",
4731 expression->base.source_position, orig_type_left, orig_type_right);
4734 semantic_comparison(&expression->binary);
4739 return create_invalid_expression();
4743 * Parses a __builtin_expect() expression.
4745 static expression_t *parse_builtin_expect(void)
4747 eat(T___builtin_expect);
4749 expression_t *expression
4750 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4753 expression->binary.left = parse_assignment_expression();
4755 expression->binary.right = parse_constant_expression();
4758 expression->base.type = expression->binary.left->base.type;
4762 return create_invalid_expression();
4766 * Parses a MS assume() expression.
4768 static expression_t *parse_assume(void) {
4771 expression_t *expression
4772 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4775 add_anchor_token(')');
4776 expression->unary.value = parse_assignment_expression();
4777 rem_anchor_token(')');
4780 expression->base.type = type_void;
4783 return create_invalid_expression();
4787 * Parses a primary expression.
4789 static expression_t *parse_primary_expression(void)
4791 switch (token.type) {
4792 case T_INTEGER: return parse_int_const();
4793 case T_CHARACTER_CONSTANT: return parse_character_constant();
4794 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4795 case T_FLOATINGPOINT: return parse_float_const();
4796 case T_STRING_LITERAL:
4797 case T_WIDE_STRING_LITERAL: return parse_string_const();
4798 case T_IDENTIFIER: return parse_reference();
4799 case T___FUNCTION__:
4800 case T___func__: return parse_function_keyword();
4801 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4802 case T___builtin_offsetof: return parse_offsetof();
4803 case T___builtin_va_start: return parse_va_start();
4804 case T___builtin_va_arg: return parse_va_arg();
4805 case T___builtin_expect: return parse_builtin_expect();
4806 case T___builtin_alloca:
4807 case T___builtin_nan:
4808 case T___builtin_nand:
4809 case T___builtin_nanf:
4810 case T___builtin_va_end: return parse_builtin_symbol();
4811 case T___builtin_isgreater:
4812 case T___builtin_isgreaterequal:
4813 case T___builtin_isless:
4814 case T___builtin_islessequal:
4815 case T___builtin_islessgreater:
4816 case T___builtin_isunordered: return parse_compare_builtin();
4817 case T___builtin_constant_p: return parse_builtin_constant();
4818 case T___builtin_prefetch: return parse_builtin_prefetch();
4819 case T__assume: return parse_assume();
4821 case '(': return parse_brace_expression();
4824 errorf(HERE, "unexpected token %K, expected an expression", &token);
4825 return create_invalid_expression();
4829 * Check if the expression has the character type and issue a warning then.
4831 static void check_for_char_index_type(const expression_t *expression) {
4832 type_t *const type = expression->base.type;
4833 const type_t *const base_type = skip_typeref(type);
4835 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4836 warning.char_subscripts) {
4837 warningf(expression->base.source_position,
4838 "array subscript has type '%T'", type);
4842 static expression_t *parse_array_expression(unsigned precedence,
4848 add_anchor_token(']');
4850 expression_t *inside = parse_expression();
4852 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4854 array_access_expression_t *array_access = &expression->array_access;
4856 type_t *const orig_type_left = left->base.type;
4857 type_t *const orig_type_inside = inside->base.type;
4859 type_t *const type_left = skip_typeref(orig_type_left);
4860 type_t *const type_inside = skip_typeref(orig_type_inside);
4862 type_t *return_type;
4863 if (is_type_pointer(type_left)) {
4864 return_type = type_left->pointer.points_to;
4865 array_access->array_ref = left;
4866 array_access->index = inside;
4867 check_for_char_index_type(inside);
4868 } else if (is_type_pointer(type_inside)) {
4869 return_type = type_inside->pointer.points_to;
4870 array_access->array_ref = inside;
4871 array_access->index = left;
4872 array_access->flipped = true;
4873 check_for_char_index_type(left);
4875 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4877 "array access on object with non-pointer types '%T', '%T'",
4878 orig_type_left, orig_type_inside);
4880 return_type = type_error_type;
4881 array_access->array_ref = create_invalid_expression();
4884 rem_anchor_token(']');
4885 if(token.type != ']') {
4886 parse_error_expected("Problem while parsing array access", ']', 0);
4891 return_type = automatic_type_conversion(return_type);
4892 expression->base.type = return_type;
4897 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4899 expression_t *tp_expression = allocate_expression_zero(kind);
4900 tp_expression->base.type = type_size_t;
4902 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4904 add_anchor_token(')');
4905 tp_expression->typeprop.type = parse_typename();
4906 rem_anchor_token(')');
4909 expression_t *expression = parse_sub_expression(precedence);
4910 expression->base.type = revert_automatic_type_conversion(expression);
4912 tp_expression->typeprop.type = expression->base.type;
4913 tp_expression->typeprop.tp_expression = expression;
4916 return tp_expression;
4918 return create_invalid_expression();
4921 static expression_t *parse_sizeof(unsigned precedence)
4924 return parse_typeprop(EXPR_SIZEOF, precedence);
4927 static expression_t *parse_alignof(unsigned precedence)
4930 return parse_typeprop(EXPR_SIZEOF, precedence);
4933 static expression_t *parse_select_expression(unsigned precedence,
4934 expression_t *compound)
4937 assert(token.type == '.' || token.type == T_MINUSGREATER);
4939 bool is_pointer = (token.type == T_MINUSGREATER);
4942 expression_t *select = allocate_expression_zero(EXPR_SELECT);
4943 select->select.compound = compound;
4945 if(token.type != T_IDENTIFIER) {
4946 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4949 symbol_t *symbol = token.v.symbol;
4950 select->select.symbol = symbol;
4953 type_t *const orig_type = compound->base.type;
4954 type_t *const type = skip_typeref(orig_type);
4956 type_t *type_left = type;
4958 if (!is_type_pointer(type)) {
4959 if (is_type_valid(type)) {
4960 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4962 return create_invalid_expression();
4964 type_left = type->pointer.points_to;
4966 type_left = skip_typeref(type_left);
4968 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4969 type_left->kind != TYPE_COMPOUND_UNION) {
4970 if (is_type_valid(type_left)) {
4971 errorf(HERE, "request for member '%Y' in something not a struct or "
4972 "union, but '%T'", symbol, type_left);
4974 return create_invalid_expression();
4977 declaration_t *const declaration = type_left->compound.declaration;
4979 if(!declaration->init.is_defined) {
4980 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4982 return create_invalid_expression();
4985 declaration_t *iter = find_compound_entry(declaration, symbol);
4987 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4988 return create_invalid_expression();
4991 /* we always do the auto-type conversions; the & and sizeof parser contains
4992 * code to revert this! */
4993 type_t *expression_type = automatic_type_conversion(iter->type);
4995 select->select.compound_entry = iter;
4996 select->base.type = expression_type;
4998 if(expression_type->kind == TYPE_BITFIELD) {
4999 expression_t *extract
5000 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
5001 extract->unary.value = select;
5002 extract->base.type = expression_type->bitfield.base;
5011 * Parse a call expression, ie. expression '( ... )'.
5013 * @param expression the function address
5015 static expression_t *parse_call_expression(unsigned precedence,
5016 expression_t *expression)
5019 expression_t *result = allocate_expression_zero(EXPR_CALL);
5020 result->base.source_position = expression->base.source_position;
5022 call_expression_t *call = &result->call;
5023 call->function = expression;
5025 type_t *const orig_type = expression->base.type;
5026 type_t *const type = skip_typeref(orig_type);
5028 function_type_t *function_type = NULL;
5029 if (is_type_pointer(type)) {
5030 type_t *const to_type = skip_typeref(type->pointer.points_to);
5032 if (is_type_function(to_type)) {
5033 function_type = &to_type->function;
5034 call->base.type = function_type->return_type;
5038 if (function_type == NULL && is_type_valid(type)) {
5039 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
5042 /* parse arguments */
5044 add_anchor_token(')');
5045 add_anchor_token(',');
5047 if(token.type != ')') {
5048 call_argument_t *last_argument = NULL;
5051 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
5053 argument->expression = parse_assignment_expression();
5054 if(last_argument == NULL) {
5055 call->arguments = argument;
5057 last_argument->next = argument;
5059 last_argument = argument;
5061 if(token.type != ',')
5066 rem_anchor_token(',');
5067 rem_anchor_token(')');
5070 if(function_type != NULL) {
5071 function_parameter_t *parameter = function_type->parameters;
5072 call_argument_t *argument = call->arguments;
5073 for( ; parameter != NULL && argument != NULL;
5074 parameter = parameter->next, argument = argument->next) {
5075 type_t *expected_type = parameter->type;
5076 /* TODO report scope in error messages */
5077 expression_t *const arg_expr = argument->expression;
5078 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
5079 if (res_type == NULL) {
5080 /* TODO improve error message */
5081 errorf(arg_expr->base.source_position,
5082 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
5083 arg_expr, arg_expr->base.type, expected_type);
5085 argument->expression = create_implicit_cast(argument->expression, expected_type);
5088 /* too few parameters */
5089 if(parameter != NULL) {
5090 errorf(HERE, "too few arguments to function '%E'", expression);
5091 } else if(argument != NULL) {
5092 /* too many parameters */
5093 if(!function_type->variadic
5094 && !function_type->unspecified_parameters) {
5095 errorf(HERE, "too many arguments to function '%E'", expression);
5097 /* do default promotion */
5098 for( ; argument != NULL; argument = argument->next) {
5099 type_t *type = argument->expression->base.type;
5101 type = skip_typeref(type);
5102 if(is_type_integer(type)) {
5103 type = promote_integer(type);
5104 } else if(type == type_float) {
5108 argument->expression
5109 = create_implicit_cast(argument->expression, type);
5112 check_format(&result->call);
5115 check_format(&result->call);
5121 return create_invalid_expression();
5124 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
5126 static bool same_compound_type(const type_t *type1, const type_t *type2)
5129 is_type_compound(type1) &&
5130 type1->kind == type2->kind &&
5131 type1->compound.declaration == type2->compound.declaration;
5135 * Parse a conditional expression, ie. 'expression ? ... : ...'.
5137 * @param expression the conditional expression
5139 static expression_t *parse_conditional_expression(unsigned precedence,
5140 expression_t *expression)
5143 add_anchor_token(':');
5145 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
5147 conditional_expression_t *conditional = &result->conditional;
5148 conditional->condition = expression;
5151 type_t *const condition_type_orig = expression->base.type;
5152 type_t *const condition_type = skip_typeref(condition_type_orig);
5153 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
5154 type_error("expected a scalar type in conditional condition",
5155 expression->base.source_position, condition_type_orig);
5158 expression_t *true_expression = parse_expression();
5159 rem_anchor_token(':');
5161 expression_t *false_expression = parse_sub_expression(precedence);
5163 type_t *const orig_true_type = true_expression->base.type;
5164 type_t *const orig_false_type = false_expression->base.type;
5165 type_t *const true_type = skip_typeref(orig_true_type);
5166 type_t *const false_type = skip_typeref(orig_false_type);
5169 type_t *result_type;
5170 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
5171 result_type = semantic_arithmetic(true_type, false_type);
5173 true_expression = create_implicit_cast(true_expression, result_type);
5174 false_expression = create_implicit_cast(false_expression, result_type);
5176 conditional->true_expression = true_expression;
5177 conditional->false_expression = false_expression;
5178 conditional->base.type = result_type;
5179 } else if (same_compound_type(true_type, false_type) || (
5180 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
5181 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
5183 /* just take 1 of the 2 types */
5184 result_type = true_type;
5185 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
5186 && pointers_compatible(true_type, false_type)) {
5188 result_type = true_type;
5189 } else if (is_type_pointer(true_type)
5190 && is_null_pointer_constant(false_expression)) {
5191 result_type = true_type;
5192 } else if (is_type_pointer(false_type)
5193 && is_null_pointer_constant(true_expression)) {
5194 result_type = false_type;
5196 /* TODO: one pointer to void*, other some pointer */
5198 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5199 type_error_incompatible("while parsing conditional",
5200 expression->base.source_position, true_type,
5203 result_type = type_error_type;
5206 conditional->true_expression
5207 = create_implicit_cast(true_expression, result_type);
5208 conditional->false_expression
5209 = create_implicit_cast(false_expression, result_type);
5210 conditional->base.type = result_type;
5213 return create_invalid_expression();
5217 * Parse an extension expression.
5219 static expression_t *parse_extension(unsigned precedence)
5221 eat(T___extension__);
5223 /* TODO enable extensions */
5224 expression_t *expression = parse_sub_expression(precedence);
5225 /* TODO disable extensions */
5230 * Parse a __builtin_classify_type() expression.
5232 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5234 eat(T___builtin_classify_type);
5236 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5237 result->base.type = type_int;
5240 add_anchor_token(')');
5241 expression_t *expression = parse_sub_expression(precedence);
5242 rem_anchor_token(')');
5244 result->classify_type.type_expression = expression;
5248 return create_invalid_expression();
5251 static void semantic_incdec(unary_expression_t *expression)
5253 type_t *const orig_type = expression->value->base.type;
5254 type_t *const type = skip_typeref(orig_type);
5255 /* TODO !is_type_real && !is_type_pointer */
5256 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5257 if (is_type_valid(type)) {
5258 /* TODO: improve error message */
5259 errorf(HERE, "operation needs an arithmetic or pointer type");
5264 expression->base.type = orig_type;
5267 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5269 type_t *const orig_type = expression->value->base.type;
5270 type_t *const type = skip_typeref(orig_type);
5271 if(!is_type_arithmetic(type)) {
5272 if (is_type_valid(type)) {
5273 /* TODO: improve error message */
5274 errorf(HERE, "operation needs an arithmetic type");
5279 expression->base.type = orig_type;
5282 static void semantic_unexpr_scalar(unary_expression_t *expression)
5284 type_t *const orig_type = expression->value->base.type;
5285 type_t *const type = skip_typeref(orig_type);
5286 if (!is_type_scalar(type)) {
5287 if (is_type_valid(type)) {
5288 errorf(HERE, "operand of ! must be of scalar type");
5293 expression->base.type = orig_type;
5296 static void semantic_unexpr_integer(unary_expression_t *expression)
5298 type_t *const orig_type = expression->value->base.type;
5299 type_t *const type = skip_typeref(orig_type);
5300 if (!is_type_integer(type)) {
5301 if (is_type_valid(type)) {
5302 errorf(HERE, "operand of ~ must be of integer type");
5307 expression->base.type = orig_type;
5310 static void semantic_dereference(unary_expression_t *expression)
5312 type_t *const orig_type = expression->value->base.type;
5313 type_t *const type = skip_typeref(orig_type);
5314 if(!is_type_pointer(type)) {
5315 if (is_type_valid(type)) {
5316 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5321 type_t *result_type = type->pointer.points_to;
5322 result_type = automatic_type_conversion(result_type);
5323 expression->base.type = result_type;
5327 * Check the semantic of the address taken expression.
5329 static void semantic_take_addr(unary_expression_t *expression)
5331 expression_t *value = expression->value;
5332 value->base.type = revert_automatic_type_conversion(value);
5334 type_t *orig_type = value->base.type;
5335 if(!is_type_valid(orig_type))
5338 if(value->kind == EXPR_REFERENCE) {
5339 declaration_t *const declaration = value->reference.declaration;
5340 if(declaration != NULL) {
5341 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5342 errorf(expression->base.source_position,
5343 "address of register variable '%Y' requested",
5344 declaration->symbol);
5346 declaration->address_taken = 1;
5350 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5353 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5354 static expression_t *parse_##unexpression_type(unsigned precedence) \
5358 expression_t *unary_expression \
5359 = allocate_expression_zero(unexpression_type); \
5360 unary_expression->base.source_position = HERE; \
5361 unary_expression->unary.value = parse_sub_expression(precedence); \
5363 sfunc(&unary_expression->unary); \
5365 return unary_expression; \
5368 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5369 semantic_unexpr_arithmetic)
5370 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5371 semantic_unexpr_arithmetic)
5372 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5373 semantic_unexpr_scalar)
5374 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5375 semantic_dereference)
5376 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5378 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5379 semantic_unexpr_integer)
5380 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5382 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5385 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5387 static expression_t *parse_##unexpression_type(unsigned precedence, \
5388 expression_t *left) \
5390 (void) precedence; \
5393 expression_t *unary_expression \
5394 = allocate_expression_zero(unexpression_type); \
5395 unary_expression->unary.value = left; \
5397 sfunc(&unary_expression->unary); \
5399 return unary_expression; \
5402 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5403 EXPR_UNARY_POSTFIX_INCREMENT,
5405 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5406 EXPR_UNARY_POSTFIX_DECREMENT,
5409 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5411 /* TODO: handle complex + imaginary types */
5413 /* § 6.3.1.8 Usual arithmetic conversions */
5414 if(type_left == type_long_double || type_right == type_long_double) {
5415 return type_long_double;
5416 } else if(type_left == type_double || type_right == type_double) {
5418 } else if(type_left == type_float || type_right == type_float) {
5422 type_right = promote_integer(type_right);
5423 type_left = promote_integer(type_left);
5425 if(type_left == type_right)
5428 bool signed_left = is_type_signed(type_left);
5429 bool signed_right = is_type_signed(type_right);
5430 int rank_left = get_rank(type_left);
5431 int rank_right = get_rank(type_right);
5432 if(rank_left < rank_right) {
5433 if(signed_left == signed_right || !signed_right) {
5439 if(signed_left == signed_right || !signed_left) {
5448 * Check the semantic restrictions for a binary expression.
5450 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5452 expression_t *const left = expression->left;
5453 expression_t *const right = expression->right;
5454 type_t *const orig_type_left = left->base.type;
5455 type_t *const orig_type_right = right->base.type;
5456 type_t *const type_left = skip_typeref(orig_type_left);
5457 type_t *const type_right = skip_typeref(orig_type_right);
5459 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5460 /* TODO: improve error message */
5461 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5462 errorf(HERE, "operation needs arithmetic types");
5467 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5468 expression->left = create_implicit_cast(left, arithmetic_type);
5469 expression->right = create_implicit_cast(right, arithmetic_type);
5470 expression->base.type = arithmetic_type;
5473 static void semantic_shift_op(binary_expression_t *expression)
5475 expression_t *const left = expression->left;
5476 expression_t *const right = expression->right;
5477 type_t *const orig_type_left = left->base.type;
5478 type_t *const orig_type_right = right->base.type;
5479 type_t * type_left = skip_typeref(orig_type_left);
5480 type_t * type_right = skip_typeref(orig_type_right);
5482 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5483 /* TODO: improve error message */
5484 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5485 errorf(HERE, "operation needs integer types");
5490 type_left = promote_integer(type_left);
5491 type_right = promote_integer(type_right);
5493 expression->left = create_implicit_cast(left, type_left);
5494 expression->right = create_implicit_cast(right, type_right);
5495 expression->base.type = type_left;
5498 static void semantic_add(binary_expression_t *expression)
5500 expression_t *const left = expression->left;
5501 expression_t *const right = expression->right;
5502 type_t *const orig_type_left = left->base.type;
5503 type_t *const orig_type_right = right->base.type;
5504 type_t *const type_left = skip_typeref(orig_type_left);
5505 type_t *const type_right = skip_typeref(orig_type_right);
5508 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5509 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5510 expression->left = create_implicit_cast(left, arithmetic_type);
5511 expression->right = create_implicit_cast(right, arithmetic_type);
5512 expression->base.type = arithmetic_type;
5514 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5515 expression->base.type = type_left;
5516 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5517 expression->base.type = type_right;
5518 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5519 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5523 static void semantic_sub(binary_expression_t *expression)
5525 expression_t *const left = expression->left;
5526 expression_t *const right = expression->right;
5527 type_t *const orig_type_left = left->base.type;
5528 type_t *const orig_type_right = right->base.type;
5529 type_t *const type_left = skip_typeref(orig_type_left);
5530 type_t *const type_right = skip_typeref(orig_type_right);
5533 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5534 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5535 expression->left = create_implicit_cast(left, arithmetic_type);
5536 expression->right = create_implicit_cast(right, arithmetic_type);
5537 expression->base.type = arithmetic_type;
5539 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5540 expression->base.type = type_left;
5541 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5542 if(!pointers_compatible(type_left, type_right)) {
5544 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5545 orig_type_left, orig_type_right);
5547 expression->base.type = type_ptrdiff_t;
5549 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5550 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5551 orig_type_left, orig_type_right);
5556 * Check the semantics of comparison expressions.
5558 * @param expression The expression to check.
5560 static void semantic_comparison(binary_expression_t *expression)
5562 expression_t *left = expression->left;
5563 expression_t *right = expression->right;
5564 type_t *orig_type_left = left->base.type;
5565 type_t *orig_type_right = right->base.type;
5567 type_t *type_left = skip_typeref(orig_type_left);
5568 type_t *type_right = skip_typeref(orig_type_right);
5570 /* TODO non-arithmetic types */
5571 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5572 if (warning.sign_compare &&
5573 (expression->base.kind != EXPR_BINARY_EQUAL &&
5574 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5575 (is_type_signed(type_left) != is_type_signed(type_right))) {
5576 warningf(expression->base.source_position,
5577 "comparison between signed and unsigned");
5579 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5580 expression->left = create_implicit_cast(left, arithmetic_type);
5581 expression->right = create_implicit_cast(right, arithmetic_type);
5582 expression->base.type = arithmetic_type;
5583 if (warning.float_equal &&
5584 (expression->base.kind == EXPR_BINARY_EQUAL ||
5585 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5586 is_type_float(arithmetic_type)) {
5587 warningf(expression->base.source_position,
5588 "comparing floating point with == or != is unsafe");
5590 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5591 /* TODO check compatibility */
5592 } else if (is_type_pointer(type_left)) {
5593 expression->right = create_implicit_cast(right, type_left);
5594 } else if (is_type_pointer(type_right)) {
5595 expression->left = create_implicit_cast(left, type_right);
5596 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5597 type_error_incompatible("invalid operands in comparison",
5598 expression->base.source_position,
5599 type_left, type_right);
5601 expression->base.type = type_int;
5604 static void semantic_arithmetic_assign(binary_expression_t *expression)
5606 expression_t *left = expression->left;
5607 expression_t *right = expression->right;
5608 type_t *orig_type_left = left->base.type;
5609 type_t *orig_type_right = right->base.type;
5611 type_t *type_left = skip_typeref(orig_type_left);
5612 type_t *type_right = skip_typeref(orig_type_right);
5614 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5615 /* TODO: improve error message */
5616 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5617 errorf(HERE, "operation needs arithmetic types");
5622 /* combined instructions are tricky. We can't create an implicit cast on
5623 * the left side, because we need the uncasted form for the store.
5624 * The ast2firm pass has to know that left_type must be right_type
5625 * for the arithmetic operation and create a cast by itself */
5626 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5627 expression->right = create_implicit_cast(right, arithmetic_type);
5628 expression->base.type = type_left;
5631 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5633 expression_t *const left = expression->left;
5634 expression_t *const right = expression->right;
5635 type_t *const orig_type_left = left->base.type;
5636 type_t *const orig_type_right = right->base.type;
5637 type_t *const type_left = skip_typeref(orig_type_left);
5638 type_t *const type_right = skip_typeref(orig_type_right);
5640 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5641 /* combined instructions are tricky. We can't create an implicit cast on
5642 * the left side, because we need the uncasted form for the store.
5643 * The ast2firm pass has to know that left_type must be right_type
5644 * for the arithmetic operation and create a cast by itself */
5645 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5646 expression->right = create_implicit_cast(right, arithmetic_type);
5647 expression->base.type = type_left;
5648 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5649 expression->base.type = type_left;
5650 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5651 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5656 * Check the semantic restrictions of a logical expression.
5658 static void semantic_logical_op(binary_expression_t *expression)
5660 expression_t *const left = expression->left;
5661 expression_t *const right = expression->right;
5662 type_t *const orig_type_left = left->base.type;
5663 type_t *const orig_type_right = right->base.type;
5664 type_t *const type_left = skip_typeref(orig_type_left);
5665 type_t *const type_right = skip_typeref(orig_type_right);
5667 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5668 /* TODO: improve error message */
5669 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5670 errorf(HERE, "operation needs scalar types");
5675 expression->base.type = type_int;
5679 * Checks if a compound type has constant fields.
5681 static bool has_const_fields(const compound_type_t *type)
5683 const scope_t *scope = &type->declaration->scope;
5684 const declaration_t *declaration = scope->declarations;
5686 for (; declaration != NULL; declaration = declaration->next) {
5687 if (declaration->namespc != NAMESPACE_NORMAL)
5690 const type_t *decl_type = skip_typeref(declaration->type);
5691 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5699 * Check the semantic restrictions of a binary assign expression.
5701 static void semantic_binexpr_assign(binary_expression_t *expression)
5703 expression_t *left = expression->left;
5704 type_t *orig_type_left = left->base.type;
5706 type_t *type_left = revert_automatic_type_conversion(left);
5707 type_left = skip_typeref(orig_type_left);
5709 /* must be a modifiable lvalue */
5710 if (is_type_array(type_left)) {
5711 errorf(HERE, "cannot assign to arrays ('%E')", left);
5714 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5715 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5719 if(is_type_incomplete(type_left)) {
5721 "left-hand side of assignment '%E' has incomplete type '%T'",
5722 left, orig_type_left);
5725 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5726 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5727 left, orig_type_left);
5731 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5733 if (res_type == NULL) {
5734 errorf(expression->base.source_position,
5735 "cannot assign to '%T' from '%T'",
5736 orig_type_left, expression->right->base.type);
5738 expression->right = create_implicit_cast(expression->right, res_type);
5741 expression->base.type = orig_type_left;
5745 * Determine if the outermost operation (or parts thereof) of the given
5746 * expression has no effect in order to generate a warning about this fact.
5747 * Therefore in some cases this only examines some of the operands of the
5748 * expression (see comments in the function and examples below).
5750 * f() + 23; // warning, because + has no effect
5751 * x || f(); // no warning, because x controls execution of f()
5752 * x ? y : f(); // warning, because y has no effect
5753 * (void)x; // no warning to be able to suppress the warning
5754 * This function can NOT be used for an "expression has definitely no effect"-
5756 static bool expression_has_effect(const expression_t *const expr)
5758 switch (expr->kind) {
5759 case EXPR_UNKNOWN: break;
5760 case EXPR_INVALID: return true; /* do NOT warn */
5761 case EXPR_REFERENCE: return false;
5762 case EXPR_CONST: return false;
5763 case EXPR_CHARACTER_CONSTANT: return false;
5764 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5765 case EXPR_STRING_LITERAL: return false;
5766 case EXPR_WIDE_STRING_LITERAL: return false;
5769 const call_expression_t *const call = &expr->call;
5770 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5773 switch (call->function->builtin_symbol.symbol->ID) {
5774 case T___builtin_va_end: return true;
5775 default: return false;
5779 /* Generate the warning if either the left or right hand side of a
5780 * conditional expression has no effect */
5781 case EXPR_CONDITIONAL: {
5782 const conditional_expression_t *const cond = &expr->conditional;
5784 expression_has_effect(cond->true_expression) &&
5785 expression_has_effect(cond->false_expression);
5788 case EXPR_SELECT: return false;
5789 case EXPR_ARRAY_ACCESS: return false;
5790 case EXPR_SIZEOF: return false;
5791 case EXPR_CLASSIFY_TYPE: return false;
5792 case EXPR_ALIGNOF: return false;
5794 case EXPR_FUNCTION: return false;
5795 case EXPR_PRETTY_FUNCTION: return false;
5796 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5797 case EXPR_BUILTIN_CONSTANT_P: return false;
5798 case EXPR_BUILTIN_PREFETCH: return true;
5799 case EXPR_OFFSETOF: return false;
5800 case EXPR_VA_START: return true;
5801 case EXPR_VA_ARG: return true;
5802 case EXPR_STATEMENT: return true; // TODO
5803 case EXPR_COMPOUND_LITERAL: return false;
5805 case EXPR_UNARY_NEGATE: return false;
5806 case EXPR_UNARY_PLUS: return false;
5807 case EXPR_UNARY_BITWISE_NEGATE: return false;
5808 case EXPR_UNARY_NOT: return false;
5809 case EXPR_UNARY_DEREFERENCE: return false;
5810 case EXPR_UNARY_TAKE_ADDRESS: return false;
5811 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5812 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5813 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5814 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5816 /* Treat void casts as if they have an effect in order to being able to
5817 * suppress the warning */
5818 case EXPR_UNARY_CAST: {
5819 type_t *const type = skip_typeref(expr->base.type);
5820 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5823 case EXPR_UNARY_CAST_IMPLICIT: return true;
5824 case EXPR_UNARY_ASSUME: return true;
5825 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5827 case EXPR_BINARY_ADD: return false;
5828 case EXPR_BINARY_SUB: return false;
5829 case EXPR_BINARY_MUL: return false;
5830 case EXPR_BINARY_DIV: return false;
5831 case EXPR_BINARY_MOD: return false;
5832 case EXPR_BINARY_EQUAL: return false;
5833 case EXPR_BINARY_NOTEQUAL: return false;
5834 case EXPR_BINARY_LESS: return false;
5835 case EXPR_BINARY_LESSEQUAL: return false;
5836 case EXPR_BINARY_GREATER: return false;
5837 case EXPR_BINARY_GREATEREQUAL: return false;
5838 case EXPR_BINARY_BITWISE_AND: return false;
5839 case EXPR_BINARY_BITWISE_OR: return false;
5840 case EXPR_BINARY_BITWISE_XOR: return false;
5841 case EXPR_BINARY_SHIFTLEFT: return false;
5842 case EXPR_BINARY_SHIFTRIGHT: return false;
5843 case EXPR_BINARY_ASSIGN: return true;
5844 case EXPR_BINARY_MUL_ASSIGN: return true;
5845 case EXPR_BINARY_DIV_ASSIGN: return true;
5846 case EXPR_BINARY_MOD_ASSIGN: return true;
5847 case EXPR_BINARY_ADD_ASSIGN: return true;
5848 case EXPR_BINARY_SUB_ASSIGN: return true;
5849 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5850 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5851 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5852 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5853 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5855 /* Only examine the right hand side of && and ||, because the left hand
5856 * side already has the effect of controlling the execution of the right
5858 case EXPR_BINARY_LOGICAL_AND:
5859 case EXPR_BINARY_LOGICAL_OR:
5860 /* Only examine the right hand side of a comma expression, because the left
5861 * hand side has a separate warning */
5862 case EXPR_BINARY_COMMA:
5863 return expression_has_effect(expr->binary.right);
5865 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5866 case EXPR_BINARY_ISGREATER: return false;
5867 case EXPR_BINARY_ISGREATEREQUAL: return false;
5868 case EXPR_BINARY_ISLESS: return false;
5869 case EXPR_BINARY_ISLESSEQUAL: return false;
5870 case EXPR_BINARY_ISLESSGREATER: return false;
5871 case EXPR_BINARY_ISUNORDERED: return false;
5874 internal_errorf(HERE, "unexpected expression");
5877 static void semantic_comma(binary_expression_t *expression)
5879 if (warning.unused_value) {
5880 const expression_t *const left = expression->left;
5881 if (!expression_has_effect(left)) {
5882 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5885 expression->base.type = expression->right->base.type;
5888 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5889 static expression_t *parse_##binexpression_type(unsigned precedence, \
5890 expression_t *left) \
5893 source_position_t pos = HERE; \
5895 expression_t *right = parse_sub_expression(precedence + lr); \
5897 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5898 binexpr->base.source_position = pos; \
5899 binexpr->binary.left = left; \
5900 binexpr->binary.right = right; \
5901 sfunc(&binexpr->binary); \
5906 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5907 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5908 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5909 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5910 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5911 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5912 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5913 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5914 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5916 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5917 semantic_comparison, 1)
5918 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5919 semantic_comparison, 1)
5920 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5921 semantic_comparison, 1)
5922 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5923 semantic_comparison, 1)
5925 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5926 semantic_binexpr_arithmetic, 1)
5927 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5928 semantic_binexpr_arithmetic, 1)
5929 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5930 semantic_binexpr_arithmetic, 1)
5931 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5932 semantic_logical_op, 1)
5933 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5934 semantic_logical_op, 1)
5935 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5936 semantic_shift_op, 1)
5937 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5938 semantic_shift_op, 1)
5939 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5940 semantic_arithmetic_addsubb_assign, 0)
5941 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5942 semantic_arithmetic_addsubb_assign, 0)
5943 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5944 semantic_arithmetic_assign, 0)
5945 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5946 semantic_arithmetic_assign, 0)
5947 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5948 semantic_arithmetic_assign, 0)
5949 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5950 semantic_arithmetic_assign, 0)
5951 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5952 semantic_arithmetic_assign, 0)
5953 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5954 semantic_arithmetic_assign, 0)
5955 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5956 semantic_arithmetic_assign, 0)
5957 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5958 semantic_arithmetic_assign, 0)
5960 static expression_t *parse_sub_expression(unsigned precedence)
5962 if(token.type < 0) {
5963 return expected_expression_error();
5966 expression_parser_function_t *parser
5967 = &expression_parsers[token.type];
5968 source_position_t source_position = token.source_position;
5971 if(parser->parser != NULL) {
5972 left = parser->parser(parser->precedence);
5974 left = parse_primary_expression();
5976 assert(left != NULL);
5977 left->base.source_position = source_position;
5980 if(token.type < 0) {
5981 return expected_expression_error();
5984 parser = &expression_parsers[token.type];
5985 if(parser->infix_parser == NULL)
5987 if(parser->infix_precedence < precedence)
5990 left = parser->infix_parser(parser->infix_precedence, left);
5992 assert(left != NULL);
5993 assert(left->kind != EXPR_UNKNOWN);
5994 left->base.source_position = source_position;
6001 * Parse an expression.
6003 static expression_t *parse_expression(void)
6005 return parse_sub_expression(1);
6009 * Register a parser for a prefix-like operator with given precedence.
6011 * @param parser the parser function
6012 * @param token_type the token type of the prefix token
6013 * @param precedence the precedence of the operator
6015 static void register_expression_parser(parse_expression_function parser,
6016 int token_type, unsigned precedence)
6018 expression_parser_function_t *entry = &expression_parsers[token_type];
6020 if(entry->parser != NULL) {
6021 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6022 panic("trying to register multiple expression parsers for a token");
6024 entry->parser = parser;
6025 entry->precedence = precedence;
6029 * Register a parser for an infix operator with given precedence.
6031 * @param parser the parser function
6032 * @param token_type the token type of the infix operator
6033 * @param precedence the precedence of the operator
6035 static void register_infix_parser(parse_expression_infix_function parser,
6036 int token_type, unsigned precedence)
6038 expression_parser_function_t *entry = &expression_parsers[token_type];
6040 if(entry->infix_parser != NULL) {
6041 diagnosticf("for token '%k'\n", (token_type_t)token_type);
6042 panic("trying to register multiple infix expression parsers for a "
6045 entry->infix_parser = parser;
6046 entry->infix_precedence = precedence;
6050 * Initialize the expression parsers.
6052 static void init_expression_parsers(void)
6054 memset(&expression_parsers, 0, sizeof(expression_parsers));
6056 register_infix_parser(parse_array_expression, '[', 30);
6057 register_infix_parser(parse_call_expression, '(', 30);
6058 register_infix_parser(parse_select_expression, '.', 30);
6059 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
6060 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
6062 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
6065 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
6066 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
6067 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
6068 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
6069 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
6070 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
6071 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
6072 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
6073 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
6074 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
6075 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
6076 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
6077 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
6078 T_EXCLAMATIONMARKEQUAL, 13);
6079 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
6080 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
6081 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
6082 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
6083 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
6084 register_infix_parser(parse_conditional_expression, '?', 7);
6085 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
6086 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
6087 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
6088 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
6089 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
6090 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
6091 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
6092 T_LESSLESSEQUAL, 2);
6093 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
6094 T_GREATERGREATEREQUAL, 2);
6095 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
6097 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
6099 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
6102 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
6104 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
6105 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
6106 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
6107 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
6108 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
6109 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
6110 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
6112 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
6114 register_expression_parser(parse_sizeof, T_sizeof, 25);
6115 register_expression_parser(parse_alignof, T___alignof__, 25);
6116 register_expression_parser(parse_extension, T___extension__, 25);
6117 register_expression_parser(parse_builtin_classify_type,
6118 T___builtin_classify_type, 25);
6122 * Parse a asm statement constraints specification.
6124 static asm_constraint_t *parse_asm_constraints(void)
6126 asm_constraint_t *result = NULL;
6127 asm_constraint_t *last = NULL;
6129 while(token.type == T_STRING_LITERAL || token.type == '[') {
6130 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
6131 memset(constraint, 0, sizeof(constraint[0]));
6133 if(token.type == '[') {
6135 if(token.type != T_IDENTIFIER) {
6136 parse_error_expected("while parsing asm constraint",
6140 constraint->symbol = token.v.symbol;
6145 constraint->constraints = parse_string_literals();
6147 constraint->expression = parse_expression();
6151 last->next = constraint;
6153 result = constraint;
6157 if(token.type != ',')
6168 * Parse a asm statement clobber specification.
6170 static asm_clobber_t *parse_asm_clobbers(void)
6172 asm_clobber_t *result = NULL;
6173 asm_clobber_t *last = NULL;
6175 while(token.type == T_STRING_LITERAL) {
6176 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
6177 clobber->clobber = parse_string_literals();
6180 last->next = clobber;
6186 if(token.type != ',')
6195 * Parse an asm statement.
6197 static statement_t *parse_asm_statement(void)
6201 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6202 statement->base.source_position = token.source_position;
6204 asm_statement_t *asm_statement = &statement->asms;
6206 if(token.type == T_volatile) {
6208 asm_statement->is_volatile = true;
6212 add_anchor_token(')');
6213 add_anchor_token(':');
6214 asm_statement->asm_text = parse_string_literals();
6216 if(token.type != ':') {
6217 rem_anchor_token(':');
6222 asm_statement->inputs = parse_asm_constraints();
6223 if(token.type != ':') {
6224 rem_anchor_token(':');
6229 asm_statement->outputs = parse_asm_constraints();
6230 if(token.type != ':') {
6231 rem_anchor_token(':');
6234 rem_anchor_token(':');
6237 asm_statement->clobbers = parse_asm_clobbers();
6240 rem_anchor_token(')');
6245 return create_invalid_statement();
6249 * Parse a case statement.
6251 static statement_t *parse_case_statement(void)
6255 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6257 statement->base.source_position = token.source_position;
6258 statement->case_label.expression = parse_expression();
6260 if (c_mode & _GNUC) {
6261 if (token.type == T_DOTDOTDOT) {
6263 statement->case_label.end_range = parse_expression();
6269 if (! is_constant_expression(statement->case_label.expression)) {
6270 errorf(statement->base.source_position,
6271 "case label does not reduce to an integer constant");
6273 /* TODO: check if the case label is already known */
6274 if (current_switch != NULL) {
6275 /* link all cases into the switch statement */
6276 if (current_switch->last_case == NULL) {
6277 current_switch->first_case =
6278 current_switch->last_case = &statement->case_label;
6280 current_switch->last_case->next = &statement->case_label;
6283 errorf(statement->base.source_position,
6284 "case label not within a switch statement");
6287 statement->case_label.statement = parse_statement();
6291 return create_invalid_statement();
6295 * Finds an existing default label of a switch statement.
6297 static case_label_statement_t *
6298 find_default_label(const switch_statement_t *statement)
6300 case_label_statement_t *label = statement->first_case;
6301 for ( ; label != NULL; label = label->next) {
6302 if (label->expression == NULL)
6309 * Parse a default statement.
6311 static statement_t *parse_default_statement(void)
6315 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6317 statement->base.source_position = token.source_position;
6320 if (current_switch != NULL) {
6321 const case_label_statement_t *def_label = find_default_label(current_switch);
6322 if (def_label != NULL) {
6323 errorf(HERE, "multiple default labels in one switch");
6324 errorf(def_label->base.source_position,
6325 "this is the first default label");
6327 /* link all cases into the switch statement */
6328 if (current_switch->last_case == NULL) {
6329 current_switch->first_case =
6330 current_switch->last_case = &statement->case_label;
6332 current_switch->last_case->next = &statement->case_label;
6336 errorf(statement->base.source_position,
6337 "'default' label not within a switch statement");
6339 statement->case_label.statement = parse_statement();
6343 return create_invalid_statement();
6347 * Return the declaration for a given label symbol or create a new one.
6349 static declaration_t *get_label(symbol_t *symbol)
6351 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6352 assert(current_function != NULL);
6353 /* if we found a label in the same function, then we already created the
6355 if(candidate != NULL
6356 && candidate->parent_scope == ¤t_function->scope) {
6360 /* otherwise we need to create a new one */
6361 declaration_t *const declaration = allocate_declaration_zero();
6362 declaration->namespc = NAMESPACE_LABEL;
6363 declaration->symbol = symbol;
6365 label_push(declaration);
6371 * Parse a label statement.
6373 static statement_t *parse_label_statement(void)
6375 assert(token.type == T_IDENTIFIER);
6376 symbol_t *symbol = token.v.symbol;
6379 declaration_t *label = get_label(symbol);
6381 /* if source position is already set then the label is defined twice,
6382 * otherwise it was just mentioned in a goto so far */
6383 if(label->source_position.input_name != NULL) {
6384 errorf(HERE, "duplicate label '%Y'", symbol);
6385 errorf(label->source_position, "previous definition of '%Y' was here",
6388 label->source_position = token.source_position;
6391 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6393 statement->base.source_position = token.source_position;
6394 statement->label.label = label;
6398 if(token.type == '}') {
6399 /* TODO only warn? */
6401 warningf(HERE, "label at end of compound statement");
6402 statement->label.statement = create_empty_statement();
6404 errorf(HERE, "label at end of compound statement");
6405 statement->label.statement = create_invalid_statement();
6409 if (token.type == ';') {
6410 /* eat an empty statement here, to avoid the warning about an empty
6411 * after a label. label:; is commonly used to have a label before
6413 statement->label.statement = create_empty_statement();
6416 statement->label.statement = parse_statement();
6420 /* remember the labels's in a list for later checking */
6421 if (label_last == NULL) {
6422 label_first = &statement->label;
6424 label_last->next = &statement->label;
6426 label_last = &statement->label;
6432 * Parse an if statement.
6434 static statement_t *parse_if(void)
6438 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6439 statement->base.source_position = token.source_position;
6442 add_anchor_token(')');
6443 statement->ifs.condition = parse_expression();
6444 rem_anchor_token(')');
6447 add_anchor_token(T_else);
6448 statement->ifs.true_statement = parse_statement();
6449 rem_anchor_token(T_else);
6451 if(token.type == T_else) {
6453 statement->ifs.false_statement = parse_statement();
6458 return create_invalid_statement();
6462 * Parse a switch statement.
6464 static statement_t *parse_switch(void)
6468 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6469 statement->base.source_position = token.source_position;
6472 expression_t *const expr = parse_expression();
6473 type_t * type = skip_typeref(expr->base.type);
6474 if (is_type_integer(type)) {
6475 type = promote_integer(type);
6476 } else if (is_type_valid(type)) {
6477 errorf(expr->base.source_position,
6478 "switch quantity is not an integer, but '%T'", type);
6479 type = type_error_type;
6481 statement->switchs.expression = create_implicit_cast(expr, type);
6484 switch_statement_t *rem = current_switch;
6485 current_switch = &statement->switchs;
6486 statement->switchs.body = parse_statement();
6487 current_switch = rem;
6489 if (warning.switch_default
6490 && find_default_label(&statement->switchs) == NULL) {
6491 warningf(statement->base.source_position, "switch has no default case");
6496 return create_invalid_statement();
6499 static statement_t *parse_loop_body(statement_t *const loop)
6501 statement_t *const rem = current_loop;
6502 current_loop = loop;
6504 statement_t *const body = parse_statement();
6511 * Parse a while statement.
6513 static statement_t *parse_while(void)
6517 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6518 statement->base.source_position = token.source_position;
6521 add_anchor_token(')');
6522 statement->whiles.condition = parse_expression();
6523 rem_anchor_token(')');
6526 statement->whiles.body = parse_loop_body(statement);
6530 return create_invalid_statement();
6534 * Parse a do statement.
6536 static statement_t *parse_do(void)
6540 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6542 statement->base.source_position = token.source_position;
6544 add_anchor_token(T_while);
6545 statement->do_while.body = parse_loop_body(statement);
6546 rem_anchor_token(T_while);
6550 add_anchor_token(')');
6551 statement->do_while.condition = parse_expression();
6552 rem_anchor_token(')');
6558 return create_invalid_statement();
6562 * Parse a for statement.
6564 static statement_t *parse_for(void)
6568 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6569 statement->base.source_position = token.source_position;
6571 int top = environment_top();
6572 scope_t *last_scope = scope;
6573 set_scope(&statement->fors.scope);
6576 add_anchor_token(')');
6578 if(token.type != ';') {
6579 if(is_declaration_specifier(&token, false)) {
6580 parse_declaration(record_declaration);
6582 expression_t *const init = parse_expression();
6583 statement->fors.initialisation = init;
6584 if (warning.unused_value && !expression_has_effect(init)) {
6585 warningf(init->base.source_position,
6586 "initialisation of 'for'-statement has no effect");
6594 if(token.type != ';') {
6595 statement->fors.condition = parse_expression();
6598 if(token.type != ')') {
6599 expression_t *const step = parse_expression();
6600 statement->fors.step = step;
6601 if (warning.unused_value && !expression_has_effect(step)) {
6602 warningf(step->base.source_position,
6603 "step of 'for'-statement has no effect");
6606 rem_anchor_token(')');
6608 statement->fors.body = parse_loop_body(statement);
6610 assert(scope == &statement->fors.scope);
6611 set_scope(last_scope);
6612 environment_pop_to(top);
6617 rem_anchor_token(')');
6618 assert(scope == &statement->fors.scope);
6619 set_scope(last_scope);
6620 environment_pop_to(top);
6622 return create_invalid_statement();
6626 * Parse a goto statement.
6628 static statement_t *parse_goto(void)
6632 if(token.type != T_IDENTIFIER) {
6633 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6637 symbol_t *symbol = token.v.symbol;
6640 declaration_t *label = get_label(symbol);
6642 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6643 statement->base.source_position = token.source_position;
6645 statement->gotos.label = label;
6647 /* remember the goto's in a list for later checking */
6648 if (goto_last == NULL) {
6649 goto_first = &statement->gotos;
6651 goto_last->next = &statement->gotos;
6653 goto_last = &statement->gotos;
6659 return create_invalid_statement();
6663 * Parse a continue statement.
6665 static statement_t *parse_continue(void)
6667 statement_t *statement;
6668 if (current_loop == NULL) {
6669 errorf(HERE, "continue statement not within loop");
6672 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6674 statement->base.source_position = token.source_position;
6682 return create_invalid_statement();
6686 * Parse a break statement.
6688 static statement_t *parse_break(void)
6690 statement_t *statement;
6691 if (current_switch == NULL && current_loop == NULL) {
6692 errorf(HERE, "break statement not within loop or switch");
6695 statement = allocate_statement_zero(STATEMENT_BREAK);
6697 statement->base.source_position = token.source_position;
6705 return create_invalid_statement();
6709 * Check if a given declaration represents a local variable.
6711 static bool is_local_var_declaration(const declaration_t *declaration) {
6712 switch ((storage_class_tag_t) declaration->storage_class) {
6713 case STORAGE_CLASS_AUTO:
6714 case STORAGE_CLASS_REGISTER: {
6715 const type_t *type = skip_typeref(declaration->type);
6716 if(is_type_function(type)) {
6728 * Check if a given declaration represents a variable.
6730 static bool is_var_declaration(const declaration_t *declaration) {
6731 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6734 const type_t *type = skip_typeref(declaration->type);
6735 return !is_type_function(type);
6739 * Check if a given expression represents a local variable.
6741 static bool is_local_variable(const expression_t *expression)
6743 if (expression->base.kind != EXPR_REFERENCE) {
6746 const declaration_t *declaration = expression->reference.declaration;
6747 return is_local_var_declaration(declaration);
6751 * Check if a given expression represents a local variable and
6752 * return its declaration then, else return NULL.
6754 declaration_t *expr_is_variable(const expression_t *expression)
6756 if (expression->base.kind != EXPR_REFERENCE) {
6759 declaration_t *declaration = expression->reference.declaration;
6760 if (is_var_declaration(declaration))
6766 * Parse a return statement.
6768 static statement_t *parse_return(void)
6772 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6773 statement->base.source_position = token.source_position;
6775 expression_t *return_value = NULL;
6776 if(token.type != ';') {
6777 return_value = parse_expression();
6781 const type_t *const func_type = current_function->type;
6782 assert(is_type_function(func_type));
6783 type_t *const return_type = skip_typeref(func_type->function.return_type);
6785 if(return_value != NULL) {
6786 type_t *return_value_type = skip_typeref(return_value->base.type);
6788 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6789 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6790 warningf(statement->base.source_position,
6791 "'return' with a value, in function returning void");
6792 return_value = NULL;
6794 type_t *const res_type = semantic_assign(return_type,
6795 return_value, "'return'");
6796 if (res_type == NULL) {
6797 errorf(statement->base.source_position,
6798 "cannot return something of type '%T' in function returning '%T'",
6799 return_value->base.type, return_type);
6801 return_value = create_implicit_cast(return_value, res_type);
6804 /* check for returning address of a local var */
6805 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6806 const expression_t *expression = return_value->unary.value;
6807 if (is_local_variable(expression)) {
6808 warningf(statement->base.source_position,
6809 "function returns address of local variable");
6813 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6814 warningf(statement->base.source_position,
6815 "'return' without value, in function returning non-void");
6818 statement->returns.value = return_value;
6822 return create_invalid_statement();
6826 * Parse a declaration statement.
6828 static statement_t *parse_declaration_statement(void)
6830 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6832 statement->base.source_position = token.source_position;
6834 declaration_t *before = last_declaration;
6835 parse_declaration(record_declaration);
6837 if(before == NULL) {
6838 statement->declaration.declarations_begin = scope->declarations;
6840 statement->declaration.declarations_begin = before->next;
6842 statement->declaration.declarations_end = last_declaration;
6848 * Parse an expression statement, ie. expr ';'.
6850 static statement_t *parse_expression_statement(void)
6852 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6854 statement->base.source_position = token.source_position;
6855 expression_t *const expr = parse_expression();
6856 statement->expression.expression = expr;
6858 if (warning.unused_value && !expression_has_effect(expr)) {
6859 warningf(expr->base.source_position, "statement has no effect");
6866 return create_invalid_statement();
6870 * Parse a statement.
6872 static statement_t *parse_statement(void)
6874 statement_t *statement = NULL;
6876 /* declaration or statement */
6877 add_anchor_token(';');
6878 switch(token.type) {
6880 statement = parse_asm_statement();
6884 statement = parse_case_statement();
6888 statement = parse_default_statement();
6892 statement = parse_compound_statement();
6896 statement = parse_if();
6900 statement = parse_switch();
6904 statement = parse_while();
6908 statement = parse_do();
6912 statement = parse_for();
6916 statement = parse_goto();
6920 statement = parse_continue();
6924 statement = parse_break();
6928 statement = parse_return();
6932 if(warning.empty_statement) {
6933 warningf(HERE, "statement is empty");
6935 statement = create_empty_statement();
6940 if(look_ahead(1)->type == ':') {
6941 statement = parse_label_statement();
6945 if(is_typedef_symbol(token.v.symbol)) {
6946 statement = parse_declaration_statement();
6950 statement = parse_expression_statement();
6953 case T___extension__:
6954 /* this can be a prefix to a declaration or an expression statement */
6955 /* we simply eat it now and parse the rest with tail recursion */
6958 } while(token.type == T___extension__);
6959 statement = parse_statement();
6963 statement = parse_declaration_statement();
6967 statement = parse_expression_statement();
6970 rem_anchor_token(';');
6972 assert(statement != NULL
6973 && statement->base.source_position.input_name != NULL);
6979 * Parse a compound statement.
6981 static statement_t *parse_compound_statement(void)
6983 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6985 statement->base.source_position = token.source_position;
6988 add_anchor_token('}');
6990 int top = environment_top();
6991 scope_t *last_scope = scope;
6992 set_scope(&statement->compound.scope);
6994 statement_t *last_statement = NULL;
6996 while(token.type != '}' && token.type != T_EOF) {
6997 statement_t *sub_statement = parse_statement();
6998 if(is_invalid_statement(sub_statement)) {
6999 /* an error occurred. if we are at an anchor, return */
7005 if(last_statement != NULL) {
7006 last_statement->base.next = sub_statement;
7008 statement->compound.statements = sub_statement;
7011 while(sub_statement->base.next != NULL)
7012 sub_statement = sub_statement->base.next;
7014 last_statement = sub_statement;
7017 if(token.type == '}') {
7020 errorf(statement->base.source_position,
7021 "end of file while looking for closing '}'");
7025 rem_anchor_token('}');
7026 assert(scope == &statement->compound.scope);
7027 set_scope(last_scope);
7028 environment_pop_to(top);
7034 * Initialize builtin types.
7036 static void initialize_builtin_types(void)
7038 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
7039 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
7040 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
7041 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
7042 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
7043 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
7044 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
7045 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
7047 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
7048 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
7049 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
7050 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
7054 * Check for unused global static functions and variables
7056 static void check_unused_globals(void)
7058 if (!warning.unused_function && !warning.unused_variable)
7061 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
7062 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
7065 type_t *const type = decl->type;
7067 if (is_type_function(skip_typeref(type))) {
7068 if (!warning.unused_function || decl->is_inline)
7071 s = (decl->init.statement != NULL ? "defined" : "declared");
7073 if (!warning.unused_variable)
7079 warningf(decl->source_position, "'%#T' %s but not used",
7080 type, decl->symbol, s);
7085 * Parse a translation unit.
7087 static translation_unit_t *parse_translation_unit(void)
7089 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
7091 assert(global_scope == NULL);
7092 global_scope = &unit->scope;
7094 assert(scope == NULL);
7095 set_scope(&unit->scope);
7097 initialize_builtin_types();
7099 while(token.type != T_EOF) {
7100 if (token.type == ';') {
7101 /* TODO error in strict mode */
7102 warningf(HERE, "stray ';' outside of function");
7105 parse_external_declaration();
7109 assert(scope == &unit->scope);
7111 last_declaration = NULL;
7113 assert(global_scope == &unit->scope);
7114 check_unused_globals();
7115 global_scope = NULL;
7123 * @return the translation unit or NULL if errors occurred.
7125 translation_unit_t *parse(void)
7127 environment_stack = NEW_ARR_F(stack_entry_t, 0);
7128 label_stack = NEW_ARR_F(stack_entry_t, 0);
7129 diagnostic_count = 0;
7133 type_set_output(stderr);
7134 ast_set_output(stderr);
7136 lookahead_bufpos = 0;
7137 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
7140 translation_unit_t *unit = parse_translation_unit();
7142 DEL_ARR_F(environment_stack);
7143 DEL_ARR_F(label_stack);
7149 * Initialize the parser.
7151 void init_parser(void)
7154 /* add predefined symbols for extended-decl-modifier */
7155 sym_align = symbol_table_insert("align");
7156 sym_allocate = symbol_table_insert("allocate");
7157 sym_dllimport = symbol_table_insert("dllimport");
7158 sym_dllexport = symbol_table_insert("dllexport");
7159 sym_naked = symbol_table_insert("naked");
7160 sym_noinline = symbol_table_insert("noinline");
7161 sym_noreturn = symbol_table_insert("noreturn");
7162 sym_nothrow = symbol_table_insert("nothrow");
7163 sym_novtable = symbol_table_insert("novtable");
7164 sym_property = symbol_table_insert("property");
7165 sym_get = symbol_table_insert("get");
7166 sym_put = symbol_table_insert("put");
7167 sym_selectany = symbol_table_insert("selectany");
7168 sym_thread = symbol_table_insert("thread");
7169 sym_uuid = symbol_table_insert("uuid");
7170 sym_deprecated = symbol_table_insert("deprecated");
7171 sym_restrict = symbol_table_insert("restrict");
7172 sym_noalias = symbol_table_insert("noalias");
7174 memset(token_anchor_set, 0, sizeof(token_anchor_set));
7176 init_expression_parsers();
7177 obstack_init(&temp_obst);
7179 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
7180 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
7184 * Terminate the parser.
7186 void exit_parser(void)
7188 obstack_free(&temp_obst, NULL);