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"
37 #include "walk_statements.h"
39 #include "adt/bitfiddle.h"
40 #include "adt/error.h"
41 #include "adt/array.h"
43 /** if wchar_t is equal to unsigned short. */
44 bool opt_short_wchar_t =
51 //#define PRINT_TOKENS
52 #define MAX_LOOKAHEAD 2
55 declaration_t *old_declaration;
57 unsigned short namespc;
60 typedef struct argument_list_t argument_list_t;
61 struct argument_list_t {
63 argument_list_t *next;
66 typedef struct gnu_attribute_t gnu_attribute_t;
67 struct gnu_attribute_t {
68 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
69 gnu_attribute_t *next;
70 bool invalid; /**< Set if this attribute had argument errors, */
71 bool have_arguments; /**< True, if this attribute has arguments. */
75 atomic_type_kind_t akind;
76 long argument; /**< Single argument. */
77 argument_list_t *arguments; /**< List of argument expressions. */
81 typedef struct declaration_specifiers_t declaration_specifiers_t;
82 struct declaration_specifiers_t {
83 source_position_t source_position;
84 unsigned char declared_storage_class;
85 unsigned char alignment; /**< Alignment, 0 if not set. */
86 unsigned int is_inline : 1;
87 unsigned int deprecated : 1;
88 decl_modifiers_t modifiers; /**< declaration modifiers */
89 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
90 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
91 symbol_t *get_property_sym; /**< the name of the get property if set. */
92 symbol_t *put_property_sym; /**< the name of the put property if set. */
97 * An environment for parsing initializers (and compound literals).
99 typedef struct parse_initializer_env_t {
100 type_t *type; /**< the type of the initializer. In case of an
101 array type with unspecified size this gets
102 adjusted to the actual size. */
103 declaration_t *declaration; /**< the declaration that is initialized if any */
104 bool must_be_constant;
105 } parse_initializer_env_t;
107 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration, bool is_definition);
109 /** The current token. */
110 static token_t token;
111 /** The lookahead ring-buffer. */
112 static token_t lookahead_buffer[MAX_LOOKAHEAD];
113 /** Position of the next token in the lookahead buffer. */
114 static int lookahead_bufpos;
115 static stack_entry_t *environment_stack = NULL;
116 static stack_entry_t *label_stack = NULL;
117 static stack_entry_t *local_label_stack = NULL;
118 /** The global file scope. */
119 static scope_t *file_scope = NULL;
120 /** The current scope. */
121 static scope_t *scope = NULL;
122 static declaration_t *last_declaration = NULL;
123 /** Point to the current function declaration if inside a function. */
124 static declaration_t *current_function = NULL;
125 static declaration_t *current_init_decl = NULL;
126 static switch_statement_t *current_switch = NULL;
127 static statement_t *current_loop = NULL;
128 static statement_t *current_parent = NULL;
129 static ms_try_statement_t *current_try = NULL;
130 static goto_statement_t *goto_first = NULL;
131 static goto_statement_t *goto_last = NULL;
132 static label_statement_t *label_first = NULL;
133 static label_statement_t *label_last = NULL;
134 /** current translation unit. */
135 static translation_unit_t *unit = NULL;
136 /** true if we are in a type property context (evaluation only for type. */
137 static bool in_type_prop = false;
138 /** true in we are in a __extension__ context. */
139 static bool in_gcc_extension = false;
140 static struct obstack temp_obst;
143 #define PUSH_PARENT(stmt) \
144 statement_t *const prev_parent = current_parent; \
145 ((void)(current_parent = (stmt)))
146 #define POP_PARENT ((void)(current_parent = prev_parent))
148 /** special symbol used for anonymous entities. */
149 static const symbol_t *sym_anonymous = NULL;
151 /* symbols for Microsoft extended-decl-modifier */
152 static const symbol_t *sym_align = NULL;
153 static const symbol_t *sym_allocate = NULL;
154 static const symbol_t *sym_dllimport = NULL;
155 static const symbol_t *sym_dllexport = NULL;
156 static const symbol_t *sym_naked = NULL;
157 static const symbol_t *sym_noinline = NULL;
158 static const symbol_t *sym_noreturn = NULL;
159 static const symbol_t *sym_nothrow = NULL;
160 static const symbol_t *sym_novtable = NULL;
161 static const symbol_t *sym_property = NULL;
162 static const symbol_t *sym_get = NULL;
163 static const symbol_t *sym_put = NULL;
164 static const symbol_t *sym_selectany = NULL;
165 static const symbol_t *sym_thread = NULL;
166 static const symbol_t *sym_uuid = NULL;
167 static const symbol_t *sym_deprecated = NULL;
168 static const symbol_t *sym_restrict = NULL;
169 static const symbol_t *sym_noalias = NULL;
171 /** The token anchor set */
172 static unsigned char token_anchor_set[T_LAST_TOKEN];
174 /** The current source position. */
175 #define HERE (&token.source_position)
177 /** true if we are in GCC mode. */
178 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
180 static type_t *type_valist;
182 static statement_t *parse_compound_statement(bool inside_expression_statement);
183 static statement_t *parse_statement(void);
185 static expression_t *parse_sub_expression(precedence_t);
186 static expression_t *parse_expression(void);
187 static type_t *parse_typename(void);
189 static void parse_compound_type_entries(declaration_t *compound_declaration);
190 static declaration_t *parse_declarator(
191 const declaration_specifiers_t *specifiers, bool may_be_abstract);
192 static declaration_t *record_declaration(declaration_t *declaration, bool is_definition);
194 static void semantic_comparison(binary_expression_t *expression);
196 #define STORAGE_CLASSES \
204 #define TYPE_QUALIFIERS \
209 case T__forceinline: \
210 case T___attribute__:
212 #ifdef PROVIDE_COMPLEX
213 #define COMPLEX_SPECIFIERS \
215 #define IMAGINARY_SPECIFIERS \
218 #define COMPLEX_SPECIFIERS
219 #define IMAGINARY_SPECIFIERS
222 #define TYPE_SPECIFIERS \
237 case T___builtin_va_list: \
242 #define DECLARATION_START \
247 #define TYPENAME_START \
251 #define EXPRESSION_START \
260 case T_CHARACTER_CONSTANT: \
261 case T_FLOATINGPOINT: \
265 case T_STRING_LITERAL: \
266 case T_WIDE_CHARACTER_CONSTANT: \
267 case T_WIDE_STRING_LITERAL: \
268 case T___FUNCDNAME__: \
269 case T___FUNCSIG__: \
270 case T___FUNCTION__: \
271 case T___PRETTY_FUNCTION__: \
272 case T___alignof__: \
273 case T___builtin_alloca: \
274 case T___builtin_classify_type: \
275 case T___builtin_constant_p: \
276 case T___builtin_expect: \
277 case T___builtin_huge_val: \
278 case T___builtin_inf: \
279 case T___builtin_inff: \
280 case T___builtin_infl: \
281 case T___builtin_isgreater: \
282 case T___builtin_isgreaterequal: \
283 case T___builtin_isless: \
284 case T___builtin_islessequal: \
285 case T___builtin_islessgreater: \
286 case T___builtin_isunordered: \
287 case T___builtin_nan: \
288 case T___builtin_nanf: \
289 case T___builtin_nanl: \
290 case T___builtin_offsetof: \
291 case T___builtin_prefetch: \
292 case T___builtin_va_arg: \
293 case T___builtin_va_end: \
294 case T___builtin_va_start: \
302 * Allocate an AST node with given size and
303 * initialize all fields with zero.
305 static void *allocate_ast_zero(size_t size)
307 void *res = allocate_ast(size);
308 memset(res, 0, size);
312 static declaration_t *allocate_declaration_zero(void)
314 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
315 declaration->type = type_error_type;
316 declaration->alignment = 0;
321 * Returns the size of a statement node.
323 * @param kind the statement kind
325 static size_t get_statement_struct_size(statement_kind_t kind)
327 static const size_t sizes[] = {
328 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
329 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
330 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
331 [STATEMENT_RETURN] = sizeof(return_statement_t),
332 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
333 [STATEMENT_IF] = sizeof(if_statement_t),
334 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
335 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
336 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
337 [STATEMENT_BREAK] = sizeof(statement_base_t),
338 [STATEMENT_GOTO] = sizeof(goto_statement_t),
339 [STATEMENT_LABEL] = sizeof(label_statement_t),
340 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
341 [STATEMENT_WHILE] = sizeof(while_statement_t),
342 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
343 [STATEMENT_FOR] = sizeof(for_statement_t),
344 [STATEMENT_ASM] = sizeof(asm_statement_t),
345 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
346 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
348 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
349 assert(sizes[kind] != 0);
354 * Returns the size of an expression node.
356 * @param kind the expression kind
358 static size_t get_expression_struct_size(expression_kind_t kind)
360 static const size_t sizes[] = {
361 [EXPR_INVALID] = sizeof(expression_base_t),
362 [EXPR_REFERENCE] = sizeof(reference_expression_t),
363 [EXPR_CONST] = sizeof(const_expression_t),
364 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
365 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
366 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
367 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
368 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
369 [EXPR_CALL] = sizeof(call_expression_t),
370 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
371 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
372 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
373 [EXPR_SELECT] = sizeof(select_expression_t),
374 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
375 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
376 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
377 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
378 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
379 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
380 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
381 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
382 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
383 [EXPR_VA_START] = sizeof(va_start_expression_t),
384 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
385 [EXPR_STATEMENT] = sizeof(statement_expression_t),
386 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
388 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
389 return sizes[EXPR_UNARY_FIRST];
391 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
392 return sizes[EXPR_BINARY_FIRST];
394 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
395 assert(sizes[kind] != 0);
400 * Allocate a statement node of given kind and initialize all
403 static statement_t *allocate_statement_zero(statement_kind_t kind)
405 size_t size = get_statement_struct_size(kind);
406 statement_t *res = allocate_ast_zero(size);
408 res->base.kind = kind;
409 res->base.parent = current_parent;
410 res->base.source_position = token.source_position;
415 * Allocate an expression node of given kind and initialize all
418 static expression_t *allocate_expression_zero(expression_kind_t kind)
420 size_t size = get_expression_struct_size(kind);
421 expression_t *res = allocate_ast_zero(size);
423 res->base.kind = kind;
424 res->base.type = type_error_type;
429 * Creates a new invalid expression.
431 static expression_t *create_invalid_expression(void)
433 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
434 expression->base.source_position = token.source_position;
439 * Creates a new invalid statement.
441 static statement_t *create_invalid_statement(void)
443 return allocate_statement_zero(STATEMENT_INVALID);
447 * Allocate a new empty statement.
449 static statement_t *create_empty_statement(void)
451 return allocate_statement_zero(STATEMENT_EMPTY);
455 * Returns the size of a type node.
457 * @param kind the type kind
459 static size_t get_type_struct_size(type_kind_t kind)
461 static const size_t sizes[] = {
462 [TYPE_ATOMIC] = sizeof(atomic_type_t),
463 [TYPE_COMPLEX] = sizeof(complex_type_t),
464 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
465 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
466 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
467 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
468 [TYPE_ENUM] = sizeof(enum_type_t),
469 [TYPE_FUNCTION] = sizeof(function_type_t),
470 [TYPE_POINTER] = sizeof(pointer_type_t),
471 [TYPE_ARRAY] = sizeof(array_type_t),
472 [TYPE_BUILTIN] = sizeof(builtin_type_t),
473 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
474 [TYPE_TYPEOF] = sizeof(typeof_type_t),
476 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
477 assert(kind <= TYPE_TYPEOF);
478 assert(sizes[kind] != 0);
483 * Allocate a type node of given kind and initialize all
486 * @param kind type kind to allocate
488 static type_t *allocate_type_zero(type_kind_t kind)
490 size_t size = get_type_struct_size(kind);
491 type_t *res = obstack_alloc(type_obst, size);
492 memset(res, 0, size);
493 res->base.kind = kind;
499 * Returns the size of an initializer node.
501 * @param kind the initializer kind
503 static size_t get_initializer_size(initializer_kind_t kind)
505 static const size_t sizes[] = {
506 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
507 [INITIALIZER_STRING] = sizeof(initializer_string_t),
508 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
509 [INITIALIZER_LIST] = sizeof(initializer_list_t),
510 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
512 assert(kind < sizeof(sizes) / sizeof(*sizes));
513 assert(sizes[kind] != 0);
518 * Allocate an initializer node of given kind and initialize all
521 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
523 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
530 * Free a type from the type obstack.
532 static void free_type(void *type)
534 obstack_free(type_obst, type);
538 * Returns the index of the top element of the environment stack.
540 static size_t environment_top(void)
542 return ARR_LEN(environment_stack);
546 * Returns the index of the top element of the global label stack.
548 static size_t label_top(void)
550 return ARR_LEN(label_stack);
554 * Returns the index of the top element of the local label stack.
556 static size_t local_label_top(void)
558 return ARR_LEN(local_label_stack);
562 * Return the next token.
564 static inline void next_token(void)
566 token = lookahead_buffer[lookahead_bufpos];
567 lookahead_buffer[lookahead_bufpos] = lexer_token;
570 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
573 print_token(stderr, &token);
574 fprintf(stderr, "\n");
579 * Return the next token with a given lookahead.
581 static inline const token_t *look_ahead(int num)
583 assert(num > 0 && num <= MAX_LOOKAHEAD);
584 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
585 return &lookahead_buffer[pos];
589 * Adds a token to the token anchor set (a multi-set).
591 static void add_anchor_token(int token_type)
593 assert(0 <= token_type && token_type < T_LAST_TOKEN);
594 ++token_anchor_set[token_type];
597 static int save_and_reset_anchor_state(int token_type)
599 assert(0 <= token_type && token_type < T_LAST_TOKEN);
600 int count = token_anchor_set[token_type];
601 token_anchor_set[token_type] = 0;
605 static void restore_anchor_state(int token_type, int count)
607 assert(0 <= token_type && token_type < T_LAST_TOKEN);
608 token_anchor_set[token_type] = count;
612 * Remove a token from the token anchor set (a multi-set).
614 static void rem_anchor_token(int token_type)
616 assert(0 <= token_type && token_type < T_LAST_TOKEN);
617 assert(token_anchor_set[token_type] != 0);
618 --token_anchor_set[token_type];
621 static bool at_anchor(void)
625 return token_anchor_set[token.type];
629 * Eat tokens until a matching token is found.
631 static void eat_until_matching_token(int type)
635 case '(': end_token = ')'; break;
636 case '{': end_token = '}'; break;
637 case '[': end_token = ']'; break;
638 default: end_token = type; break;
641 unsigned parenthesis_count = 0;
642 unsigned brace_count = 0;
643 unsigned bracket_count = 0;
644 while (token.type != end_token ||
645 parenthesis_count != 0 ||
647 bracket_count != 0) {
648 switch (token.type) {
650 case '(': ++parenthesis_count; break;
651 case '{': ++brace_count; break;
652 case '[': ++bracket_count; break;
655 if (parenthesis_count > 0)
665 if (bracket_count > 0)
668 if (token.type == end_token &&
669 parenthesis_count == 0 &&
683 * Eat input tokens until an anchor is found.
685 static void eat_until_anchor(void)
687 while (token_anchor_set[token.type] == 0) {
688 if (token.type == '(' || token.type == '{' || token.type == '[')
689 eat_until_matching_token(token.type);
694 static void eat_block(void)
696 eat_until_matching_token('{');
697 if (token.type == '}')
701 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
704 * Report a parse error because an expected token was not found.
707 #if defined __GNUC__ && __GNUC__ >= 4
708 __attribute__((sentinel))
710 void parse_error_expected(const char *message, ...)
712 if (message != NULL) {
713 errorf(HERE, "%s", message);
716 va_start(ap, message);
717 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
722 * Report a type error.
724 static void type_error(const char *msg, const source_position_t *source_position,
727 errorf(source_position, "%s, but found type '%T'", msg, type);
731 * Report an incompatible type.
733 static void type_error_incompatible(const char *msg,
734 const source_position_t *source_position, type_t *type1, type_t *type2)
736 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
741 * Expect the the current token is the expected token.
742 * If not, generate an error, eat the current statement,
743 * and goto the end_error label.
745 #define expect(expected) \
747 if (UNLIKELY(token.type != (expected))) { \
748 parse_error_expected(NULL, (expected), NULL); \
749 add_anchor_token(expected); \
750 eat_until_anchor(); \
751 if (token.type == expected) \
753 rem_anchor_token(expected); \
759 static void scope_push(scope_t *new_scope)
762 scope->last_declaration = last_declaration;
763 new_scope->depth = scope->depth + 1;
765 new_scope->parent = scope;
768 last_declaration = new_scope->last_declaration;
771 static void scope_pop(void)
773 scope->last_declaration = last_declaration;
774 scope = scope->parent;
775 last_declaration = scope->last_declaration;
779 * Search a symbol in a given namespace and returns its declaration or
780 * NULL if this symbol was not found.
782 static declaration_t *get_declaration(const symbol_t *const symbol,
783 const namespace_t namespc)
785 declaration_t *declaration = symbol->declaration;
786 for( ; declaration != NULL; declaration = declaration->symbol_next) {
787 if (declaration->namespc == namespc)
795 * pushs an environment_entry on the environment stack and links the
796 * corresponding symbol to the new entry
798 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
800 symbol_t *symbol = declaration->symbol;
801 namespace_t namespc = (namespace_t) declaration->namespc;
803 /* replace/add declaration into declaration list of the symbol */
804 declaration_t **anchor;
806 for (anchor = &symbol->declaration;; anchor = &iter->symbol_next) {
811 /* replace an entry? */
812 if (iter->namespc == namespc) {
813 declaration->symbol_next = iter->symbol_next;
817 *anchor = declaration;
819 /* remember old declaration */
821 entry.symbol = symbol;
822 entry.old_declaration = iter;
823 entry.namespc = (unsigned short) namespc;
824 ARR_APP1(stack_entry_t, *stack_ptr, entry);
828 * Push a declaration on the environment stack.
830 * @param declaration the declaration
832 static void environment_push(declaration_t *declaration)
834 assert(declaration->source_position.input_name != NULL);
835 assert(declaration->parent_scope != NULL);
836 stack_push(&environment_stack, declaration);
840 * Push a declaration on the global label stack.
842 * @param declaration the declaration
844 static void label_push(declaration_t *declaration)
846 declaration->parent_scope = ¤t_function->scope;
847 stack_push(&label_stack, declaration);
851 * Push a declaration of the local label stack.
853 * @param declaration the declaration
855 static void local_label_push(declaration_t *declaration)
857 assert(declaration->parent_scope != NULL);
858 stack_push(&local_label_stack, declaration);
862 * pops symbols from the environment stack until @p new_top is the top element
864 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
866 stack_entry_t *stack = *stack_ptr;
867 size_t top = ARR_LEN(stack);
870 assert(new_top <= top);
874 for(i = top; i > new_top; --i) {
875 stack_entry_t *entry = &stack[i - 1];
877 declaration_t *old_declaration = entry->old_declaration;
878 symbol_t *symbol = entry->symbol;
879 namespace_t namespc = (namespace_t)entry->namespc;
881 /* replace/remove declaration */
882 declaration_t **anchor;
884 for (anchor = &symbol->declaration;; anchor = &iter->symbol_next) {
886 assert(iter != NULL);
887 /* replace an entry? */
888 if (iter->namespc == namespc)
892 /* Not all declarations adhere scopes (e.g. jump labels), so this
893 * correction is necessary */
894 if (old_declaration != NULL) {
895 old_declaration->symbol_next = iter->symbol_next;
896 *anchor = old_declaration;
898 *anchor = iter->symbol_next;
902 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
906 * Pop all entries from the environment stack until the new_top
909 * @param new_top the new stack top
911 static void environment_pop_to(size_t new_top)
913 stack_pop_to(&environment_stack, new_top);
917 * Pop all entries from the global label stack until the new_top
920 * @param new_top the new stack top
922 static void label_pop_to(size_t new_top)
924 stack_pop_to(&label_stack, new_top);
928 * Pop all entries from the local label stack until the new_top
931 * @param new_top the new stack top
933 static void local_label_pop_to(size_t new_top)
935 stack_pop_to(&local_label_stack, new_top);
939 static int get_akind_rank(atomic_type_kind_t akind)
944 static int get_rank(const type_t *type)
946 assert(!is_typeref(type));
947 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
948 * and esp. footnote 108). However we can't fold constants (yet), so we
949 * can't decide whether unsigned int is possible, while int always works.
950 * (unsigned int would be preferable when possible... for stuff like
951 * struct { enum { ... } bla : 4; } ) */
952 if (type->kind == TYPE_ENUM)
953 return get_akind_rank(ATOMIC_TYPE_INT);
955 assert(type->kind == TYPE_ATOMIC);
956 return get_akind_rank(type->atomic.akind);
959 static type_t *promote_integer(type_t *type)
961 if (type->kind == TYPE_BITFIELD)
962 type = type->bitfield.base_type;
964 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
971 * Create a cast expression.
973 * @param expression the expression to cast
974 * @param dest_type the destination type
976 static expression_t *create_cast_expression(expression_t *expression,
979 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
981 cast->unary.value = expression;
982 cast->base.type = dest_type;
988 * Check if a given expression represents the 0 pointer constant.
990 static bool is_null_pointer_constant(const expression_t *expression)
992 /* skip void* cast */
993 if (expression->kind == EXPR_UNARY_CAST
994 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
995 expression = expression->unary.value;
998 /* TODO: not correct yet, should be any constant integer expression
999 * which evaluates to 0 */
1000 if (expression->kind != EXPR_CONST)
1003 type_t *const type = skip_typeref(expression->base.type);
1004 if (!is_type_integer(type))
1007 return expression->conste.v.int_value == 0;
1011 * Create an implicit cast expression.
1013 * @param expression the expression to cast
1014 * @param dest_type the destination type
1016 static expression_t *create_implicit_cast(expression_t *expression,
1019 type_t *const source_type = expression->base.type;
1021 if (source_type == dest_type)
1024 return create_cast_expression(expression, dest_type);
1027 typedef enum assign_error_t {
1029 ASSIGN_ERROR_INCOMPATIBLE,
1030 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1031 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1032 ASSIGN_WARNING_POINTER_FROM_INT,
1033 ASSIGN_WARNING_INT_FROM_POINTER
1036 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1037 const expression_t *const right,
1038 const char *context,
1039 const source_position_t *source_position)
1041 type_t *const orig_type_right = right->base.type;
1042 type_t *const type_left = skip_typeref(orig_type_left);
1043 type_t *const type_right = skip_typeref(orig_type_right);
1046 case ASSIGN_SUCCESS:
1048 case ASSIGN_ERROR_INCOMPATIBLE:
1049 errorf(source_position,
1050 "destination type '%T' in %s is incompatible with type '%T'",
1051 orig_type_left, context, orig_type_right);
1054 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1055 if (warning.other) {
1056 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1057 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1059 /* the left type has all qualifiers from the right type */
1060 unsigned missing_qualifiers
1061 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1062 warningf(source_position,
1063 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1064 orig_type_left, context, orig_type_right, missing_qualifiers);
1069 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1070 if (warning.other) {
1071 warningf(source_position,
1072 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1073 orig_type_left, context, right, orig_type_right);
1077 case ASSIGN_WARNING_POINTER_FROM_INT:
1078 if (warning.other) {
1079 warningf(source_position,
1080 "%s makes pointer '%T' from integer '%T' without a cast",
1081 context, orig_type_left, orig_type_right);
1085 case ASSIGN_WARNING_INT_FROM_POINTER:
1086 if (warning.other) {
1087 warningf(source_position,
1088 "%s makes integer '%T' from pointer '%T' without a cast",
1089 context, orig_type_left, orig_type_right);
1094 panic("invalid error value");
1098 /** Implements the rules from § 6.5.16.1 */
1099 static assign_error_t semantic_assign(type_t *orig_type_left,
1100 const expression_t *const right)
1102 type_t *const orig_type_right = right->base.type;
1103 type_t *const type_left = skip_typeref(orig_type_left);
1104 type_t *const type_right = skip_typeref(orig_type_right);
1106 if (is_type_pointer(type_left)) {
1107 if (is_null_pointer_constant(right)) {
1108 return ASSIGN_SUCCESS;
1109 } else if (is_type_pointer(type_right)) {
1110 type_t *points_to_left
1111 = skip_typeref(type_left->pointer.points_to);
1112 type_t *points_to_right
1113 = skip_typeref(type_right->pointer.points_to);
1114 assign_error_t res = ASSIGN_SUCCESS;
1116 /* the left type has all qualifiers from the right type */
1117 unsigned missing_qualifiers
1118 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1119 if (missing_qualifiers != 0) {
1120 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1123 points_to_left = get_unqualified_type(points_to_left);
1124 points_to_right = get_unqualified_type(points_to_right);
1126 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1129 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1130 /* ISO/IEC 14882:1998(E) §C.3.5:6 */
1131 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1134 if (!types_compatible(points_to_left, points_to_right)) {
1135 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1139 } else if (is_type_integer(type_right)) {
1140 return ASSIGN_WARNING_POINTER_FROM_INT;
1142 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1143 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1144 && is_type_pointer(type_right))) {
1145 return ASSIGN_SUCCESS;
1146 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1147 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1148 type_t *const unqual_type_left = get_unqualified_type(type_left);
1149 type_t *const unqual_type_right = get_unqualified_type(type_right);
1150 if (types_compatible(unqual_type_left, unqual_type_right)) {
1151 return ASSIGN_SUCCESS;
1153 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1154 return ASSIGN_WARNING_INT_FROM_POINTER;
1157 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1158 return ASSIGN_SUCCESS;
1160 return ASSIGN_ERROR_INCOMPATIBLE;
1163 static expression_t *parse_constant_expression(void)
1165 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1167 if (!is_constant_expression(result)) {
1168 errorf(&result->base.source_position,
1169 "expression '%E' is not constant\n", result);
1175 static expression_t *parse_assignment_expression(void)
1177 return parse_sub_expression(PREC_ASSIGNMENT);
1180 static type_t *make_global_typedef(const char *name, type_t *type)
1182 symbol_t *const symbol = symbol_table_insert(name);
1184 declaration_t *const declaration = allocate_declaration_zero();
1185 declaration->namespc = NAMESPACE_NORMAL;
1186 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1187 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1188 declaration->type = type;
1189 declaration->symbol = symbol;
1190 declaration->source_position = builtin_source_position;
1191 declaration->implicit = true;
1193 record_declaration(declaration, false);
1195 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF);
1196 typedef_type->typedeft.declaration = declaration;
1198 return typedef_type;
1201 static string_t parse_string_literals(void)
1203 assert(token.type == T_STRING_LITERAL);
1204 string_t result = token.v.string;
1208 while (token.type == T_STRING_LITERAL) {
1209 result = concat_strings(&result, &token.v.string);
1216 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1217 [GNU_AK_CONST] = "const",
1218 [GNU_AK_VOLATILE] = "volatile",
1219 [GNU_AK_CDECL] = "cdecl",
1220 [GNU_AK_STDCALL] = "stdcall",
1221 [GNU_AK_FASTCALL] = "fastcall",
1222 [GNU_AK_DEPRECATED] = "deprecated",
1223 [GNU_AK_NOINLINE] = "noinline",
1224 [GNU_AK_NORETURN] = "noreturn",
1225 [GNU_AK_NAKED] = "naked",
1226 [GNU_AK_PURE] = "pure",
1227 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1228 [GNU_AK_MALLOC] = "malloc",
1229 [GNU_AK_WEAK] = "weak",
1230 [GNU_AK_CONSTRUCTOR] = "constructor",
1231 [GNU_AK_DESTRUCTOR] = "destructor",
1232 [GNU_AK_NOTHROW] = "nothrow",
1233 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1234 [GNU_AK_COMMON] = "common",
1235 [GNU_AK_NOCOMMON] = "nocommon",
1236 [GNU_AK_PACKED] = "packed",
1237 [GNU_AK_SHARED] = "shared",
1238 [GNU_AK_NOTSHARED] = "notshared",
1239 [GNU_AK_USED] = "used",
1240 [GNU_AK_UNUSED] = "unused",
1241 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1242 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1243 [GNU_AK_LONGCALL] = "longcall",
1244 [GNU_AK_SHORTCALL] = "shortcall",
1245 [GNU_AK_LONG_CALL] = "long_call",
1246 [GNU_AK_SHORT_CALL] = "short_call",
1247 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1248 [GNU_AK_INTERRUPT] = "interrupt",
1249 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1250 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1251 [GNU_AK_NESTING] = "nesting",
1252 [GNU_AK_NEAR] = "near",
1253 [GNU_AK_FAR] = "far",
1254 [GNU_AK_SIGNAL] = "signal",
1255 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1256 [GNU_AK_TINY_DATA] = "tiny_data",
1257 [GNU_AK_SAVEALL] = "saveall",
1258 [GNU_AK_FLATTEN] = "flatten",
1259 [GNU_AK_SSEREGPARM] = "sseregparm",
1260 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1261 [GNU_AK_RETURN_TWICE] = "return_twice",
1262 [GNU_AK_MAY_ALIAS] = "may_alias",
1263 [GNU_AK_MS_STRUCT] = "ms_struct",
1264 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1265 [GNU_AK_DLLIMPORT] = "dllimport",
1266 [GNU_AK_DLLEXPORT] = "dllexport",
1267 [GNU_AK_ALIGNED] = "aligned",
1268 [GNU_AK_ALIAS] = "alias",
1269 [GNU_AK_SECTION] = "section",
1270 [GNU_AK_FORMAT] = "format",
1271 [GNU_AK_FORMAT_ARG] = "format_arg",
1272 [GNU_AK_WEAKREF] = "weakref",
1273 [GNU_AK_NONNULL] = "nonnull",
1274 [GNU_AK_TLS_MODEL] = "tls_model",
1275 [GNU_AK_VISIBILITY] = "visibility",
1276 [GNU_AK_REGPARM] = "regparm",
1277 [GNU_AK_MODE] = "mode",
1278 [GNU_AK_MODEL] = "model",
1279 [GNU_AK_TRAP_EXIT] = "trap_exit",
1280 [GNU_AK_SP_SWITCH] = "sp_switch",
1281 [GNU_AK_SENTINEL] = "sentinel"
1285 * compare two string, ignoring double underscores on the second.
1287 static int strcmp_underscore(const char *s1, const char *s2)
1289 if (s2[0] == '_' && s2[1] == '_') {
1290 size_t len2 = strlen(s2);
1291 size_t len1 = strlen(s1);
1292 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1293 return strncmp(s1, s2+2, len2-4);
1297 return strcmp(s1, s2);
1301 * Allocate a new gnu temporal attribute.
1303 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1305 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1306 attribute->kind = kind;
1307 attribute->next = NULL;
1308 attribute->invalid = false;
1309 attribute->have_arguments = false;
1315 * parse one constant expression argument.
1317 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1319 expression_t *expression;
1320 add_anchor_token(')');
1321 expression = parse_constant_expression();
1322 rem_anchor_token(')');
1324 attribute->u.argument = fold_constant(expression);
1327 attribute->invalid = true;
1331 * parse a list of constant expressions arguments.
1333 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1335 argument_list_t **list = &attribute->u.arguments;
1336 argument_list_t *entry;
1337 expression_t *expression;
1338 add_anchor_token(')');
1339 add_anchor_token(',');
1341 expression = parse_constant_expression();
1342 entry = obstack_alloc(&temp_obst, sizeof(entry));
1343 entry->argument = fold_constant(expression);
1346 list = &entry->next;
1347 if (token.type != ',')
1351 rem_anchor_token(',');
1352 rem_anchor_token(')');
1356 attribute->invalid = true;
1360 * parse one string literal argument.
1362 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1365 add_anchor_token('(');
1366 if (token.type != T_STRING_LITERAL) {
1367 parse_error_expected("while parsing attribute directive",
1368 T_STRING_LITERAL, NULL);
1371 *string = parse_string_literals();
1372 rem_anchor_token('(');
1376 attribute->invalid = true;
1380 * parse one tls model.
1382 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1384 static const char *const tls_models[] = {
1390 string_t string = { NULL, 0 };
1391 parse_gnu_attribute_string_arg(attribute, &string);
1392 if (string.begin != NULL) {
1393 for(size_t i = 0; i < 4; ++i) {
1394 if (strcmp(tls_models[i], string.begin) == 0) {
1395 attribute->u.value = i;
1399 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1401 attribute->invalid = true;
1405 * parse one tls model.
1407 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1409 static const char *const visibilities[] = {
1415 string_t string = { NULL, 0 };
1416 parse_gnu_attribute_string_arg(attribute, &string);
1417 if (string.begin != NULL) {
1418 for(size_t i = 0; i < 4; ++i) {
1419 if (strcmp(visibilities[i], string.begin) == 0) {
1420 attribute->u.value = i;
1424 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1426 attribute->invalid = true;
1430 * parse one (code) model.
1432 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1434 static const char *const visibilities[] = {
1439 string_t string = { NULL, 0 };
1440 parse_gnu_attribute_string_arg(attribute, &string);
1441 if (string.begin != NULL) {
1442 for(int i = 0; i < 3; ++i) {
1443 if (strcmp(visibilities[i], string.begin) == 0) {
1444 attribute->u.value = i;
1448 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1450 attribute->invalid = true;
1453 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1455 /* TODO: find out what is allowed here... */
1457 /* at least: byte, word, pointer, list of machine modes
1458 * __XXX___ is interpreted as XXX */
1459 add_anchor_token(')');
1461 if (token.type != T_IDENTIFIER) {
1462 expect(T_IDENTIFIER);
1465 /* This isn't really correct, the backend should provide a list of machine
1466 * specific modes (according to gcc philosophy that is...) */
1467 const char *symbol_str = token.v.symbol->string;
1468 if (strcmp_underscore("QI", symbol_str) == 0 ||
1469 strcmp_underscore("byte", symbol_str) == 0) {
1470 attribute->u.akind = ATOMIC_TYPE_CHAR;
1471 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1472 attribute->u.akind = ATOMIC_TYPE_SHORT;
1473 } else if (strcmp_underscore("SI", symbol_str) == 0
1474 || strcmp_underscore("word", symbol_str) == 0
1475 || strcmp_underscore("pointer", symbol_str) == 0) {
1476 attribute->u.akind = ATOMIC_TYPE_INT;
1477 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1478 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1481 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1482 attribute->invalid = true;
1486 rem_anchor_token(')');
1490 attribute->invalid = true;
1494 * parse one interrupt argument.
1496 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1498 static const char *const interrupts[] = {
1505 string_t string = { NULL, 0 };
1506 parse_gnu_attribute_string_arg(attribute, &string);
1507 if (string.begin != NULL) {
1508 for(size_t i = 0; i < 5; ++i) {
1509 if (strcmp(interrupts[i], string.begin) == 0) {
1510 attribute->u.value = i;
1514 errorf(HERE, "'%s' is not an interrupt", string.begin);
1516 attribute->invalid = true;
1520 * parse ( identifier, const expression, const expression )
1522 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1524 static const char *const format_names[] = {
1532 if (token.type != T_IDENTIFIER) {
1533 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1536 const char *name = token.v.symbol->string;
1537 for(i = 0; i < 4; ++i) {
1538 if (strcmp_underscore(format_names[i], name) == 0)
1542 if (warning.attribute)
1543 warningf(HERE, "'%s' is an unrecognized format function type", name);
1548 add_anchor_token(')');
1549 add_anchor_token(',');
1550 parse_constant_expression();
1551 rem_anchor_token(',');
1552 rem_anchor_token(')');
1555 add_anchor_token(')');
1556 parse_constant_expression();
1557 rem_anchor_token(')');
1561 attribute->u.value = true;
1564 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1566 if (!attribute->have_arguments)
1569 /* should have no arguments */
1570 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1571 eat_until_matching_token('(');
1572 /* we have already consumed '(', so we stop before ')', eat it */
1574 attribute->invalid = true;
1578 * Parse one GNU attribute.
1580 * Note that attribute names can be specified WITH or WITHOUT
1581 * double underscores, ie const or __const__.
1583 * The following attributes are parsed without arguments
1608 * no_instrument_function
1609 * warn_unused_result
1626 * externally_visible
1634 * The following attributes are parsed with arguments
1635 * aligned( const expression )
1636 * alias( string literal )
1637 * section( string literal )
1638 * format( identifier, const expression, const expression )
1639 * format_arg( const expression )
1640 * tls_model( string literal )
1641 * visibility( string literal )
1642 * regparm( const expression )
1643 * model( string leteral )
1644 * trap_exit( const expression )
1645 * sp_switch( string literal )
1647 * The following attributes might have arguments
1648 * weak_ref( string literal )
1649 * non_null( const expression // ',' )
1650 * interrupt( string literal )
1651 * sentinel( constant expression )
1653 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1655 gnu_attribute_t *head = *attributes;
1656 gnu_attribute_t *last = *attributes;
1657 decl_modifiers_t modifiers = 0;
1658 gnu_attribute_t *attribute;
1660 eat(T___attribute__);
1664 if (token.type != ')') {
1665 /* find the end of the list */
1667 while (last->next != NULL)
1671 /* non-empty attribute list */
1674 if (token.type == T_const) {
1676 } else if (token.type == T_volatile) {
1678 } else if (token.type == T_cdecl) {
1679 /* __attribute__((cdecl)), WITH ms mode */
1681 } else if (token.type == T_IDENTIFIER) {
1682 const symbol_t *sym = token.v.symbol;
1685 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1692 for(i = 0; i < GNU_AK_LAST; ++i) {
1693 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1696 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1699 if (kind == GNU_AK_LAST) {
1700 if (warning.attribute)
1701 warningf(HERE, "'%s' attribute directive ignored", name);
1703 /* skip possible arguments */
1704 if (token.type == '(') {
1705 eat_until_matching_token(')');
1708 /* check for arguments */
1709 attribute = allocate_gnu_attribute(kind);
1710 if (token.type == '(') {
1712 if (token.type == ')') {
1713 /* empty args are allowed */
1716 attribute->have_arguments = true;
1720 case GNU_AK_VOLATILE:
1725 case GNU_AK_NOCOMMON:
1727 case GNU_AK_NOTSHARED:
1728 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1729 case GNU_AK_WARN_UNUSED_RESULT:
1730 case GNU_AK_LONGCALL:
1731 case GNU_AK_SHORTCALL:
1732 case GNU_AK_LONG_CALL:
1733 case GNU_AK_SHORT_CALL:
1734 case GNU_AK_FUNCTION_VECTOR:
1735 case GNU_AK_INTERRUPT_HANDLER:
1736 case GNU_AK_NMI_HANDLER:
1737 case GNU_AK_NESTING:
1741 case GNU_AK_EIGTHBIT_DATA:
1742 case GNU_AK_TINY_DATA:
1743 case GNU_AK_SAVEALL:
1744 case GNU_AK_FLATTEN:
1745 case GNU_AK_SSEREGPARM:
1746 case GNU_AK_EXTERNALLY_VISIBLE:
1747 case GNU_AK_RETURN_TWICE:
1748 case GNU_AK_MAY_ALIAS:
1749 case GNU_AK_MS_STRUCT:
1750 case GNU_AK_GCC_STRUCT:
1753 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1754 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1755 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1756 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1757 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1758 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1759 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1760 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1761 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1762 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1763 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1764 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1765 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1766 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1767 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1768 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1769 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1770 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1772 case GNU_AK_ALIGNED:
1773 /* __align__ may be used without an argument */
1774 if (attribute->have_arguments) {
1775 parse_gnu_attribute_const_arg(attribute);
1779 case GNU_AK_FORMAT_ARG:
1780 case GNU_AK_REGPARM:
1781 case GNU_AK_TRAP_EXIT:
1782 if (!attribute->have_arguments) {
1783 /* should have arguments */
1784 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1785 attribute->invalid = true;
1787 parse_gnu_attribute_const_arg(attribute);
1790 case GNU_AK_SECTION:
1791 case GNU_AK_SP_SWITCH:
1792 if (!attribute->have_arguments) {
1793 /* should have arguments */
1794 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1795 attribute->invalid = true;
1797 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1800 if (!attribute->have_arguments) {
1801 /* should have arguments */
1802 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1803 attribute->invalid = true;
1805 parse_gnu_attribute_format_args(attribute);
1807 case GNU_AK_WEAKREF:
1808 /* may have one string argument */
1809 if (attribute->have_arguments)
1810 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1812 case GNU_AK_NONNULL:
1813 if (attribute->have_arguments)
1814 parse_gnu_attribute_const_arg_list(attribute);
1816 case GNU_AK_TLS_MODEL:
1817 if (!attribute->have_arguments) {
1818 /* should have arguments */
1819 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1821 parse_gnu_attribute_tls_model_arg(attribute);
1823 case GNU_AK_VISIBILITY:
1824 if (!attribute->have_arguments) {
1825 /* should have arguments */
1826 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1828 parse_gnu_attribute_visibility_arg(attribute);
1831 if (!attribute->have_arguments) {
1832 /* should have arguments */
1833 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1835 parse_gnu_attribute_model_arg(attribute);
1839 if (!attribute->have_arguments) {
1840 /* should have arguments */
1841 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1843 parse_gnu_attribute_mode_arg(attribute);
1846 case GNU_AK_INTERRUPT:
1847 /* may have one string argument */
1848 if (attribute->have_arguments)
1849 parse_gnu_attribute_interrupt_arg(attribute);
1851 case GNU_AK_SENTINEL:
1852 /* may have one string argument */
1853 if (attribute->have_arguments)
1854 parse_gnu_attribute_const_arg(attribute);
1857 /* already handled */
1861 check_no_argument(attribute, name);
1864 if (attribute != NULL) {
1866 last->next = attribute;
1869 head = last = attribute;
1873 if (token.type != ',')
1887 * Parse GNU attributes.
1889 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1891 decl_modifiers_t modifiers = 0;
1894 switch(token.type) {
1895 case T___attribute__:
1896 modifiers |= parse_gnu_attribute(attributes);
1902 if (token.type != T_STRING_LITERAL) {
1903 parse_error_expected("while parsing assembler attribute",
1904 T_STRING_LITERAL, NULL);
1905 eat_until_matching_token('(');
1908 parse_string_literals();
1913 case T_cdecl: modifiers |= DM_CDECL; break;
1914 case T__fastcall: modifiers |= DM_FASTCALL; break;
1915 case T__stdcall: modifiers |= DM_STDCALL; break;
1918 /* TODO record modifier */
1920 warningf(HERE, "Ignoring declaration modifier %K", &token);
1924 default: return modifiers;
1931 static void mark_decls_read(expression_t *expr, declaration_t *lhs_decl);
1933 static declaration_t *determine_lhs_decl(expression_t *const expr, declaration_t *lhs_decl)
1935 switch (expr->kind) {
1936 case EXPR_REFERENCE: {
1937 declaration_t *const decl = expr->reference.declaration;
1941 case EXPR_ARRAY_ACCESS: {
1942 expression_t *const ref = expr->array_access.array_ref;
1943 declaration_t * decl = NULL;
1944 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1945 decl = determine_lhs_decl(ref, lhs_decl);
1948 mark_decls_read(expr->select.compound, lhs_decl);
1950 mark_decls_read(expr->array_access.index, lhs_decl);
1955 if (is_type_compound(skip_typeref(expr->base.type))) {
1956 return determine_lhs_decl(expr->select.compound, lhs_decl);
1958 mark_decls_read(expr->select.compound, lhs_decl);
1963 case EXPR_UNARY_DEREFERENCE: {
1964 expression_t *const val = expr->unary.value;
1965 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1967 return determine_lhs_decl(val->unary.value, lhs_decl);
1969 mark_decls_read(val, NULL);
1975 mark_decls_read(expr, NULL);
1980 #define DECL_ANY ((declaration_t*)-1)
1983 * Mark declarations, which are read. This is used to deted variables, which
1987 * x is not marked as "read", because it is only read to calculate its own new
1991 * x and y are not detected as "not read", because multiple variables are
1994 static void mark_decls_read(expression_t *const expr, declaration_t *lhs_decl)
1996 switch (expr->kind) {
1997 case EXPR_REFERENCE: {
1998 declaration_t *const decl = expr->reference.declaration;
1999 if (lhs_decl != decl && lhs_decl != DECL_ANY)
2005 // TODO respect pure/const
2006 mark_decls_read(expr->call.function, NULL);
2007 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2008 mark_decls_read(arg->expression, NULL);
2012 case EXPR_CONDITIONAL:
2013 // TODO lhs_decl should depend on whether true/false have an effect
2014 mark_decls_read(expr->conditional.condition, NULL);
2015 if (expr->conditional.true_expression != NULL)
2016 mark_decls_read(expr->conditional.true_expression, lhs_decl);
2017 mark_decls_read(expr->conditional.false_expression, lhs_decl);
2021 if (lhs_decl == DECL_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2023 mark_decls_read(expr->select.compound, lhs_decl);
2026 case EXPR_ARRAY_ACCESS: {
2027 expression_t *const ref = expr->array_access.array_ref;
2028 mark_decls_read(ref, lhs_decl);
2029 lhs_decl = determine_lhs_decl(ref, lhs_decl);
2030 mark_decls_read(expr->array_access.index, lhs_decl);
2035 mark_decls_read(expr->va_arge.ap, lhs_decl);
2038 case EXPR_UNARY_CAST:
2039 /* Special case: Use void cast to mark a variable as "read" */
2040 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2044 case EXPR_UNARY_DEREFERENCE:
2045 if (lhs_decl == DECL_ANY)
2049 case EXPR_UNARY_THROW:
2050 if (expr->unary.value == NULL)
2054 case EXPR_UNARY_NEGATE:
2055 case EXPR_UNARY_PLUS:
2056 case EXPR_UNARY_BITWISE_NEGATE:
2057 case EXPR_UNARY_NOT:
2058 case EXPR_UNARY_TAKE_ADDRESS:
2059 case EXPR_UNARY_POSTFIX_INCREMENT:
2060 case EXPR_UNARY_POSTFIX_DECREMENT:
2061 case EXPR_UNARY_PREFIX_INCREMENT:
2062 case EXPR_UNARY_PREFIX_DECREMENT:
2063 case EXPR_UNARY_CAST_IMPLICIT:
2064 case EXPR_UNARY_ASSUME:
2066 mark_decls_read(expr->unary.value, lhs_decl);
2069 case EXPR_BINARY_ADD:
2070 case EXPR_BINARY_SUB:
2071 case EXPR_BINARY_MUL:
2072 case EXPR_BINARY_DIV:
2073 case EXPR_BINARY_MOD:
2074 case EXPR_BINARY_EQUAL:
2075 case EXPR_BINARY_NOTEQUAL:
2076 case EXPR_BINARY_LESS:
2077 case EXPR_BINARY_LESSEQUAL:
2078 case EXPR_BINARY_GREATER:
2079 case EXPR_BINARY_GREATEREQUAL:
2080 case EXPR_BINARY_BITWISE_AND:
2081 case EXPR_BINARY_BITWISE_OR:
2082 case EXPR_BINARY_BITWISE_XOR:
2083 case EXPR_BINARY_LOGICAL_AND:
2084 case EXPR_BINARY_LOGICAL_OR:
2085 case EXPR_BINARY_SHIFTLEFT:
2086 case EXPR_BINARY_SHIFTRIGHT:
2087 case EXPR_BINARY_COMMA:
2088 case EXPR_BINARY_ISGREATER:
2089 case EXPR_BINARY_ISGREATEREQUAL:
2090 case EXPR_BINARY_ISLESS:
2091 case EXPR_BINARY_ISLESSEQUAL:
2092 case EXPR_BINARY_ISLESSGREATER:
2093 case EXPR_BINARY_ISUNORDERED:
2094 mark_decls_read(expr->binary.left, lhs_decl);
2095 mark_decls_read(expr->binary.right, lhs_decl);
2098 case EXPR_BINARY_ASSIGN:
2099 case EXPR_BINARY_MUL_ASSIGN:
2100 case EXPR_BINARY_DIV_ASSIGN:
2101 case EXPR_BINARY_MOD_ASSIGN:
2102 case EXPR_BINARY_ADD_ASSIGN:
2103 case EXPR_BINARY_SUB_ASSIGN:
2104 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2105 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2106 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2107 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2108 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2109 if (lhs_decl == DECL_ANY)
2111 lhs_decl = determine_lhs_decl(expr->binary.left, lhs_decl);
2112 mark_decls_read(expr->binary.right, lhs_decl);
2117 determine_lhs_decl(expr->va_starte.ap, lhs_decl);
2123 case EXPR_CHARACTER_CONSTANT:
2124 case EXPR_WIDE_CHARACTER_CONSTANT:
2125 case EXPR_STRING_LITERAL:
2126 case EXPR_WIDE_STRING_LITERAL:
2127 case EXPR_COMPOUND_LITERAL: // TODO init?
2129 case EXPR_CLASSIFY_TYPE:
2132 case EXPR_BUILTIN_SYMBOL:
2133 case EXPR_BUILTIN_CONSTANT_P:
2134 case EXPR_BUILTIN_PREFETCH:
2136 case EXPR_STATEMENT: // TODO
2137 case EXPR_LABEL_ADDRESS:
2138 case EXPR_BINARY_BUILTIN_EXPECT:
2142 panic("unhandled expression");
2145 static designator_t *parse_designation(void)
2147 designator_t *result = NULL;
2148 designator_t *last = NULL;
2151 designator_t *designator;
2152 switch(token.type) {
2154 designator = allocate_ast_zero(sizeof(designator[0]));
2155 designator->source_position = token.source_position;
2157 add_anchor_token(']');
2158 designator->array_index = parse_constant_expression();
2159 rem_anchor_token(']');
2163 designator = allocate_ast_zero(sizeof(designator[0]));
2164 designator->source_position = token.source_position;
2166 if (token.type != T_IDENTIFIER) {
2167 parse_error_expected("while parsing designator",
2168 T_IDENTIFIER, NULL);
2171 designator->symbol = token.v.symbol;
2179 assert(designator != NULL);
2181 last->next = designator;
2183 result = designator;
2191 static initializer_t *initializer_from_string(array_type_t *type,
2192 const string_t *const string)
2194 /* TODO: check len vs. size of array type */
2197 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2198 initializer->string.string = *string;
2203 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2204 wide_string_t *const string)
2206 /* TODO: check len vs. size of array type */
2209 initializer_t *const initializer =
2210 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2211 initializer->wide_string.string = *string;
2217 * Build an initializer from a given expression.
2219 static initializer_t *initializer_from_expression(type_t *orig_type,
2220 expression_t *expression)
2222 /* TODO check that expression is a constant expression */
2224 /* § 6.7.8.14/15 char array may be initialized by string literals */
2225 type_t *type = skip_typeref(orig_type);
2226 type_t *expr_type_orig = expression->base.type;
2227 type_t *expr_type = skip_typeref(expr_type_orig);
2228 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2229 array_type_t *const array_type = &type->array;
2230 type_t *const element_type = skip_typeref(array_type->element_type);
2232 if (element_type->kind == TYPE_ATOMIC) {
2233 atomic_type_kind_t akind = element_type->atomic.akind;
2234 switch (expression->kind) {
2235 case EXPR_STRING_LITERAL:
2236 if (akind == ATOMIC_TYPE_CHAR
2237 || akind == ATOMIC_TYPE_SCHAR
2238 || akind == ATOMIC_TYPE_UCHAR) {
2239 return initializer_from_string(array_type,
2240 &expression->string.value);
2243 case EXPR_WIDE_STRING_LITERAL: {
2244 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2245 if (get_unqualified_type(element_type) == bare_wchar_type) {
2246 return initializer_from_wide_string(array_type,
2247 &expression->wide_string.value);
2257 assign_error_t error = semantic_assign(type, expression);
2258 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2260 report_assign_error(error, type, expression, "initializer",
2261 &expression->base.source_position);
2263 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2265 if (type->kind == TYPE_BITFIELD) {
2266 type = type->bitfield.base_type;
2269 result->value.value = create_implicit_cast(expression, type);
2275 * Checks if a given expression can be used as an constant initializer.
2277 static bool is_initializer_constant(const expression_t *expression)
2279 return is_constant_expression(expression)
2280 || is_address_constant(expression);
2284 * Parses an scalar initializer.
2286 * § 6.7.8.11; eat {} without warning
2288 static initializer_t *parse_scalar_initializer(type_t *type,
2289 bool must_be_constant)
2291 /* there might be extra {} hierarchies */
2293 if (token.type == '{') {
2295 warningf(HERE, "extra curly braces around scalar initializer");
2299 } while (token.type == '{');
2302 expression_t *expression = parse_assignment_expression();
2303 mark_decls_read(expression, NULL);
2304 if (must_be_constant && !is_initializer_constant(expression)) {
2305 errorf(&expression->base.source_position,
2306 "Initialisation expression '%E' is not constant\n",
2310 initializer_t *initializer = initializer_from_expression(type, expression);
2312 if (initializer == NULL) {
2313 errorf(&expression->base.source_position,
2314 "expression '%E' (type '%T') doesn't match expected type '%T'",
2315 expression, expression->base.type, type);
2320 bool additional_warning_displayed = false;
2321 while (braces > 0) {
2322 if (token.type == ',') {
2325 if (token.type != '}') {
2326 if (!additional_warning_displayed && warning.other) {
2327 warningf(HERE, "additional elements in scalar initializer");
2328 additional_warning_displayed = true;
2339 * An entry in the type path.
2341 typedef struct type_path_entry_t type_path_entry_t;
2342 struct type_path_entry_t {
2343 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2345 size_t index; /**< For array types: the current index. */
2346 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2351 * A type path expression a position inside compound or array types.
2353 typedef struct type_path_t type_path_t;
2354 struct type_path_t {
2355 type_path_entry_t *path; /**< An flexible array containing the current path. */
2356 type_t *top_type; /**< type of the element the path points */
2357 size_t max_index; /**< largest index in outermost array */
2361 * Prints a type path for debugging.
2363 static __attribute__((unused)) void debug_print_type_path(
2364 const type_path_t *path)
2366 size_t len = ARR_LEN(path->path);
2368 for(size_t i = 0; i < len; ++i) {
2369 const type_path_entry_t *entry = & path->path[i];
2371 type_t *type = skip_typeref(entry->type);
2372 if (is_type_compound(type)) {
2373 /* in gcc mode structs can have no members */
2374 if (entry->v.compound_entry == NULL) {
2378 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2379 } else if (is_type_array(type)) {
2380 fprintf(stderr, "[%zu]", entry->v.index);
2382 fprintf(stderr, "-INVALID-");
2385 if (path->top_type != NULL) {
2386 fprintf(stderr, " (");
2387 print_type(path->top_type);
2388 fprintf(stderr, ")");
2393 * Return the top type path entry, ie. in a path
2394 * (type).a.b returns the b.
2396 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2398 size_t len = ARR_LEN(path->path);
2400 return &path->path[len-1];
2404 * Enlarge the type path by an (empty) element.
2406 static type_path_entry_t *append_to_type_path(type_path_t *path)
2408 size_t len = ARR_LEN(path->path);
2409 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2411 type_path_entry_t *result = & path->path[len];
2412 memset(result, 0, sizeof(result[0]));
2417 * Descending into a sub-type. Enter the scope of the current
2420 static void descend_into_subtype(type_path_t *path)
2422 type_t *orig_top_type = path->top_type;
2423 type_t *top_type = skip_typeref(orig_top_type);
2425 type_path_entry_t *top = append_to_type_path(path);
2426 top->type = top_type;
2428 if (is_type_compound(top_type)) {
2429 declaration_t *declaration = top_type->compound.declaration;
2430 declaration_t *entry = declaration->scope.declarations;
2431 top->v.compound_entry = entry;
2433 if (entry != NULL) {
2434 path->top_type = entry->type;
2436 path->top_type = NULL;
2438 } else if (is_type_array(top_type)) {
2440 path->top_type = top_type->array.element_type;
2442 assert(!is_type_valid(top_type));
2447 * Pop an entry from the given type path, ie. returning from
2448 * (type).a.b to (type).a
2450 static void ascend_from_subtype(type_path_t *path)
2452 type_path_entry_t *top = get_type_path_top(path);
2454 path->top_type = top->type;
2456 size_t len = ARR_LEN(path->path);
2457 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2461 * Pop entries from the given type path until the given
2462 * path level is reached.
2464 static void ascend_to(type_path_t *path, size_t top_path_level)
2466 size_t len = ARR_LEN(path->path);
2468 while (len > top_path_level) {
2469 ascend_from_subtype(path);
2470 len = ARR_LEN(path->path);
2474 static bool walk_designator(type_path_t *path, const designator_t *designator,
2475 bool used_in_offsetof)
2477 for( ; designator != NULL; designator = designator->next) {
2478 type_path_entry_t *top = get_type_path_top(path);
2479 type_t *orig_type = top->type;
2481 type_t *type = skip_typeref(orig_type);
2483 if (designator->symbol != NULL) {
2484 symbol_t *symbol = designator->symbol;
2485 if (!is_type_compound(type)) {
2486 if (is_type_valid(type)) {
2487 errorf(&designator->source_position,
2488 "'.%Y' designator used for non-compound type '%T'",
2492 top->type = type_error_type;
2493 top->v.compound_entry = NULL;
2494 orig_type = type_error_type;
2496 declaration_t *declaration = type->compound.declaration;
2497 declaration_t *iter = declaration->scope.declarations;
2498 for( ; iter != NULL; iter = iter->next) {
2499 if (iter->symbol == symbol) {
2504 errorf(&designator->source_position,
2505 "'%T' has no member named '%Y'", orig_type, symbol);
2508 if (used_in_offsetof) {
2509 type_t *real_type = skip_typeref(iter->type);
2510 if (real_type->kind == TYPE_BITFIELD) {
2511 errorf(&designator->source_position,
2512 "offsetof designator '%Y' may not specify bitfield",
2518 top->type = orig_type;
2519 top->v.compound_entry = iter;
2520 orig_type = iter->type;
2523 expression_t *array_index = designator->array_index;
2524 assert(designator->array_index != NULL);
2526 if (!is_type_array(type)) {
2527 if (is_type_valid(type)) {
2528 errorf(&designator->source_position,
2529 "[%E] designator used for non-array type '%T'",
2530 array_index, orig_type);
2535 long index = fold_constant(array_index);
2536 if (!used_in_offsetof) {
2538 errorf(&designator->source_position,
2539 "array index [%E] must be positive", array_index);
2540 } else if (type->array.size_constant) {
2541 long array_size = type->array.size;
2542 if (index >= array_size) {
2543 errorf(&designator->source_position,
2544 "designator [%E] (%d) exceeds array size %d",
2545 array_index, index, array_size);
2550 top->type = orig_type;
2551 top->v.index = (size_t) index;
2552 orig_type = type->array.element_type;
2554 path->top_type = orig_type;
2556 if (designator->next != NULL) {
2557 descend_into_subtype(path);
2566 static void advance_current_object(type_path_t *path, size_t top_path_level)
2568 type_path_entry_t *top = get_type_path_top(path);
2570 type_t *type = skip_typeref(top->type);
2571 if (is_type_union(type)) {
2572 /* in unions only the first element is initialized */
2573 top->v.compound_entry = NULL;
2574 } else if (is_type_struct(type)) {
2575 declaration_t *entry = top->v.compound_entry;
2577 entry = entry->next;
2578 top->v.compound_entry = entry;
2579 if (entry != NULL) {
2580 path->top_type = entry->type;
2583 } else if (is_type_array(type)) {
2584 assert(is_type_array(type));
2588 if (!type->array.size_constant || top->v.index < type->array.size) {
2592 assert(!is_type_valid(type));
2596 /* we're past the last member of the current sub-aggregate, try if we
2597 * can ascend in the type hierarchy and continue with another subobject */
2598 size_t len = ARR_LEN(path->path);
2600 if (len > top_path_level) {
2601 ascend_from_subtype(path);
2602 advance_current_object(path, top_path_level);
2604 path->top_type = NULL;
2609 * skip until token is found.
2611 static void skip_until(int type)
2613 while (token.type != type) {
2614 if (token.type == T_EOF)
2621 * skip any {...} blocks until a closing bracket is reached.
2623 static void skip_initializers(void)
2625 if (token.type == '{')
2628 while (token.type != '}') {
2629 if (token.type == T_EOF)
2631 if (token.type == '{') {
2639 static initializer_t *create_empty_initializer(void)
2641 static initializer_t empty_initializer
2642 = { .list = { { INITIALIZER_LIST }, 0 } };
2643 return &empty_initializer;
2647 * Parse a part of an initialiser for a struct or union,
2649 static initializer_t *parse_sub_initializer(type_path_t *path,
2650 type_t *outer_type, size_t top_path_level,
2651 parse_initializer_env_t *env)
2653 if (token.type == '}') {
2654 /* empty initializer */
2655 return create_empty_initializer();
2658 type_t *orig_type = path->top_type;
2659 type_t *type = NULL;
2661 if (orig_type == NULL) {
2662 /* We are initializing an empty compound. */
2664 type = skip_typeref(orig_type);
2667 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2670 designator_t *designator = NULL;
2671 if (token.type == '.' || token.type == '[') {
2672 designator = parse_designation();
2673 goto finish_designator;
2674 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2675 /* GNU-style designator ("identifier: value") */
2676 designator = allocate_ast_zero(sizeof(designator[0]));
2677 designator->source_position = token.source_position;
2678 designator->symbol = token.v.symbol;
2683 /* reset path to toplevel, evaluate designator from there */
2684 ascend_to(path, top_path_level);
2685 if (!walk_designator(path, designator, false)) {
2686 /* can't continue after designation error */
2690 initializer_t *designator_initializer
2691 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2692 designator_initializer->designator.designator = designator;
2693 ARR_APP1(initializer_t*, initializers, designator_initializer);
2695 orig_type = path->top_type;
2696 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2701 if (token.type == '{') {
2702 if (type != NULL && is_type_scalar(type)) {
2703 sub = parse_scalar_initializer(type, env->must_be_constant);
2707 if (env->declaration != NULL) {
2708 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2709 env->declaration->symbol);
2711 errorf(HERE, "extra brace group at end of initializer");
2714 descend_into_subtype(path);
2716 add_anchor_token('}');
2717 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2719 rem_anchor_token('}');
2722 ascend_from_subtype(path);
2726 goto error_parse_next;
2730 /* must be an expression */
2731 expression_t *expression = parse_assignment_expression();
2733 if (env->must_be_constant && !is_initializer_constant(expression)) {
2734 errorf(&expression->base.source_position,
2735 "Initialisation expression '%E' is not constant\n",
2740 /* we are already outside, ... */
2741 type_t *const outer_type_skip = skip_typeref(outer_type);
2742 if (is_type_compound(outer_type_skip) &&
2743 !outer_type_skip->compound.declaration->init.complete) {
2744 goto error_parse_next;
2749 /* handle { "string" } special case */
2750 if ((expression->kind == EXPR_STRING_LITERAL
2751 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2752 && outer_type != NULL) {
2753 sub = initializer_from_expression(outer_type, expression);
2755 if (token.type == ',') {
2758 if (token.type != '}' && warning.other) {
2759 warningf(HERE, "excessive elements in initializer for type '%T'",
2762 /* TODO: eat , ... */
2767 /* descend into subtypes until expression matches type */
2769 orig_type = path->top_type;
2770 type = skip_typeref(orig_type);
2772 sub = initializer_from_expression(orig_type, expression);
2776 if (!is_type_valid(type)) {
2779 if (is_type_scalar(type)) {
2780 errorf(&expression->base.source_position,
2781 "expression '%E' doesn't match expected type '%T'",
2782 expression, orig_type);
2786 descend_into_subtype(path);
2790 /* update largest index of top array */
2791 const type_path_entry_t *first = &path->path[0];
2792 type_t *first_type = first->type;
2793 first_type = skip_typeref(first_type);
2794 if (is_type_array(first_type)) {
2795 size_t index = first->v.index;
2796 if (index > path->max_index)
2797 path->max_index = index;
2801 /* append to initializers list */
2802 ARR_APP1(initializer_t*, initializers, sub);
2805 if (warning.other) {
2806 if (env->declaration != NULL) {
2807 warningf(HERE, "excess elements in struct initializer for '%Y'",
2808 env->declaration->symbol);
2810 warningf(HERE, "excess elements in struct initializer");
2816 if (token.type == '}') {
2820 if (token.type == '}') {
2825 /* advance to the next declaration if we are not at the end */
2826 advance_current_object(path, top_path_level);
2827 orig_type = path->top_type;
2828 if (orig_type != NULL)
2829 type = skip_typeref(orig_type);
2835 size_t len = ARR_LEN(initializers);
2836 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2837 initializer_t *result = allocate_ast_zero(size);
2838 result->kind = INITIALIZER_LIST;
2839 result->list.len = len;
2840 memcpy(&result->list.initializers, initializers,
2841 len * sizeof(initializers[0]));
2843 DEL_ARR_F(initializers);
2844 ascend_to(path, top_path_level+1);
2849 skip_initializers();
2850 DEL_ARR_F(initializers);
2851 ascend_to(path, top_path_level+1);
2856 * Parses an initializer. Parsers either a compound literal
2857 * (env->declaration == NULL) or an initializer of a declaration.
2859 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2861 type_t *type = skip_typeref(env->type);
2862 initializer_t *result = NULL;
2865 if (is_type_scalar(type)) {
2866 result = parse_scalar_initializer(type, env->must_be_constant);
2867 } else if (token.type == '{') {
2871 memset(&path, 0, sizeof(path));
2872 path.top_type = env->type;
2873 path.path = NEW_ARR_F(type_path_entry_t, 0);
2875 descend_into_subtype(&path);
2877 add_anchor_token('}');
2878 result = parse_sub_initializer(&path, env->type, 1, env);
2879 rem_anchor_token('}');
2881 max_index = path.max_index;
2882 DEL_ARR_F(path.path);
2886 /* parse_scalar_initializer() also works in this case: we simply
2887 * have an expression without {} around it */
2888 result = parse_scalar_initializer(type, env->must_be_constant);
2891 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2892 * the array type size */
2893 if (is_type_array(type) && type->array.size_expression == NULL
2894 && result != NULL) {
2896 switch (result->kind) {
2897 case INITIALIZER_LIST:
2898 size = max_index + 1;
2901 case INITIALIZER_STRING:
2902 size = result->string.string.size;
2905 case INITIALIZER_WIDE_STRING:
2906 size = result->wide_string.string.size;
2909 case INITIALIZER_DESIGNATOR:
2910 case INITIALIZER_VALUE:
2911 /* can happen for parse errors */
2916 internal_errorf(HERE, "invalid initializer type");
2919 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2920 cnst->base.type = type_size_t;
2921 cnst->conste.v.int_value = size;
2923 type_t *new_type = duplicate_type(type);
2925 new_type->array.size_expression = cnst;
2926 new_type->array.size_constant = true;
2927 new_type->array.size = size;
2928 env->type = new_type;
2936 static declaration_t *append_declaration(declaration_t *declaration);
2938 static declaration_t *parse_compound_type_specifier(bool is_struct)
2940 gnu_attribute_t *attributes = NULL;
2941 decl_modifiers_t modifiers = 0;
2948 symbol_t *symbol = NULL;
2949 declaration_t *declaration = NULL;
2951 if (token.type == T___attribute__) {
2952 modifiers |= parse_attributes(&attributes);
2955 if (token.type == T_IDENTIFIER) {
2956 symbol = token.v.symbol;
2959 namespace_t const namespc =
2960 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2961 declaration = get_declaration(symbol, namespc);
2962 if (declaration != NULL) {
2963 if (declaration->parent_scope != scope &&
2964 (token.type == '{' || token.type == ';')) {
2966 } else if (declaration->init.complete &&
2967 token.type == '{') {
2968 assert(symbol != NULL);
2969 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2970 is_struct ? "struct" : "union", symbol,
2971 &declaration->source_position);
2972 declaration->scope.declarations = NULL;
2975 } else if (token.type != '{') {
2977 parse_error_expected("while parsing struct type specifier",
2978 T_IDENTIFIER, '{', NULL);
2980 parse_error_expected("while parsing union type specifier",
2981 T_IDENTIFIER, '{', NULL);
2987 if (declaration == NULL) {
2988 declaration = allocate_declaration_zero();
2989 declaration->namespc =
2990 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2991 declaration->source_position = token.source_position;
2992 declaration->symbol = symbol;
2993 declaration->parent_scope = scope;
2994 if (symbol != NULL) {
2995 environment_push(declaration);
2997 append_declaration(declaration);
3000 if (token.type == '{') {
3001 declaration->init.complete = true;
3003 parse_compound_type_entries(declaration);
3004 modifiers |= parse_attributes(&attributes);
3007 declaration->modifiers |= modifiers;
3011 static void parse_enum_entries(type_t *const enum_type)
3015 if (token.type == '}') {
3017 errorf(HERE, "empty enum not allowed");
3021 add_anchor_token('}');
3023 if (token.type != T_IDENTIFIER) {
3024 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3026 rem_anchor_token('}');
3030 declaration_t *const entry = allocate_declaration_zero();
3031 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
3032 entry->type = enum_type;
3033 entry->symbol = token.v.symbol;
3034 entry->source_position = token.source_position;
3037 if (token.type == '=') {
3039 expression_t *value = parse_constant_expression();
3041 value = create_implicit_cast(value, enum_type);
3042 entry->init.enum_value = value;
3047 record_declaration(entry, false);
3049 if (token.type != ',')
3052 } while (token.type != '}');
3053 rem_anchor_token('}');
3061 static type_t *parse_enum_specifier(void)
3063 gnu_attribute_t *attributes = NULL;
3064 declaration_t *declaration;
3068 if (token.type == T_IDENTIFIER) {
3069 symbol = token.v.symbol;
3072 declaration = get_declaration(symbol, NAMESPACE_ENUM);
3073 } else if (token.type != '{') {
3074 parse_error_expected("while parsing enum type specifier",
3075 T_IDENTIFIER, '{', NULL);
3082 if (declaration == NULL) {
3083 declaration = allocate_declaration_zero();
3084 declaration->namespc = NAMESPACE_ENUM;
3085 declaration->source_position = token.source_position;
3086 declaration->symbol = symbol;
3087 declaration->parent_scope = scope;
3090 type_t *const type = allocate_type_zero(TYPE_ENUM);
3091 type->enumt.declaration = declaration;
3093 if (token.type == '{') {
3094 if (declaration->init.complete) {
3095 errorf(HERE, "multiple definitions of enum %Y", symbol);
3097 if (symbol != NULL) {
3098 environment_push(declaration);
3100 append_declaration(declaration);
3101 declaration->init.complete = true;
3103 parse_enum_entries(type);
3104 parse_attributes(&attributes);
3111 * if a symbol is a typedef to another type, return true
3113 static bool is_typedef_symbol(symbol_t *symbol)
3115 const declaration_t *const declaration =
3116 get_declaration(symbol, NAMESPACE_NORMAL);
3118 declaration != NULL &&
3119 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
3122 static type_t *parse_typeof(void)
3129 add_anchor_token(')');
3131 expression_t *expression = NULL;
3133 bool old_type_prop = in_type_prop;
3134 bool old_gcc_extension = in_gcc_extension;
3135 in_type_prop = true;
3137 while (token.type == T___extension__) {
3138 /* This can be a prefix to a typename or an expression. */
3140 in_gcc_extension = true;
3142 switch (token.type) {
3144 if (is_typedef_symbol(token.v.symbol)) {
3145 type = parse_typename();
3147 expression = parse_expression();
3148 type = expression->base.type;
3153 type = parse_typename();
3157 expression = parse_expression();
3158 type = expression->base.type;
3161 in_type_prop = old_type_prop;
3162 in_gcc_extension = old_gcc_extension;
3164 rem_anchor_token(')');
3167 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3168 typeof_type->typeoft.expression = expression;
3169 typeof_type->typeoft.typeof_type = type;
3176 typedef enum specifiers_t {
3177 SPECIFIER_SIGNED = 1 << 0,
3178 SPECIFIER_UNSIGNED = 1 << 1,
3179 SPECIFIER_LONG = 1 << 2,
3180 SPECIFIER_INT = 1 << 3,
3181 SPECIFIER_DOUBLE = 1 << 4,
3182 SPECIFIER_CHAR = 1 << 5,
3183 SPECIFIER_SHORT = 1 << 6,
3184 SPECIFIER_LONG_LONG = 1 << 7,
3185 SPECIFIER_FLOAT = 1 << 8,
3186 SPECIFIER_BOOL = 1 << 9,
3187 SPECIFIER_VOID = 1 << 10,
3188 SPECIFIER_INT8 = 1 << 11,
3189 SPECIFIER_INT16 = 1 << 12,
3190 SPECIFIER_INT32 = 1 << 13,
3191 SPECIFIER_INT64 = 1 << 14,
3192 SPECIFIER_INT128 = 1 << 15,
3193 SPECIFIER_COMPLEX = 1 << 16,
3194 SPECIFIER_IMAGINARY = 1 << 17,
3197 static type_t *create_builtin_type(symbol_t *const symbol,
3198 type_t *const real_type)
3200 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3201 type->builtin.symbol = symbol;
3202 type->builtin.real_type = real_type;
3204 type_t *result = typehash_insert(type);
3205 if (type != result) {
3212 static type_t *get_typedef_type(symbol_t *symbol)
3214 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
3215 if (declaration == NULL ||
3216 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
3219 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3220 type->typedeft.declaration = declaration;
3226 * check for the allowed MS alignment values.
3228 static bool check_alignment_value(long long intvalue)
3230 if (intvalue < 1 || intvalue > 8192) {
3231 errorf(HERE, "illegal alignment value");
3234 unsigned v = (unsigned)intvalue;
3235 for (unsigned i = 1; i <= 8192; i += i) {
3239 errorf(HERE, "alignment must be power of two");
3243 #define DET_MOD(name, tag) do { \
3244 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3245 *modifiers |= tag; \
3248 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3250 decl_modifiers_t *modifiers = &specifiers->modifiers;
3253 if (token.type == T_restrict) {
3255 DET_MOD(restrict, DM_RESTRICT);
3257 } else if (token.type != T_IDENTIFIER)
3259 symbol_t *symbol = token.v.symbol;
3260 if (symbol == sym_align) {
3263 if (token.type != T_INTEGER)
3265 if (check_alignment_value(token.v.intvalue)) {
3266 if (specifiers->alignment != 0 && warning.other)
3267 warningf(HERE, "align used more than once");
3268 specifiers->alignment = (unsigned char)token.v.intvalue;
3272 } else if (symbol == sym_allocate) {
3275 if (token.type != T_IDENTIFIER)
3277 (void)token.v.symbol;
3279 } else if (symbol == sym_dllimport) {
3281 DET_MOD(dllimport, DM_DLLIMPORT);
3282 } else if (symbol == sym_dllexport) {
3284 DET_MOD(dllexport, DM_DLLEXPORT);
3285 } else if (symbol == sym_thread) {
3287 DET_MOD(thread, DM_THREAD);
3288 } else if (symbol == sym_naked) {
3290 DET_MOD(naked, DM_NAKED);
3291 } else if (symbol == sym_noinline) {
3293 DET_MOD(noinline, DM_NOINLINE);
3294 } else if (symbol == sym_noreturn) {
3296 DET_MOD(noreturn, DM_NORETURN);
3297 } else if (symbol == sym_nothrow) {
3299 DET_MOD(nothrow, DM_NOTHROW);
3300 } else if (symbol == sym_novtable) {
3302 DET_MOD(novtable, DM_NOVTABLE);
3303 } else if (symbol == sym_property) {
3307 bool is_get = false;
3308 if (token.type != T_IDENTIFIER)
3310 if (token.v.symbol == sym_get) {
3312 } else if (token.v.symbol == sym_put) {
3314 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3319 if (token.type != T_IDENTIFIER)
3322 if (specifiers->get_property_sym != NULL) {
3323 errorf(HERE, "get property name already specified");
3325 specifiers->get_property_sym = token.v.symbol;
3328 if (specifiers->put_property_sym != NULL) {
3329 errorf(HERE, "put property name already specified");
3331 specifiers->put_property_sym = token.v.symbol;
3335 if (token.type == ',') {
3342 } else if (symbol == sym_selectany) {
3344 DET_MOD(selectany, DM_SELECTANY);
3345 } else if (symbol == sym_uuid) {
3348 if (token.type != T_STRING_LITERAL)
3352 } else if (symbol == sym_deprecated) {
3354 if (specifiers->deprecated != 0 && warning.other)
3355 warningf(HERE, "deprecated used more than once");
3356 specifiers->deprecated = 1;
3357 if (token.type == '(') {
3359 if (token.type == T_STRING_LITERAL) {
3360 specifiers->deprecated_string = token.v.string.begin;
3363 errorf(HERE, "string literal expected");
3367 } else if (symbol == sym_noalias) {
3369 DET_MOD(noalias, DM_NOALIAS);
3372 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3374 if (token.type == '(')
3378 if (token.type == ',')
3385 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3387 declaration_t *const decl = allocate_declaration_zero();
3388 decl->source_position = *HERE;
3389 decl->declared_storage_class = storage_class;
3390 decl->storage_class =
3391 storage_class != STORAGE_CLASS_NONE || scope == file_scope ?
3392 storage_class : STORAGE_CLASS_AUTO;
3393 decl->symbol = symbol;
3394 decl->implicit = true;
3395 record_declaration(decl, false);
3400 * Finish the construction of a struct type by calculating
3401 * its size, offsets, alignment.
3403 static void finish_struct_type(compound_type_t *type) {
3404 if (type->declaration == NULL)
3406 declaration_t *struct_decl = type->declaration;
3407 if (! struct_decl->init.complete)
3412 il_alignment_t alignment = 1;
3413 bool need_pad = false;
3415 declaration_t *entry = struct_decl->scope.declarations;
3416 for (; entry != NULL; entry = entry->next) {
3417 if (entry->namespc != NAMESPACE_NORMAL)
3420 type_t *m_type = skip_typeref(entry->type);
3421 if (! is_type_valid(m_type)) {
3422 /* simply ignore errors here */
3425 il_alignment_t m_alignment = m_type->base.alignment;
3426 if (m_alignment > alignment)
3427 alignment = m_alignment;
3429 offset = (size + m_alignment - 1) & -m_alignment;
3433 entry->offset = offset;
3434 size = offset + m_type->base.size;
3436 if (type->base.alignment != 0) {
3437 alignment = type->base.alignment;
3440 offset = (size + alignment - 1) & -alignment;
3444 if (warning.padded && need_pad) {
3445 warningf(&struct_decl->source_position,
3446 "'%#T' needs padding", type, struct_decl->symbol);
3448 if (warning.packed && !need_pad) {
3449 warningf(&struct_decl->source_position,
3450 "superfluous packed attribute on '%#T'",
3451 type, struct_decl->symbol);
3454 type->base.size = offset;
3455 type->base.alignment = alignment;
3459 * Finish the construction of an union type by calculating
3460 * its size and alignment.
3462 static void finish_union_type(compound_type_t *type) {
3463 if (type->declaration == NULL)
3465 declaration_t *union_decl = type->declaration;
3466 if (! union_decl->init.complete)
3470 il_alignment_t alignment = 1;
3472 declaration_t *entry = union_decl->scope.declarations;
3473 for (; entry != NULL; entry = entry->next) {
3474 if (entry->namespc != NAMESPACE_NORMAL)
3477 type_t *m_type = skip_typeref(entry->type);
3478 if (! is_type_valid(m_type))
3482 if (m_type->base.size > size)
3483 size = m_type->base.size;
3484 if (m_type->base.alignment > alignment)
3485 alignment = m_type->base.alignment;
3487 if (type->base.alignment != 0) {
3488 alignment = type->base.alignment;
3490 size = (size + alignment - 1) & -alignment;
3491 type->base.size = size;
3492 type->base.alignment = alignment;
3495 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3497 type_t *type = NULL;
3498 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3499 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3500 unsigned type_specifiers = 0;
3501 bool newtype = false;
3502 bool saw_error = false;
3503 bool old_gcc_extension = in_gcc_extension;
3505 specifiers->source_position = token.source_position;
3508 specifiers->modifiers
3509 |= parse_attributes(&specifiers->gnu_attributes);
3510 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3511 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3513 switch (token.type) {
3516 #define MATCH_STORAGE_CLASS(token, class) \
3518 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3519 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3521 specifiers->declared_storage_class = class; \
3525 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3526 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3527 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3528 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3529 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3534 add_anchor_token(')');
3535 parse_microsoft_extended_decl_modifier(specifiers);
3536 rem_anchor_token(')');
3541 switch (specifiers->declared_storage_class) {
3542 case STORAGE_CLASS_NONE:
3543 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3546 case STORAGE_CLASS_EXTERN:
3547 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3550 case STORAGE_CLASS_STATIC:
3551 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3555 errorf(HERE, "multiple storage classes in declaration specifiers");
3561 /* type qualifiers */
3562 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3564 qualifiers |= qualifier; \
3568 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3569 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3570 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3571 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3572 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3573 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3574 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3575 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3577 case T___extension__:
3579 in_gcc_extension = true;
3582 /* type specifiers */
3583 #define MATCH_SPECIFIER(token, specifier, name) \
3586 if (type_specifiers & specifier) { \
3587 errorf(HERE, "multiple " name " type specifiers given"); \
3589 type_specifiers |= specifier; \
3593 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3594 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3595 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3596 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3597 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3598 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3599 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3600 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3601 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3602 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3603 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3604 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3605 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3606 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3607 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3608 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3610 case T__forceinline:
3611 /* only in microsoft mode */
3612 specifiers->modifiers |= DM_FORCEINLINE;
3617 specifiers->is_inline = true;
3622 if (type_specifiers & SPECIFIER_LONG_LONG) {
3623 errorf(HERE, "multiple type specifiers given");
3624 } else if (type_specifiers & SPECIFIER_LONG) {
3625 type_specifiers |= SPECIFIER_LONG_LONG;
3627 type_specifiers |= SPECIFIER_LONG;
3632 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3634 type->compound.declaration = parse_compound_type_specifier(true);
3635 finish_struct_type(&type->compound);
3639 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3640 type->compound.declaration = parse_compound_type_specifier(false);
3641 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3642 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3643 finish_union_type(&type->compound);
3647 type = parse_enum_specifier();
3650 type = parse_typeof();
3652 case T___builtin_va_list:
3653 type = duplicate_type(type_valist);
3657 case T_IDENTIFIER: {
3658 /* only parse identifier if we haven't found a type yet */
3659 if (type != NULL || type_specifiers != 0) {
3660 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3661 * declaration, so it doesn't generate errors about expecting '(' or
3663 switch (look_ahead(1)->type) {
3670 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3673 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3678 goto finish_specifiers;
3682 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3683 if (typedef_type == NULL) {
3684 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3685 * declaration, so it doesn't generate 'implicit int' followed by more
3686 * errors later on. */
3687 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3692 errorf(HERE, "%K does not name a type", &token);
3694 declaration_t *const decl =
3695 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3697 type = allocate_type_zero(TYPE_TYPEDEF);
3698 type->typedeft.declaration = decl;
3702 if (la1_type == '*')
3703 goto finish_specifiers;
3708 goto finish_specifiers;
3713 type = typedef_type;
3717 /* function specifier */
3719 goto finish_specifiers;
3724 in_gcc_extension = old_gcc_extension;
3726 if (type == NULL || (saw_error && type_specifiers != 0)) {
3727 atomic_type_kind_t atomic_type;
3729 /* match valid basic types */
3730 switch(type_specifiers) {
3731 case SPECIFIER_VOID:
3732 atomic_type = ATOMIC_TYPE_VOID;
3734 case SPECIFIER_CHAR:
3735 atomic_type = ATOMIC_TYPE_CHAR;
3737 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3738 atomic_type = ATOMIC_TYPE_SCHAR;
3740 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3741 atomic_type = ATOMIC_TYPE_UCHAR;
3743 case SPECIFIER_SHORT:
3744 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3745 case SPECIFIER_SHORT | SPECIFIER_INT:
3746 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3747 atomic_type = ATOMIC_TYPE_SHORT;
3749 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3750 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3751 atomic_type = ATOMIC_TYPE_USHORT;
3754 case SPECIFIER_SIGNED:
3755 case SPECIFIER_SIGNED | SPECIFIER_INT:
3756 atomic_type = ATOMIC_TYPE_INT;
3758 case SPECIFIER_UNSIGNED:
3759 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3760 atomic_type = ATOMIC_TYPE_UINT;
3762 case SPECIFIER_LONG:
3763 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3764 case SPECIFIER_LONG | SPECIFIER_INT:
3765 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3766 atomic_type = ATOMIC_TYPE_LONG;
3768 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3769 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3770 atomic_type = ATOMIC_TYPE_ULONG;
3773 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3774 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3775 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3776 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3778 atomic_type = ATOMIC_TYPE_LONGLONG;
3779 goto warn_about_long_long;
3781 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3782 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3784 atomic_type = ATOMIC_TYPE_ULONGLONG;
3785 warn_about_long_long:
3786 if (warning.long_long) {
3787 warningf(&specifiers->source_position,
3788 "ISO C90 does not support 'long long'");
3792 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3793 atomic_type = unsigned_int8_type_kind;
3796 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3797 atomic_type = unsigned_int16_type_kind;
3800 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3801 atomic_type = unsigned_int32_type_kind;
3804 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3805 atomic_type = unsigned_int64_type_kind;
3808 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3809 atomic_type = unsigned_int128_type_kind;
3812 case SPECIFIER_INT8:
3813 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3814 atomic_type = int8_type_kind;
3817 case SPECIFIER_INT16:
3818 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3819 atomic_type = int16_type_kind;
3822 case SPECIFIER_INT32:
3823 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3824 atomic_type = int32_type_kind;
3827 case SPECIFIER_INT64:
3828 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3829 atomic_type = int64_type_kind;
3832 case SPECIFIER_INT128:
3833 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3834 atomic_type = int128_type_kind;
3837 case SPECIFIER_FLOAT:
3838 atomic_type = ATOMIC_TYPE_FLOAT;
3840 case SPECIFIER_DOUBLE:
3841 atomic_type = ATOMIC_TYPE_DOUBLE;
3843 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3844 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3846 case SPECIFIER_BOOL:
3847 atomic_type = ATOMIC_TYPE_BOOL;
3849 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3850 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3851 atomic_type = ATOMIC_TYPE_FLOAT;
3853 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3854 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3855 atomic_type = ATOMIC_TYPE_DOUBLE;
3857 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3858 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3859 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3862 /* invalid specifier combination, give an error message */
3863 if (type_specifiers == 0) {
3868 if (warning.implicit_int) {
3869 warningf(HERE, "no type specifiers in declaration, using 'int'");
3871 atomic_type = ATOMIC_TYPE_INT;
3874 errorf(HERE, "no type specifiers given in declaration");
3876 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3877 (type_specifiers & SPECIFIER_UNSIGNED)) {
3878 errorf(HERE, "signed and unsigned specifiers given");
3879 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3880 errorf(HERE, "only integer types can be signed or unsigned");
3882 errorf(HERE, "multiple datatypes in declaration");
3887 if (type_specifiers & SPECIFIER_COMPLEX) {
3888 type = allocate_type_zero(TYPE_COMPLEX);
3889 type->complex.akind = atomic_type;
3890 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3891 type = allocate_type_zero(TYPE_IMAGINARY);
3892 type->imaginary.akind = atomic_type;
3894 type = allocate_type_zero(TYPE_ATOMIC);
3895 type->atomic.akind = atomic_type;
3898 } else if (type_specifiers != 0) {
3899 errorf(HERE, "multiple datatypes in declaration");
3902 /* FIXME: check type qualifiers here */
3904 type->base.qualifiers = qualifiers;
3905 type->base.modifiers = modifiers;
3907 type_t *result = typehash_insert(type);
3908 if (newtype && result != type) {
3912 specifiers->type = result;
3916 specifiers->type = type_error_type;
3920 static type_qualifiers_t parse_type_qualifiers(void)
3922 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3925 switch(token.type) {
3926 /* type qualifiers */
3927 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3928 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3929 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3930 /* microsoft extended type modifiers */
3931 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3932 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3933 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3934 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3935 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3944 * Parses an K&R identifier list and return a list of declarations.
3946 * @param last points to the last declaration in the list
3947 * @return the list of declarations
3949 static declaration_t *parse_identifier_list(declaration_t **last)
3951 declaration_t *declarations = NULL;
3952 declaration_t *last_declaration = NULL;
3954 declaration_t *const declaration = allocate_declaration_zero();
3955 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3956 declaration->source_position = token.source_position;
3957 declaration->symbol = token.v.symbol;
3960 if (last_declaration != NULL) {
3961 last_declaration->next = declaration;
3963 declarations = declaration;
3965 last_declaration = declaration;
3967 if (token.type != ',') {
3971 } while (token.type == T_IDENTIFIER);
3973 *last = last_declaration;
3974 return declarations;
3977 static type_t *automatic_type_conversion(type_t *orig_type);
3979 static void semantic_parameter(declaration_t *declaration)
3981 /* TODO: improve error messages */
3982 source_position_t const* const pos = &declaration->source_position;
3984 switch (declaration->declared_storage_class) {
3985 case STORAGE_CLASS_TYPEDEF:
3986 errorf(pos, "typedef not allowed in parameter list");
3989 /* Allowed storage classes */
3990 case STORAGE_CLASS_NONE:
3991 case STORAGE_CLASS_REGISTER:
3995 errorf(pos, "parameter may only have none or register storage class");
3999 type_t *const orig_type = declaration->type;
4000 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
4001 * sugar. Turn it into a pointer.
4002 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4003 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4005 type_t *const type = automatic_type_conversion(orig_type);
4006 declaration->type = type;
4008 if (is_type_incomplete(skip_typeref(type))) {
4009 errorf(pos, "parameter '%#T' is of incomplete type",
4010 orig_type, declaration->symbol);
4014 static declaration_t *parse_parameter(void)
4016 declaration_specifiers_t specifiers;
4017 memset(&specifiers, 0, sizeof(specifiers));
4019 parse_declaration_specifiers(&specifiers);
4021 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
4027 * Parses a function type parameter list and return a list of declarations.
4029 * @param last point to the last element of the list
4030 * @return the parameter list
4032 static declaration_t *parse_parameters(function_type_t *type, declaration_t **last)
4034 declaration_t *declarations = NULL;
4037 add_anchor_token(')');
4038 int saved_comma_state = save_and_reset_anchor_state(',');
4040 if (token.type == T_IDENTIFIER &&
4041 !is_typedef_symbol(token.v.symbol)) {
4042 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4043 if (la1_type == ',' || la1_type == ')') {
4044 type->kr_style_parameters = true;
4045 declarations = parse_identifier_list(last);
4046 goto parameters_finished;
4050 if (token.type == ')') {
4051 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4052 if (!(c_mode & _CXX))
4053 type->unspecified_parameters = 1;
4054 goto parameters_finished;
4057 declaration_t *declaration;
4058 declaration_t *last_declaration = NULL;
4059 function_parameter_t *parameter;
4060 function_parameter_t *last_parameter = NULL;
4063 switch(token.type) {
4067 goto parameters_finished;
4070 case T___extension__:
4072 declaration = parse_parameter();
4074 /* func(void) is not a parameter */
4075 if (last_parameter == NULL
4076 && token.type == ')'
4077 && declaration->symbol == NULL
4078 && skip_typeref(declaration->type) == type_void) {
4079 goto parameters_finished;
4081 semantic_parameter(declaration);
4083 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4084 memset(parameter, 0, sizeof(parameter[0]));
4085 parameter->type = declaration->type;
4087 if (last_parameter != NULL) {
4088 last_declaration->next = declaration;
4089 last_parameter->next = parameter;
4091 type->parameters = parameter;
4092 declarations = declaration;
4094 last_parameter = parameter;
4095 last_declaration = declaration;
4099 goto parameters_finished;
4101 if (token.type != ',') {
4102 goto parameters_finished;
4108 parameters_finished:
4109 rem_anchor_token(')');
4112 restore_anchor_state(',', saved_comma_state);
4113 *last = last_declaration;
4114 return declarations;
4117 restore_anchor_state(',', saved_comma_state);
4122 typedef enum construct_type_kind_t {
4127 } construct_type_kind_t;
4129 typedef struct construct_type_t construct_type_t;
4130 struct construct_type_t {
4131 construct_type_kind_t kind;
4132 construct_type_t *next;
4135 typedef struct parsed_pointer_t parsed_pointer_t;
4136 struct parsed_pointer_t {
4137 construct_type_t construct_type;
4138 type_qualifiers_t type_qualifiers;
4141 typedef struct construct_function_type_t construct_function_type_t;
4142 struct construct_function_type_t {
4143 construct_type_t construct_type;
4144 type_t *function_type;
4147 typedef struct parsed_array_t parsed_array_t;
4148 struct parsed_array_t {
4149 construct_type_t construct_type;
4150 type_qualifiers_t type_qualifiers;
4156 typedef struct construct_base_type_t construct_base_type_t;
4157 struct construct_base_type_t {
4158 construct_type_t construct_type;
4162 static construct_type_t *parse_pointer_declarator(void)
4166 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4167 memset(pointer, 0, sizeof(pointer[0]));
4168 pointer->construct_type.kind = CONSTRUCT_POINTER;
4169 pointer->type_qualifiers = parse_type_qualifiers();
4171 return (construct_type_t*) pointer;
4174 static construct_type_t *parse_array_declarator(void)
4177 add_anchor_token(']');
4179 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4180 memset(array, 0, sizeof(array[0]));
4181 array->construct_type.kind = CONSTRUCT_ARRAY;
4183 if (token.type == T_static) {
4184 array->is_static = true;
4188 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4189 if (type_qualifiers != 0) {
4190 if (token.type == T_static) {
4191 array->is_static = true;
4195 array->type_qualifiers = type_qualifiers;
4197 if (token.type == '*' && look_ahead(1)->type == ']') {
4198 array->is_variable = true;
4200 } else if (token.type != ']') {
4201 array->size = parse_assignment_expression();
4204 rem_anchor_token(']');
4208 return (construct_type_t*) array;
4211 static construct_type_t *parse_function_declarator(declaration_t *declaration)
4214 if (declaration != NULL) {
4215 type = allocate_type_zero(TYPE_FUNCTION);
4217 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
4219 if (mask & (mask-1)) {
4220 const char *first = NULL, *second = NULL;
4222 /* more than one calling convention set */
4223 if (declaration->modifiers & DM_CDECL) {
4224 if (first == NULL) first = "cdecl";
4225 else if (second == NULL) second = "cdecl";
4227 if (declaration->modifiers & DM_STDCALL) {
4228 if (first == NULL) first = "stdcall";
4229 else if (second == NULL) second = "stdcall";
4231 if (declaration->modifiers & DM_FASTCALL) {
4232 if (first == NULL) first = "fastcall";
4233 else if (second == NULL) second = "fastcall";
4235 if (declaration->modifiers & DM_THISCALL) {
4236 if (first == NULL) first = "thiscall";
4237 else if (second == NULL) second = "thiscall";
4239 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
4242 if (declaration->modifiers & DM_CDECL)
4243 type->function.calling_convention = CC_CDECL;
4244 else if (declaration->modifiers & DM_STDCALL)
4245 type->function.calling_convention = CC_STDCALL;
4246 else if (declaration->modifiers & DM_FASTCALL)
4247 type->function.calling_convention = CC_FASTCALL;
4248 else if (declaration->modifiers & DM_THISCALL)
4249 type->function.calling_convention = CC_THISCALL;
4251 type = allocate_type_zero(TYPE_FUNCTION);
4254 declaration_t *last;
4255 declaration_t *parameters = parse_parameters(&type->function, &last);
4256 if (declaration != NULL) {
4257 declaration->scope.declarations = parameters;
4258 declaration->scope.last_declaration = last;
4261 construct_function_type_t *construct_function_type =
4262 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4263 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4264 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4265 construct_function_type->function_type = type;
4267 return &construct_function_type->construct_type;
4270 static void fix_declaration_type(declaration_t *declaration)
4272 decl_modifiers_t declaration_modifiers = declaration->modifiers;
4273 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
4275 if (declaration_modifiers & DM_TRANSPARENT_UNION)
4276 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4278 if (declaration->type->base.modifiers == type_modifiers)
4281 type_t *copy = duplicate_type(declaration->type);
4282 copy->base.modifiers = type_modifiers;
4284 type_t *result = typehash_insert(copy);
4285 if (result != copy) {
4286 obstack_free(type_obst, copy);
4289 declaration->type = result;
4292 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
4293 bool may_be_abstract)
4295 /* construct a single linked list of construct_type_t's which describe
4296 * how to construct the final declarator type */
4297 construct_type_t *first = NULL;
4298 construct_type_t *last = NULL;
4299 gnu_attribute_t *attributes = NULL;
4301 decl_modifiers_t modifiers = parse_attributes(&attributes);
4304 while (token.type == '*') {
4305 construct_type_t *type = parse_pointer_declarator();
4315 /* TODO: find out if this is correct */
4316 modifiers |= parse_attributes(&attributes);
4319 if (declaration != NULL)
4320 declaration->modifiers |= modifiers;
4322 construct_type_t *inner_types = NULL;
4324 switch(token.type) {
4326 if (declaration == NULL) {
4327 errorf(HERE, "no identifier expected in typename");
4329 declaration->symbol = token.v.symbol;
4330 declaration->source_position = token.source_position;
4336 add_anchor_token(')');
4337 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4338 if (inner_types != NULL) {
4339 /* All later declarators only modify the return type, not declaration */
4342 rem_anchor_token(')');
4346 if (may_be_abstract)
4348 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4353 construct_type_t *p = last;
4356 construct_type_t *type;
4357 switch(token.type) {
4359 type = parse_function_declarator(declaration);
4362 type = parse_array_declarator();
4365 goto declarator_finished;
4368 /* insert in the middle of the list (behind p) */
4370 type->next = p->next;
4381 declarator_finished:
4382 /* append inner_types at the end of the list, we don't to set last anymore
4383 * as it's not needed anymore */
4385 assert(first == NULL);
4386 first = inner_types;
4388 last->next = inner_types;
4396 static void parse_declaration_attributes(declaration_t *declaration)
4398 gnu_attribute_t *attributes = NULL;
4399 decl_modifiers_t modifiers = parse_attributes(&attributes);
4401 if (declaration == NULL)
4404 declaration->modifiers |= modifiers;
4405 /* check if we have these stupid mode attributes... */
4406 type_t *old_type = declaration->type;
4407 if (old_type == NULL)
4410 gnu_attribute_t *attribute = attributes;
4411 for ( ; attribute != NULL; attribute = attribute->next) {
4412 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4415 atomic_type_kind_t akind = attribute->u.akind;
4416 if (!is_type_signed(old_type)) {
4418 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4419 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4420 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4421 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4423 panic("invalid akind in mode attribute");
4427 = make_atomic_type(akind, old_type->base.qualifiers);
4431 static type_t *construct_declarator_type(construct_type_t *construct_list,
4434 construct_type_t *iter = construct_list;
4435 for( ; iter != NULL; iter = iter->next) {
4436 switch(iter->kind) {
4437 case CONSTRUCT_INVALID:
4438 internal_errorf(HERE, "invalid type construction found");
4439 case CONSTRUCT_FUNCTION: {
4440 construct_function_type_t *construct_function_type
4441 = (construct_function_type_t*) iter;
4443 type_t *function_type = construct_function_type->function_type;
4445 function_type->function.return_type = type;
4447 type_t *skipped_return_type = skip_typeref(type);
4449 if (is_type_function(skipped_return_type)) {
4450 errorf(HERE, "function returning function is not allowed");
4451 } else if (is_type_array(skipped_return_type)) {
4452 errorf(HERE, "function returning array is not allowed");
4454 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4456 "type qualifiers in return type of function type are meaningless");
4460 type = function_type;
4464 case CONSTRUCT_POINTER: {
4465 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4466 type = make_pointer_type(type, parsed_pointer->type_qualifiers);
4470 case CONSTRUCT_ARRAY: {
4471 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4472 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4474 expression_t *size_expression = parsed_array->size;
4475 if (size_expression != NULL) {
4477 = create_implicit_cast(size_expression, type_size_t);
4480 array_type->base.qualifiers = parsed_array->type_qualifiers;
4481 array_type->array.element_type = type;
4482 array_type->array.is_static = parsed_array->is_static;
4483 array_type->array.is_variable = parsed_array->is_variable;
4484 array_type->array.size_expression = size_expression;
4486 if (size_expression != NULL) {
4487 if (is_constant_expression(size_expression)) {
4488 array_type->array.size_constant = true;
4489 array_type->array.size
4490 = fold_constant(size_expression);
4492 array_type->array.is_vla = true;
4496 type_t *skipped_type = skip_typeref(type);
4498 if (is_type_incomplete(skipped_type)) {
4499 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4500 } else if (is_type_function(skipped_type)) {
4501 errorf(HERE, "array of functions is not allowed");
4508 type_t *hashed_type = typehash_insert(type);
4509 if (hashed_type != type) {
4510 /* the function type was constructed earlier freeing it here will
4511 * destroy other types... */
4512 if (iter->kind != CONSTRUCT_FUNCTION) {
4522 static declaration_t *parse_declarator(
4523 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4525 declaration_t *const declaration = allocate_declaration_zero();
4526 declaration->source_position = specifiers->source_position;
4527 declaration->declared_storage_class = specifiers->declared_storage_class;
4528 declaration->modifiers = specifiers->modifiers;
4529 declaration->deprecated_string = specifiers->deprecated_string;
4530 declaration->get_property_sym = specifiers->get_property_sym;
4531 declaration->put_property_sym = specifiers->put_property_sym;
4532 declaration->is_inline = specifiers->is_inline;
4534 declaration->storage_class = specifiers->declared_storage_class;
4535 if (declaration->storage_class == STORAGE_CLASS_NONE &&
4536 scope != file_scope) {
4537 declaration->storage_class = STORAGE_CLASS_AUTO;
4540 if (specifiers->alignment != 0) {
4541 /* TODO: add checks here */
4542 declaration->alignment = specifiers->alignment;
4545 construct_type_t *construct_type
4546 = parse_inner_declarator(declaration, may_be_abstract);
4547 type_t *const type = specifiers->type;
4548 declaration->type = construct_declarator_type(construct_type, type);
4550 parse_declaration_attributes(declaration);
4552 fix_declaration_type(declaration);
4554 if (construct_type != NULL) {
4555 obstack_free(&temp_obst, construct_type);
4561 static type_t *parse_abstract_declarator(type_t *base_type)
4563 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4565 type_t *result = construct_declarator_type(construct_type, base_type);
4566 if (construct_type != NULL) {
4567 obstack_free(&temp_obst, construct_type);
4573 static declaration_t *append_declaration(declaration_t* const declaration)
4575 if (last_declaration != NULL) {
4576 last_declaration->next = declaration;
4578 scope->declarations = declaration;
4580 last_declaration = declaration;
4585 * Check if the declaration of main is suspicious. main should be a
4586 * function with external linkage, returning int, taking either zero
4587 * arguments, two, or three arguments of appropriate types, ie.
4589 * int main([ int argc, char **argv [, char **env ] ]).
4591 * @param decl the declaration to check
4592 * @param type the function type of the declaration
4594 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4596 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4597 warningf(&decl->source_position,
4598 "'main' is normally a non-static function");
4600 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4601 warningf(&decl->source_position,
4602 "return type of 'main' should be 'int', but is '%T'",
4603 func_type->return_type);
4605 const function_parameter_t *parm = func_type->parameters;
4607 type_t *const first_type = parm->type;
4608 if (!types_compatible(skip_typeref(first_type), type_int)) {
4609 warningf(&decl->source_position,
4610 "first argument of 'main' should be 'int', but is '%T'", first_type);
4614 type_t *const second_type = parm->type;
4615 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4616 warningf(&decl->source_position,
4617 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4621 type_t *const third_type = parm->type;
4622 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4623 warningf(&decl->source_position,
4624 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4628 goto warn_arg_count;
4632 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4638 * Check if a symbol is the equal to "main".
4640 static bool is_sym_main(const symbol_t *const sym)
4642 return strcmp(sym->string, "main") == 0;
4645 static declaration_t *record_declaration(
4646 declaration_t *const declaration,
4647 const bool is_definition)
4649 const symbol_t *const symbol = declaration->symbol;
4650 const namespace_t namespc = (namespace_t)declaration->namespc;
4652 assert(symbol != NULL);
4653 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4655 type_t *const orig_type = declaration->type;
4656 type_t *const type = skip_typeref(orig_type);
4657 if (is_type_function(type) &&
4658 type->function.unspecified_parameters &&
4659 warning.strict_prototypes &&
4660 previous_declaration == NULL) {
4661 warningf(&declaration->source_position,
4662 "function declaration '%#T' is not a prototype",
4666 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4667 check_type_of_main(declaration, &type->function);
4670 if (warning.nested_externs &&
4671 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4672 scope != file_scope) {
4673 warningf(&declaration->source_position,
4674 "nested extern declaration of '%#T'", declaration->type, symbol);
4677 assert(declaration != previous_declaration);
4678 if (previous_declaration != NULL &&
4679 previous_declaration->parent_scope == ¤t_function->scope &&
4680 scope->depth == previous_declaration->parent_scope->depth + 1) {
4681 errorf(&declaration->source_position,
4682 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4683 orig_type, symbol, previous_declaration->type, symbol,
4684 &previous_declaration->source_position);
4687 if (previous_declaration != NULL &&
4688 previous_declaration->parent_scope == scope) {
4689 /* can happen for K&R style declarations */
4690 if (previous_declaration->type == NULL) {
4691 previous_declaration->type = declaration->type;
4694 const type_t *prev_type = skip_typeref(previous_declaration->type);
4695 if (!types_compatible(type, prev_type)) {
4696 errorf(&declaration->source_position,
4697 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4698 orig_type, symbol, previous_declaration->type, symbol,
4699 &previous_declaration->source_position);
4701 unsigned old_storage_class = previous_declaration->storage_class;
4702 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4703 errorf(&declaration->source_position,
4704 "redeclaration of enum entry '%Y' (declared %P)",
4705 symbol, &previous_declaration->source_position);
4706 return previous_declaration;
4709 if (warning.redundant_decls &&
4711 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4712 !(previous_declaration->modifiers & DM_USED) &&
4713 !previous_declaration->used) {
4714 warningf(&previous_declaration->source_position,
4715 "unnecessary static forward declaration for '%#T'",
4716 previous_declaration->type, symbol);
4719 unsigned new_storage_class = declaration->storage_class;
4721 if (is_type_incomplete(prev_type)) {
4722 previous_declaration->type = type;
4726 /* pretend no storage class means extern for function
4727 * declarations (except if the previous declaration is neither
4728 * none nor extern) */
4729 if (is_type_function(type)) {
4730 if (prev_type->function.unspecified_parameters) {
4731 previous_declaration->type = type;
4735 switch (old_storage_class) {
4736 case STORAGE_CLASS_NONE:
4737 old_storage_class = STORAGE_CLASS_EXTERN;
4740 case STORAGE_CLASS_EXTERN:
4741 if (is_definition) {
4742 if (warning.missing_prototypes &&
4743 prev_type->function.unspecified_parameters &&
4744 !is_sym_main(symbol)) {
4745 warningf(&declaration->source_position,
4746 "no previous prototype for '%#T'",
4749 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4750 new_storage_class = STORAGE_CLASS_EXTERN;
4759 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4760 new_storage_class == STORAGE_CLASS_EXTERN) {
4761 warn_redundant_declaration:
4762 if (!is_definition &&
4763 warning.redundant_decls &&
4764 is_type_valid(prev_type) &&
4765 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4766 warningf(&declaration->source_position,
4767 "redundant declaration for '%Y' (declared %P)",
4768 symbol, &previous_declaration->source_position);
4770 } else if (current_function == NULL) {
4771 if (old_storage_class != STORAGE_CLASS_STATIC &&
4772 new_storage_class == STORAGE_CLASS_STATIC) {
4773 errorf(&declaration->source_position,
4774 "static declaration of '%Y' follows non-static declaration (declared %P)",
4775 symbol, &previous_declaration->source_position);
4776 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4777 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4778 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4780 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4782 goto error_redeclaration;
4783 goto warn_redundant_declaration;
4785 } else if (is_type_valid(prev_type)) {
4786 if (old_storage_class == new_storage_class) {
4787 error_redeclaration:
4788 errorf(&declaration->source_position,
4789 "redeclaration of '%Y' (declared %P)",
4790 symbol, &previous_declaration->source_position);
4792 errorf(&declaration->source_position,
4793 "redeclaration of '%Y' with different linkage (declared %P)",
4794 symbol, &previous_declaration->source_position);
4799 previous_declaration->modifiers |= declaration->modifiers;
4800 previous_declaration->is_inline |= declaration->is_inline;
4801 return previous_declaration;
4802 } else if (is_type_function(type)) {
4803 if (is_definition &&
4804 declaration->storage_class != STORAGE_CLASS_STATIC) {
4805 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4806 warningf(&declaration->source_position,
4807 "no previous prototype for '%#T'", orig_type, symbol);
4808 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4809 warningf(&declaration->source_position,
4810 "no previous declaration for '%#T'", orig_type,
4815 if (warning.missing_declarations &&
4816 scope == file_scope && (
4817 declaration->storage_class == STORAGE_CLASS_NONE ||
4818 declaration->storage_class == STORAGE_CLASS_THREAD
4820 warningf(&declaration->source_position,
4821 "no previous declaration for '%#T'", orig_type, symbol);
4825 assert(declaration->parent_scope == NULL);
4826 assert(scope != NULL);
4828 declaration->parent_scope = scope;
4830 environment_push(declaration);
4831 return append_declaration(declaration);
4834 static void parser_error_multiple_definition(declaration_t *declaration,
4835 const source_position_t *source_position)
4837 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4838 declaration->symbol, &declaration->source_position);
4841 static bool is_declaration_specifier(const token_t *token,
4842 bool only_specifiers_qualifiers)
4844 switch (token->type) {
4849 return is_typedef_symbol(token->v.symbol);
4851 case T___extension__:
4853 return !only_specifiers_qualifiers;
4860 static void parse_init_declarator_rest(declaration_t *declaration)
4864 type_t *orig_type = declaration->type;
4865 type_t *type = skip_typeref(orig_type);
4867 if (declaration->init.initializer != NULL) {
4868 parser_error_multiple_definition(declaration, HERE);
4871 bool must_be_constant = false;
4872 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4873 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
4874 declaration->parent_scope == file_scope) {
4875 must_be_constant = true;
4878 if (is_type_function(type)) {
4879 errorf(&declaration->source_position,
4880 "function '%#T' is initialized like a variable",
4881 orig_type, declaration->symbol);
4882 orig_type = type_error_type;
4885 parse_initializer_env_t env;
4886 env.type = orig_type;
4887 env.must_be_constant = must_be_constant;
4888 env.declaration = current_init_decl = declaration;
4890 initializer_t *initializer = parse_initializer(&env);
4891 current_init_decl = NULL;
4893 if (!is_type_function(type)) {
4894 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4895 * the array type size */
4896 declaration->type = env.type;
4897 declaration->init.initializer = initializer;
4901 /* parse rest of a declaration without any declarator */
4902 static void parse_anonymous_declaration_rest(
4903 const declaration_specifiers_t *specifiers)
4907 if (warning.other) {
4908 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4909 warningf(&specifiers->source_position,
4910 "useless storage class in empty declaration");
4913 type_t *type = specifiers->type;
4914 switch (type->kind) {
4915 case TYPE_COMPOUND_STRUCT:
4916 case TYPE_COMPOUND_UNION: {
4917 if (type->compound.declaration->symbol == NULL) {
4918 warningf(&specifiers->source_position,
4919 "unnamed struct/union that defines no instances");
4928 warningf(&specifiers->source_position, "empty declaration");
4933 #ifdef RECORD_EMPTY_DECLARATIONS
4934 declaration_t *const declaration = allocate_declaration_zero();
4935 declaration->type = specifiers->type;
4936 declaration->declared_storage_class = specifiers->declared_storage_class;
4937 declaration->source_position = specifiers->source_position;
4938 declaration->modifiers = specifiers->modifiers;
4939 declaration->storage_class = STORAGE_CLASS_NONE;
4941 append_declaration(declaration);
4945 static void parse_declaration_rest(declaration_t *ndeclaration,
4946 const declaration_specifiers_t *specifiers,
4947 parsed_declaration_func finished_declaration)
4949 add_anchor_token(';');
4950 add_anchor_token(',');
4952 declaration_t *declaration =
4953 finished_declaration(ndeclaration, token.type == '=');
4955 type_t *orig_type = declaration->type;
4956 type_t *type = skip_typeref(orig_type);
4958 if (warning.other &&
4959 type->kind != TYPE_FUNCTION &&
4960 declaration->is_inline &&
4961 is_type_valid(type)) {
4962 warningf(&declaration->source_position,
4963 "variable '%Y' declared 'inline'\n", declaration->symbol);
4966 if (token.type == '=') {
4967 parse_init_declarator_rest(declaration);
4970 if (token.type != ',')
4974 add_anchor_token('=');
4975 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4976 rem_anchor_token('=');
4981 rem_anchor_token(';');
4982 rem_anchor_token(',');
4985 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4987 symbol_t *symbol = declaration->symbol;
4988 if (symbol == NULL) {
4989 errorf(HERE, "anonymous declaration not valid as function parameter");
4992 namespace_t namespc = (namespace_t) declaration->namespc;
4993 if (namespc != NAMESPACE_NORMAL) {
4994 return record_declaration(declaration, false);
4997 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4998 if (previous_declaration == NULL ||
4999 previous_declaration->parent_scope != scope) {
5000 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5005 if (is_definition) {
5006 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
5009 if (previous_declaration->type == NULL) {
5010 previous_declaration->type = declaration->type;
5011 previous_declaration->declared_storage_class = declaration->declared_storage_class;
5012 previous_declaration->storage_class = declaration->storage_class;
5013 previous_declaration->parent_scope = scope;
5014 return previous_declaration;
5016 return record_declaration(declaration, false);
5020 static void parse_declaration(parsed_declaration_func finished_declaration)
5022 declaration_specifiers_t specifiers;
5023 memset(&specifiers, 0, sizeof(specifiers));
5025 add_anchor_token(';');
5026 parse_declaration_specifiers(&specifiers);
5027 rem_anchor_token(';');
5029 if (token.type == ';') {
5030 parse_anonymous_declaration_rest(&specifiers);
5032 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5033 parse_declaration_rest(declaration, &specifiers, finished_declaration);
5037 static type_t *get_default_promoted_type(type_t *orig_type)
5039 type_t *result = orig_type;
5041 type_t *type = skip_typeref(orig_type);
5042 if (is_type_integer(type)) {
5043 result = promote_integer(type);
5044 } else if (type == type_float) {
5045 result = type_double;
5051 static void parse_kr_declaration_list(declaration_t *declaration)
5053 type_t *type = skip_typeref(declaration->type);
5054 if (!is_type_function(type))
5057 if (!type->function.kr_style_parameters)
5060 add_anchor_token('{');
5062 /* push function parameters */
5063 size_t const top = environment_top();
5064 scope_push(&declaration->scope);
5066 declaration_t *parameter = declaration->scope.declarations;
5067 for ( ; parameter != NULL; parameter = parameter->next) {
5068 assert(parameter->parent_scope == NULL);
5069 parameter->parent_scope = scope;
5070 environment_push(parameter);
5073 /* parse declaration list */
5074 while (is_declaration_specifier(&token, false)) {
5075 parse_declaration(finished_kr_declaration);
5078 /* pop function parameters */
5079 assert(scope == &declaration->scope);
5081 environment_pop_to(top);
5083 /* update function type */
5084 type_t *new_type = duplicate_type(type);
5086 function_parameter_t *parameters = NULL;
5087 function_parameter_t *last_parameter = NULL;
5089 declaration_t *parameter_declaration = declaration->scope.declarations;
5090 for( ; parameter_declaration != NULL;
5091 parameter_declaration = parameter_declaration->next) {
5092 type_t *parameter_type = parameter_declaration->type;
5093 if (parameter_type == NULL) {
5095 errorf(HERE, "no type specified for function parameter '%Y'",
5096 parameter_declaration->symbol);
5098 if (warning.implicit_int) {
5099 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5100 parameter_declaration->symbol);
5102 parameter_type = type_int;
5103 parameter_declaration->type = parameter_type;
5107 semantic_parameter(parameter_declaration);
5108 parameter_type = parameter_declaration->type;
5111 * we need the default promoted types for the function type
5113 parameter_type = get_default_promoted_type(parameter_type);
5115 function_parameter_t *function_parameter
5116 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5117 memset(function_parameter, 0, sizeof(function_parameter[0]));
5119 function_parameter->type = parameter_type;
5120 if (last_parameter != NULL) {
5121 last_parameter->next = function_parameter;
5123 parameters = function_parameter;
5125 last_parameter = function_parameter;
5128 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5130 new_type->function.parameters = parameters;
5131 new_type->function.unspecified_parameters = true;
5133 type = typehash_insert(new_type);
5134 if (type != new_type) {
5135 obstack_free(type_obst, new_type);
5138 declaration->type = type;
5140 rem_anchor_token('{');
5143 static bool first_err = true;
5146 * When called with first_err set, prints the name of the current function,
5149 static void print_in_function(void)
5153 diagnosticf("%s: In function '%Y':\n",
5154 current_function->source_position.input_name,
5155 current_function->symbol);
5160 * Check if all labels are defined in the current function.
5161 * Check if all labels are used in the current function.
5163 static void check_labels(void)
5165 for (const goto_statement_t *goto_statement = goto_first;
5166 goto_statement != NULL;
5167 goto_statement = goto_statement->next) {
5168 /* skip computed gotos */
5169 if (goto_statement->expression != NULL)
5172 declaration_t *label = goto_statement->label;
5175 if (label->source_position.input_name == NULL) {
5176 print_in_function();
5177 errorf(&goto_statement->base.source_position,
5178 "label '%Y' used but not defined", label->symbol);
5181 goto_first = goto_last = NULL;
5183 if (warning.unused_label) {
5184 for (const label_statement_t *label_statement = label_first;
5185 label_statement != NULL;
5186 label_statement = label_statement->next) {
5187 const declaration_t *label = label_statement->label;
5189 if (! label->used) {
5190 print_in_function();
5191 warningf(&label_statement->base.source_position,
5192 "label '%Y' defined but not used", label->symbol);
5196 label_first = label_last = NULL;
5199 static void warn_unused_decl(declaration_t *decl, declaration_t *end, char const *const what)
5201 for (; decl != NULL; decl = decl->next) {
5206 print_in_function();
5207 warningf(&decl->source_position, "%s '%Y' is unused", what, decl->symbol);
5208 } else if (!decl->read) {
5209 print_in_function();
5210 warningf(&decl->source_position, "%s '%Y' is never read", what, decl->symbol);
5218 static void check_unused_variables(statement_t *const stmt, void *const env)
5222 switch (stmt->kind) {
5223 case STATEMENT_DECLARATION: {
5224 declaration_statement_t const *const decls = &stmt->declaration;
5225 warn_unused_decl(decls->declarations_begin, decls->declarations_end, "variable");
5230 warn_unused_decl(stmt->fors.scope.declarations, NULL, "variable");
5239 * Check declarations of current_function for unused entities.
5241 static void check_declarations(void)
5243 if (warning.unused_parameter) {
5244 const scope_t *scope = ¤t_function->scope;
5246 /* do not issue unused warnings for main */
5247 if (!is_sym_main(current_function->symbol)) {
5248 warn_unused_decl(scope->declarations, NULL, "parameter");
5251 if (warning.unused_variable) {
5252 walk_statements(current_function->init.statement, check_unused_variables, NULL);
5256 static int determine_truth(expression_t const* const cond)
5259 !is_constant_expression(cond) ? 0 :
5260 fold_constant(cond) != 0 ? 1 :
5264 static bool expression_returns(expression_t const *const expr)
5266 switch (expr->kind) {
5268 expression_t const *const func = expr->call.function;
5269 if (func->kind == EXPR_REFERENCE) {
5270 declaration_t const *const decl = func->reference.declaration;
5271 if (decl != NULL && decl->modifiers & DM_NORETURN)
5275 if (!expression_returns(func))
5278 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5279 if (!expression_returns(arg->expression))
5286 case EXPR_REFERENCE:
5288 case EXPR_CHARACTER_CONSTANT:
5289 case EXPR_WIDE_CHARACTER_CONSTANT:
5290 case EXPR_STRING_LITERAL:
5291 case EXPR_WIDE_STRING_LITERAL:
5292 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5293 case EXPR_LABEL_ADDRESS:
5294 case EXPR_CLASSIFY_TYPE:
5295 case EXPR_SIZEOF: // TODO handle obscure VLA case
5298 case EXPR_BUILTIN_SYMBOL:
5299 case EXPR_BUILTIN_CONSTANT_P:
5300 case EXPR_BUILTIN_PREFETCH:
5302 case EXPR_STATEMENT: // TODO implement
5305 case EXPR_CONDITIONAL:
5306 // TODO handle constant expression
5308 expression_returns(expr->conditional.condition) && (
5309 expression_returns(expr->conditional.true_expression) ||
5310 expression_returns(expr->conditional.false_expression)
5314 return expression_returns(expr->select.compound);
5316 case EXPR_ARRAY_ACCESS:
5318 expression_returns(expr->array_access.array_ref) &&
5319 expression_returns(expr->array_access.index);
5322 return expression_returns(expr->va_starte.ap);
5325 return expression_returns(expr->va_arge.ap);
5327 EXPR_UNARY_CASES_MANDATORY
5328 return expression_returns(expr->unary.value);
5330 case EXPR_UNARY_THROW:
5334 // TODO handle constant lhs of && and ||
5336 expression_returns(expr->binary.left) &&
5337 expression_returns(expr->binary.right);
5344 panic("unhandled expression");
5347 static bool noreturn_candidate;
5349 static void check_reachable(statement_t *const stmt)
5351 if (stmt->base.reachable)
5353 if (stmt->kind != STATEMENT_DO_WHILE)
5354 stmt->base.reachable = true;
5356 statement_t *last = stmt;
5358 switch (stmt->kind) {
5359 case STATEMENT_INVALID:
5360 case STATEMENT_EMPTY:
5361 case STATEMENT_DECLARATION:
5363 next = stmt->base.next;
5366 case STATEMENT_COMPOUND:
5367 next = stmt->compound.statements;
5370 case STATEMENT_RETURN:
5371 noreturn_candidate = false;
5374 case STATEMENT_IF: {
5375 if_statement_t const* const ifs = &stmt->ifs;
5376 int const val = determine_truth(ifs->condition);
5379 check_reachable(ifs->true_statement);
5384 if (ifs->false_statement != NULL) {
5385 check_reachable(ifs->false_statement);
5389 next = stmt->base.next;
5393 case STATEMENT_SWITCH: {
5394 switch_statement_t const *const switchs = &stmt->switchs;
5395 expression_t const *const expr = switchs->expression;
5397 if (is_constant_expression(expr)) {
5398 long const val = fold_constant(expr);
5399 case_label_statement_t * defaults = NULL;
5400 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5401 if (i->expression == NULL) {
5406 if (i->first_case <= val && val <= i->last_case) {
5407 check_reachable((statement_t*)i);
5412 if (defaults != NULL) {
5413 check_reachable((statement_t*)defaults);
5417 bool has_default = false;
5418 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5419 if (i->expression == NULL)
5422 check_reachable((statement_t*)i);
5429 next = stmt->base.next;
5433 case STATEMENT_EXPRESSION: {
5434 /* Check for noreturn function call */
5435 expression_t const *const expr = stmt->expression.expression;
5436 if (!expression_returns(expr))
5439 next = stmt->base.next;
5443 case STATEMENT_CONTINUE: {
5444 statement_t *parent = stmt;
5446 parent = parent->base.parent;
5447 if (parent == NULL) /* continue not within loop */
5451 switch (parent->kind) {
5452 case STATEMENT_WHILE: goto continue_while;
5453 case STATEMENT_DO_WHILE: goto continue_do_while;
5454 case STATEMENT_FOR: goto continue_for;
5461 case STATEMENT_BREAK: {
5462 statement_t *parent = stmt;
5464 parent = parent->base.parent;
5465 if (parent == NULL) /* break not within loop/switch */
5468 switch (parent->kind) {
5469 case STATEMENT_SWITCH:
5470 case STATEMENT_WHILE:
5471 case STATEMENT_DO_WHILE:
5474 next = parent->base.next;
5475 goto found_break_parent;
5484 case STATEMENT_GOTO:
5485 if (stmt->gotos.expression) {
5486 statement_t *parent = stmt->base.parent;
5487 if (parent == NULL) /* top level goto */
5491 next = stmt->gotos.label->init.statement;
5492 if (next == NULL) /* missing label */
5497 case STATEMENT_LABEL:
5498 next = stmt->label.statement;
5501 case STATEMENT_CASE_LABEL:
5502 next = stmt->case_label.statement;
5505 case STATEMENT_WHILE: {
5506 while_statement_t const *const whiles = &stmt->whiles;
5507 int const val = determine_truth(whiles->condition);
5510 check_reachable(whiles->body);
5515 next = stmt->base.next;
5519 case STATEMENT_DO_WHILE:
5520 next = stmt->do_while.body;
5523 case STATEMENT_FOR: {
5524 for_statement_t *const fors = &stmt->fors;
5526 if (fors->condition_reachable)
5528 fors->condition_reachable = true;
5530 expression_t const *const cond = fors->condition;
5532 cond == NULL ? 1 : determine_truth(cond);
5535 check_reachable(fors->body);
5540 next = stmt->base.next;
5544 case STATEMENT_MS_TRY: {
5545 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5546 check_reachable(ms_try->try_statement);
5547 next = ms_try->final_statement;
5551 case STATEMENT_LEAVE: {
5552 statement_t *parent = stmt;
5554 parent = parent->base.parent;
5555 if (parent == NULL) /* __leave not within __try */
5558 if (parent->kind == STATEMENT_MS_TRY) {
5560 next = parent->ms_try.final_statement;
5568 while (next == NULL) {
5569 next = last->base.parent;
5571 noreturn_candidate = false;
5573 type_t *const type = current_function->type;
5574 assert(is_type_function(type));
5575 type_t *const ret = skip_typeref(type->function.return_type);
5576 if (warning.return_type &&
5577 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5578 is_type_valid(ret) &&
5579 !is_sym_main(current_function->symbol)) {
5580 warningf(&stmt->base.source_position,
5581 "control reaches end of non-void function");
5586 switch (next->kind) {
5587 case STATEMENT_INVALID:
5588 case STATEMENT_EMPTY:
5589 case STATEMENT_DECLARATION:
5590 case STATEMENT_EXPRESSION:
5592 case STATEMENT_RETURN:
5593 case STATEMENT_CONTINUE:
5594 case STATEMENT_BREAK:
5595 case STATEMENT_GOTO:
5596 case STATEMENT_LEAVE:
5597 panic("invalid control flow in function");
5599 case STATEMENT_COMPOUND:
5601 case STATEMENT_SWITCH:
5602 case STATEMENT_LABEL:
5603 case STATEMENT_CASE_LABEL:
5605 next = next->base.next;
5608 case STATEMENT_WHILE: {
5610 if (next->base.reachable)
5612 next->base.reachable = true;
5614 while_statement_t const *const whiles = &next->whiles;
5615 int const val = determine_truth(whiles->condition);
5618 check_reachable(whiles->body);
5624 next = next->base.next;
5628 case STATEMENT_DO_WHILE: {
5630 if (next->base.reachable)
5632 next->base.reachable = true;
5634 do_while_statement_t const *const dw = &next->do_while;
5635 int const val = determine_truth(dw->condition);
5638 check_reachable(dw->body);
5644 next = next->base.next;
5648 case STATEMENT_FOR: {
5650 for_statement_t *const fors = &next->fors;
5652 fors->step_reachable = true;
5654 if (fors->condition_reachable)
5656 fors->condition_reachable = true;
5658 expression_t const *const cond = fors->condition;
5660 cond == NULL ? 1 : determine_truth(cond);
5663 check_reachable(fors->body);
5669 next = next->base.next;
5673 case STATEMENT_MS_TRY:
5675 next = next->ms_try.final_statement;
5680 check_reachable(next);
5683 static void check_unreachable(statement_t* const stmt, void *const env)
5687 switch (stmt->kind) {
5688 case STATEMENT_DO_WHILE:
5689 if (!stmt->base.reachable) {
5690 expression_t const *const cond = stmt->do_while.condition;
5691 if (determine_truth(cond) >= 0) {
5692 warningf(&cond->base.source_position,
5693 "condition of do-while-loop is unreachable");
5698 case STATEMENT_FOR: {
5699 for_statement_t const* const fors = &stmt->fors;
5701 // if init and step are unreachable, cond is unreachable, too
5702 if (!stmt->base.reachable && !fors->step_reachable) {
5703 warningf(&stmt->base.source_position, "statement is unreachable");
5705 if (!stmt->base.reachable && fors->initialisation != NULL) {
5706 warningf(&fors->initialisation->base.source_position,
5707 "initialisation of for-statement is unreachable");
5710 if (!fors->condition_reachable && fors->condition != NULL) {
5711 warningf(&fors->condition->base.source_position,
5712 "condition of for-statement is unreachable");
5715 if (!fors->step_reachable && fors->step != NULL) {
5716 warningf(&fors->step->base.source_position,
5717 "step of for-statement is unreachable");
5723 case STATEMENT_COMPOUND:
5724 if (stmt->compound.statements != NULL)
5729 if (!stmt->base.reachable)
5730 warningf(&stmt->base.source_position, "statement is unreachable");
5735 static void parse_external_declaration(void)
5737 /* function-definitions and declarations both start with declaration
5739 declaration_specifiers_t specifiers;
5740 memset(&specifiers, 0, sizeof(specifiers));
5742 add_anchor_token(';');
5743 parse_declaration_specifiers(&specifiers);
5744 rem_anchor_token(';');
5746 /* must be a declaration */
5747 if (token.type == ';') {
5748 parse_anonymous_declaration_rest(&specifiers);
5752 add_anchor_token(',');
5753 add_anchor_token('=');
5754 add_anchor_token(';');
5755 add_anchor_token('{');
5757 /* declarator is common to both function-definitions and declarations */
5758 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5760 rem_anchor_token('{');
5761 rem_anchor_token(';');
5762 rem_anchor_token('=');
5763 rem_anchor_token(',');
5765 /* must be a declaration */
5766 switch (token.type) {
5770 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5774 /* must be a function definition */
5775 parse_kr_declaration_list(ndeclaration);
5777 if (token.type != '{') {
5778 parse_error_expected("while parsing function definition", '{', NULL);
5779 eat_until_matching_token(';');
5783 type_t *type = ndeclaration->type;
5785 /* note that we don't skip typerefs: the standard doesn't allow them here
5786 * (so we can't use is_type_function here) */
5787 if (type->kind != TYPE_FUNCTION) {
5788 if (is_type_valid(type)) {
5789 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5790 type, ndeclaration->symbol);
5796 if (warning.aggregate_return &&
5797 is_type_compound(skip_typeref(type->function.return_type))) {
5798 warningf(HERE, "function '%Y' returns an aggregate",
5799 ndeclaration->symbol);
5801 if (warning.traditional && !type->function.unspecified_parameters) {
5802 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5803 ndeclaration->symbol);
5805 if (warning.old_style_definition && type->function.unspecified_parameters) {
5806 warningf(HERE, "old-style function definition '%Y'",
5807 ndeclaration->symbol);
5810 /* § 6.7.5.3 (14) a function definition with () means no
5811 * parameters (and not unspecified parameters) */
5812 if (type->function.unspecified_parameters
5813 && type->function.parameters == NULL
5814 && !type->function.kr_style_parameters) {
5815 type_t *duplicate = duplicate_type(type);
5816 duplicate->function.unspecified_parameters = false;
5818 type = typehash_insert(duplicate);
5819 if (type != duplicate) {
5820 obstack_free(type_obst, duplicate);
5822 ndeclaration->type = type;
5825 declaration_t *const declaration = record_declaration(ndeclaration, true);
5826 if (ndeclaration != declaration) {
5827 declaration->scope = ndeclaration->scope;
5829 type = skip_typeref(declaration->type);
5831 /* push function parameters and switch scope */
5832 size_t const top = environment_top();
5833 scope_push(&declaration->scope);
5835 declaration_t *parameter = declaration->scope.declarations;
5836 for( ; parameter != NULL; parameter = parameter->next) {
5837 if (parameter->parent_scope == &ndeclaration->scope) {
5838 parameter->parent_scope = scope;
5840 assert(parameter->parent_scope == NULL
5841 || parameter->parent_scope == scope);
5842 parameter->parent_scope = scope;
5843 if (parameter->symbol == NULL) {
5844 errorf(¶meter->source_position, "parameter name omitted");
5847 environment_push(parameter);
5850 if (declaration->init.statement != NULL) {
5851 parser_error_multiple_definition(declaration, HERE);
5854 /* parse function body */
5855 int label_stack_top = label_top();
5856 declaration_t *old_current_function = current_function;
5857 current_function = declaration;
5858 current_parent = NULL;
5860 statement_t *const body = parse_compound_statement(false);
5861 declaration->init.statement = body;
5864 check_declarations();
5865 if (warning.return_type ||
5866 warning.unreachable_code ||
5867 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5868 noreturn_candidate = true;
5869 check_reachable(body);
5870 if (warning.unreachable_code)
5871 walk_statements(body, check_unreachable, NULL);
5872 if (warning.missing_noreturn &&
5873 noreturn_candidate &&
5874 !(declaration->modifiers & DM_NORETURN)) {
5875 warningf(&body->base.source_position,
5876 "function '%#T' is candidate for attribute 'noreturn'",
5877 type, declaration->symbol);
5881 assert(current_parent == NULL);
5882 assert(current_function == declaration);
5883 current_function = old_current_function;
5884 label_pop_to(label_stack_top);
5887 assert(scope == &declaration->scope);
5889 environment_pop_to(top);
5892 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5893 source_position_t *source_position,
5894 const symbol_t *symbol)
5896 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5898 type->bitfield.base_type = base_type;
5899 type->bitfield.size_expression = size;
5902 type_t *skipped_type = skip_typeref(base_type);
5903 if (!is_type_integer(skipped_type)) {
5904 errorf(HERE, "bitfield base type '%T' is not an integer type",
5908 bit_size = skipped_type->base.size * 8;
5911 if (is_constant_expression(size)) {
5912 long v = fold_constant(size);
5915 errorf(source_position, "negative width in bit-field '%Y'",
5917 } else if (v == 0) {
5918 errorf(source_position, "zero width for bit-field '%Y'",
5920 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5921 errorf(source_position, "width of '%Y' exceeds its type",
5924 type->bitfield.bit_size = v;
5931 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5934 declaration_t *iter = compound_declaration->scope.declarations;
5935 for( ; iter != NULL; iter = iter->next) {
5936 if (iter->namespc != NAMESPACE_NORMAL)
5939 if (iter->symbol == NULL) {
5940 type_t *type = skip_typeref(iter->type);
5941 if (is_type_compound(type)) {
5942 declaration_t *result
5943 = find_compound_entry(type->compound.declaration, symbol);
5950 if (iter->symbol == symbol) {
5958 static void parse_compound_declarators(declaration_t *struct_declaration,
5959 const declaration_specifiers_t *specifiers)
5961 declaration_t *last_declaration = struct_declaration->scope.declarations;
5962 if (last_declaration != NULL) {
5963 while (last_declaration->next != NULL) {
5964 last_declaration = last_declaration->next;
5969 declaration_t *declaration;
5971 if (token.type == ':') {
5972 source_position_t source_position = *HERE;
5975 type_t *base_type = specifiers->type;
5976 expression_t *size = parse_constant_expression();
5978 type_t *type = make_bitfield_type(base_type, size,
5979 &source_position, sym_anonymous);
5981 declaration = allocate_declaration_zero();
5982 declaration->namespc = NAMESPACE_NORMAL;
5983 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5984 declaration->storage_class = STORAGE_CLASS_NONE;
5985 declaration->source_position = source_position;
5986 declaration->modifiers = specifiers->modifiers;
5987 declaration->type = type;
5989 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5991 type_t *orig_type = declaration->type;
5992 type_t *type = skip_typeref(orig_type);
5994 if (token.type == ':') {
5995 source_position_t source_position = *HERE;
5997 expression_t *size = parse_constant_expression();
5999 type_t *bitfield_type = make_bitfield_type(orig_type, size,
6000 &source_position, declaration->symbol);
6001 declaration->type = bitfield_type;
6003 /* TODO we ignore arrays for now... what is missing is a check
6004 * that they're at the end of the struct */
6005 if (is_type_incomplete(type) && !is_type_array(type)) {
6007 "compound member '%Y' has incomplete type '%T'",
6008 declaration->symbol, orig_type);
6009 } else if (is_type_function(type)) {
6010 errorf(HERE, "compound member '%Y' must not have function type '%T'",
6011 declaration->symbol, orig_type);
6016 /* make sure we don't define a symbol multiple times */
6017 symbol_t *symbol = declaration->symbol;
6018 if (symbol != NULL) {
6019 declaration_t *prev_decl
6020 = find_compound_entry(struct_declaration, symbol);
6022 if (prev_decl != NULL) {
6023 assert(prev_decl->symbol == symbol);
6024 errorf(&declaration->source_position,
6025 "multiple declarations of symbol '%Y' (declared %P)",
6026 symbol, &prev_decl->source_position);
6030 /* append declaration */
6031 if (last_declaration != NULL) {
6032 last_declaration->next = declaration;
6034 struct_declaration->scope.declarations = declaration;
6036 last_declaration = declaration;
6038 if (token.type != ',')
6048 static void parse_compound_type_entries(declaration_t *compound_declaration)
6051 add_anchor_token('}');
6053 while (token.type != '}') {
6054 if (token.type == T_EOF) {
6055 errorf(HERE, "EOF while parsing struct");
6058 declaration_specifiers_t specifiers;
6059 memset(&specifiers, 0, sizeof(specifiers));
6060 parse_declaration_specifiers(&specifiers);
6062 parse_compound_declarators(compound_declaration, &specifiers);
6064 rem_anchor_token('}');
6068 static type_t *parse_typename(void)
6070 declaration_specifiers_t specifiers;
6071 memset(&specifiers, 0, sizeof(specifiers));
6072 parse_declaration_specifiers(&specifiers);
6073 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
6074 /* TODO: improve error message, user does probably not know what a
6075 * storage class is...
6077 errorf(HERE, "typename may not have a storage class");
6080 type_t *result = parse_abstract_declarator(specifiers.type);
6088 typedef expression_t* (*parse_expression_function)(void);
6089 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6091 typedef struct expression_parser_function_t expression_parser_function_t;
6092 struct expression_parser_function_t {
6093 parse_expression_function parser;
6094 unsigned infix_precedence;
6095 parse_expression_infix_function infix_parser;
6098 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6101 * Prints an error message if an expression was expected but not read
6103 static expression_t *expected_expression_error(void)
6105 /* skip the error message if the error token was read */
6106 if (token.type != T_ERROR) {
6107 errorf(HERE, "expected expression, got token '%K'", &token);
6111 return create_invalid_expression();
6115 * Parse a string constant.
6117 static expression_t *parse_string_const(void)
6120 if (token.type == T_STRING_LITERAL) {
6121 string_t res = token.v.string;
6123 while (token.type == T_STRING_LITERAL) {
6124 res = concat_strings(&res, &token.v.string);
6127 if (token.type != T_WIDE_STRING_LITERAL) {
6128 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6129 /* note: that we use type_char_ptr here, which is already the
6130 * automatic converted type. revert_automatic_type_conversion
6131 * will construct the array type */
6132 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6133 cnst->string.value = res;
6137 wres = concat_string_wide_string(&res, &token.v.wide_string);
6139 wres = token.v.wide_string;
6144 switch (token.type) {
6145 case T_WIDE_STRING_LITERAL:
6146 wres = concat_wide_strings(&wres, &token.v.wide_string);
6149 case T_STRING_LITERAL:
6150 wres = concat_wide_string_string(&wres, &token.v.string);
6154 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6155 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6156 cnst->wide_string.value = wres;
6165 * Parse an integer constant.
6167 static expression_t *parse_int_const(void)
6169 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6170 cnst->base.source_position = *HERE;
6171 cnst->base.type = token.datatype;
6172 cnst->conste.v.int_value = token.v.intvalue;
6180 * Parse a character constant.
6182 static expression_t *parse_character_constant(void)
6184 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6186 cnst->base.source_position = *HERE;
6187 cnst->base.type = token.datatype;
6188 cnst->conste.v.character = token.v.string;
6190 if (cnst->conste.v.character.size != 1) {
6191 if (warning.multichar && GNU_MODE) {
6192 warningf(HERE, "multi-character character constant");
6194 errorf(HERE, "more than 1 characters in character constant");
6203 * Parse a wide character constant.
6205 static expression_t *parse_wide_character_constant(void)
6207 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6209 cnst->base.source_position = *HERE;
6210 cnst->base.type = token.datatype;
6211 cnst->conste.v.wide_character = token.v.wide_string;
6213 if (cnst->conste.v.wide_character.size != 1) {
6214 if (warning.multichar && GNU_MODE) {
6215 warningf(HERE, "multi-character character constant");
6217 errorf(HERE, "more than 1 characters in character constant");
6226 * Parse a float constant.
6228 static expression_t *parse_float_const(void)
6230 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6231 cnst->base.type = token.datatype;
6232 cnst->conste.v.float_value = token.v.floatvalue;
6239 static declaration_t *create_implicit_function(symbol_t *symbol,
6240 const source_position_t *source_position)
6242 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6243 ntype->function.return_type = type_int;
6244 ntype->function.unspecified_parameters = true;
6246 type_t *type = typehash_insert(ntype);
6247 if (type != ntype) {
6251 declaration_t *const declaration = allocate_declaration_zero();
6252 declaration->storage_class = STORAGE_CLASS_EXTERN;
6253 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
6254 declaration->type = type;
6255 declaration->symbol = symbol;
6256 declaration->source_position = *source_position;
6257 declaration->implicit = true;
6259 bool strict_prototypes_old = warning.strict_prototypes;
6260 warning.strict_prototypes = false;
6261 record_declaration(declaration, false);
6262 warning.strict_prototypes = strict_prototypes_old;
6268 * Creates a return_type (func)(argument_type) function type if not
6271 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6272 type_t *argument_type2)
6274 function_parameter_t *parameter2
6275 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6276 memset(parameter2, 0, sizeof(parameter2[0]));
6277 parameter2->type = argument_type2;
6279 function_parameter_t *parameter1
6280 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6281 memset(parameter1, 0, sizeof(parameter1[0]));
6282 parameter1->type = argument_type1;
6283 parameter1->next = parameter2;
6285 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6286 type->function.return_type = return_type;
6287 type->function.parameters = parameter1;
6289 type_t *result = typehash_insert(type);
6290 if (result != type) {
6298 * Creates a return_type (func)(argument_type) function type if not
6301 * @param return_type the return type
6302 * @param argument_type the argument type
6304 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6306 function_parameter_t *parameter
6307 = obstack_alloc(type_obst, sizeof(parameter[0]));
6308 memset(parameter, 0, sizeof(parameter[0]));
6309 parameter->type = argument_type;
6311 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6312 type->function.return_type = return_type;
6313 type->function.parameters = parameter;
6315 type_t *result = typehash_insert(type);
6316 if (result != type) {
6323 static type_t *make_function_0_type(type_t *return_type)
6325 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6326 type->function.return_type = return_type;
6327 type->function.parameters = NULL;
6329 type_t *result = typehash_insert(type);
6330 if (result != type) {
6338 * Creates a function type for some function like builtins.
6340 * @param symbol the symbol describing the builtin
6342 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6344 switch(symbol->ID) {
6345 case T___builtin_alloca:
6346 return make_function_1_type(type_void_ptr, type_size_t);
6347 case T___builtin_huge_val:
6348 return make_function_0_type(type_double);
6349 case T___builtin_inf:
6350 return make_function_0_type(type_double);
6351 case T___builtin_inff:
6352 return make_function_0_type(type_float);
6353 case T___builtin_infl:
6354 return make_function_0_type(type_long_double);
6355 case T___builtin_nan:
6356 return make_function_1_type(type_double, type_char_ptr);
6357 case T___builtin_nanf:
6358 return make_function_1_type(type_float, type_char_ptr);
6359 case T___builtin_nanl:
6360 return make_function_1_type(type_long_double, type_char_ptr);
6361 case T___builtin_va_end:
6362 return make_function_1_type(type_void, type_valist);
6363 case T___builtin_expect:
6364 return make_function_2_type(type_long, type_long, type_long);
6366 internal_errorf(HERE, "not implemented builtin symbol found");
6371 * Performs automatic type cast as described in § 6.3.2.1.
6373 * @param orig_type the original type
6375 static type_t *automatic_type_conversion(type_t *orig_type)
6377 type_t *type = skip_typeref(orig_type);
6378 if (is_type_array(type)) {
6379 array_type_t *array_type = &type->array;
6380 type_t *element_type = array_type->element_type;
6381 unsigned qualifiers = array_type->base.qualifiers;
6383 return make_pointer_type(element_type, qualifiers);
6386 if (is_type_function(type)) {
6387 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6394 * reverts the automatic casts of array to pointer types and function
6395 * to function-pointer types as defined § 6.3.2.1
6397 type_t *revert_automatic_type_conversion(const expression_t *expression)
6399 switch (expression->kind) {
6400 case EXPR_REFERENCE: return expression->reference.declaration->type;
6403 return get_qualified_type(expression->select.compound_entry->type,
6404 expression->base.type->base.qualifiers);
6406 case EXPR_UNARY_DEREFERENCE: {
6407 const expression_t *const value = expression->unary.value;
6408 type_t *const type = skip_typeref(value->base.type);
6409 assert(is_type_pointer(type));
6410 return type->pointer.points_to;
6413 case EXPR_BUILTIN_SYMBOL:
6414 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6416 case EXPR_ARRAY_ACCESS: {
6417 const expression_t *array_ref = expression->array_access.array_ref;
6418 type_t *type_left = skip_typeref(array_ref->base.type);
6419 if (!is_type_valid(type_left))
6421 assert(is_type_pointer(type_left));
6422 return type_left->pointer.points_to;
6425 case EXPR_STRING_LITERAL: {
6426 size_t size = expression->string.value.size;
6427 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6430 case EXPR_WIDE_STRING_LITERAL: {
6431 size_t size = expression->wide_string.value.size;
6432 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6435 case EXPR_COMPOUND_LITERAL:
6436 return expression->compound_literal.type;
6441 return expression->base.type;
6444 static expression_t *parse_reference(void)
6446 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6448 reference_expression_t *ref = &expression->reference;
6449 symbol_t *const symbol = token.v.symbol;
6451 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6453 if (declaration == NULL) {
6454 if (!strict_mode && look_ahead(1)->type == '(') {
6455 /* an implicitly declared function */
6456 if (warning.implicit_function_declaration) {
6457 warningf(HERE, "implicit declaration of function '%Y'",
6461 declaration = create_implicit_function(symbol, HERE);
6463 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6464 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6468 type_t *orig_type = declaration->type;
6470 /* we always do the auto-type conversions; the & and sizeof parser contains
6471 * code to revert this! */
6472 type_t *type = automatic_type_conversion(orig_type);
6474 ref->declaration = declaration;
6475 ref->base.type = type;
6477 /* this declaration is used */
6478 declaration->used = true;
6480 if (declaration->parent_scope != file_scope &&
6481 declaration->parent_scope->depth < current_function->scope.depth &&
6482 is_type_valid(orig_type) && !is_type_function(orig_type)) {
6483 /* access of a variable from an outer function */
6484 declaration->address_taken = true;
6485 current_function->need_closure = true;
6488 /* check for deprecated functions */
6489 if (warning.deprecated_declarations &&
6490 declaration->modifiers & DM_DEPRECATED) {
6491 char const *const prefix = is_type_function(declaration->type) ?
6492 "function" : "variable";
6494 if (declaration->deprecated_string != NULL) {
6495 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6496 prefix, declaration->symbol, &declaration->source_position,
6497 declaration->deprecated_string);
6499 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6500 declaration->symbol, &declaration->source_position);
6503 if (warning.init_self && declaration == current_init_decl && !in_type_prop) {
6504 current_init_decl = NULL;
6505 warningf(HERE, "variable '%#T' is initialized by itself",
6506 declaration->type, declaration->symbol);
6513 static bool semantic_cast(expression_t *cast)
6515 expression_t *expression = cast->unary.value;
6516 type_t *orig_dest_type = cast->base.type;
6517 type_t *orig_type_right = expression->base.type;
6518 type_t const *dst_type = skip_typeref(orig_dest_type);
6519 type_t const *src_type = skip_typeref(orig_type_right);
6520 source_position_t const *pos = &cast->base.source_position;
6522 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6523 if (dst_type == type_void)
6526 /* only integer and pointer can be casted to pointer */
6527 if (is_type_pointer(dst_type) &&
6528 !is_type_pointer(src_type) &&
6529 !is_type_integer(src_type) &&
6530 is_type_valid(src_type)) {
6531 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6535 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6536 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6540 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6541 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6545 if (warning.cast_qual &&
6546 is_type_pointer(src_type) &&
6547 is_type_pointer(dst_type)) {
6548 type_t *src = skip_typeref(src_type->pointer.points_to);
6549 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6550 unsigned missing_qualifiers =
6551 src->base.qualifiers & ~dst->base.qualifiers;
6552 if (missing_qualifiers != 0) {
6554 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6555 missing_qualifiers, orig_type_right);
6561 static expression_t *parse_compound_literal(type_t *type)
6563 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6565 parse_initializer_env_t env;
6567 env.declaration = NULL;
6568 env.must_be_constant = false;
6569 initializer_t *initializer = parse_initializer(&env);
6572 expression->compound_literal.initializer = initializer;
6573 expression->compound_literal.type = type;
6574 expression->base.type = automatic_type_conversion(type);
6580 * Parse a cast expression.
6582 static expression_t *parse_cast(void)
6584 add_anchor_token(')');
6586 source_position_t source_position = token.source_position;
6588 type_t *type = parse_typename();
6590 rem_anchor_token(')');
6593 if (token.type == '{') {
6594 return parse_compound_literal(type);
6597 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6598 cast->base.source_position = source_position;
6600 expression_t *value = parse_sub_expression(PREC_CAST);
6601 cast->base.type = type;
6602 cast->unary.value = value;
6604 if (! semantic_cast(cast)) {
6605 /* TODO: record the error in the AST. else it is impossible to detect it */
6610 return create_invalid_expression();
6614 * Parse a statement expression.
6616 static expression_t *parse_statement_expression(void)
6618 add_anchor_token(')');
6620 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6622 statement_t *statement = parse_compound_statement(true);
6623 expression->statement.statement = statement;
6624 expression->base.source_position = statement->base.source_position;
6626 /* find last statement and use its type */
6627 type_t *type = type_void;
6628 const statement_t *stmt = statement->compound.statements;
6630 while (stmt->base.next != NULL)
6631 stmt = stmt->base.next;
6633 if (stmt->kind == STATEMENT_EXPRESSION) {
6634 type = stmt->expression.expression->base.type;
6636 } else if (warning.other) {
6637 warningf(&expression->base.source_position, "empty statement expression ({})");
6639 expression->base.type = type;
6641 rem_anchor_token(')');
6649 * Parse a parenthesized expression.
6651 static expression_t *parse_parenthesized_expression(void)
6655 switch(token.type) {
6657 /* gcc extension: a statement expression */
6658 return parse_statement_expression();
6662 return parse_cast();
6664 if (is_typedef_symbol(token.v.symbol)) {
6665 return parse_cast();
6669 add_anchor_token(')');
6670 expression_t *result = parse_expression();
6671 rem_anchor_token(')');
6678 static expression_t *parse_function_keyword(void)
6683 if (current_function == NULL) {
6684 errorf(HERE, "'__func__' used outside of a function");
6687 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6688 expression->base.type = type_char_ptr;
6689 expression->funcname.kind = FUNCNAME_FUNCTION;
6694 static expression_t *parse_pretty_function_keyword(void)
6696 eat(T___PRETTY_FUNCTION__);
6698 if (current_function == NULL) {
6699 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6702 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6703 expression->base.type = type_char_ptr;
6704 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6709 static expression_t *parse_funcsig_keyword(void)
6713 if (current_function == NULL) {
6714 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6717 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6718 expression->base.type = type_char_ptr;
6719 expression->funcname.kind = FUNCNAME_FUNCSIG;
6724 static expression_t *parse_funcdname_keyword(void)
6726 eat(T___FUNCDNAME__);
6728 if (current_function == NULL) {
6729 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6732 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6733 expression->base.type = type_char_ptr;
6734 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6739 static designator_t *parse_designator(void)
6741 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6742 result->source_position = *HERE;
6744 if (token.type != T_IDENTIFIER) {
6745 parse_error_expected("while parsing member designator",
6746 T_IDENTIFIER, NULL);
6749 result->symbol = token.v.symbol;
6752 designator_t *last_designator = result;
6754 if (token.type == '.') {
6756 if (token.type != T_IDENTIFIER) {
6757 parse_error_expected("while parsing member designator",
6758 T_IDENTIFIER, NULL);
6761 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6762 designator->source_position = *HERE;
6763 designator->symbol = token.v.symbol;
6766 last_designator->next = designator;
6767 last_designator = designator;
6770 if (token.type == '[') {
6772 add_anchor_token(']');
6773 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6774 designator->source_position = *HERE;
6775 designator->array_index = parse_expression();
6776 rem_anchor_token(']');
6778 if (designator->array_index == NULL) {
6782 last_designator->next = designator;
6783 last_designator = designator;
6795 * Parse the __builtin_offsetof() expression.
6797 static expression_t *parse_offsetof(void)
6799 eat(T___builtin_offsetof);
6801 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6802 expression->base.type = type_size_t;
6805 add_anchor_token(',');
6806 type_t *type = parse_typename();
6807 rem_anchor_token(',');
6809 add_anchor_token(')');
6810 designator_t *designator = parse_designator();
6811 rem_anchor_token(')');
6814 expression->offsetofe.type = type;
6815 expression->offsetofe.designator = designator;
6818 memset(&path, 0, sizeof(path));
6819 path.top_type = type;
6820 path.path = NEW_ARR_F(type_path_entry_t, 0);
6822 descend_into_subtype(&path);
6824 if (!walk_designator(&path, designator, true)) {
6825 return create_invalid_expression();
6828 DEL_ARR_F(path.path);
6832 return create_invalid_expression();
6836 * Parses a _builtin_va_start() expression.
6838 static expression_t *parse_va_start(void)
6840 eat(T___builtin_va_start);
6842 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6845 add_anchor_token(',');
6846 expression->va_starte.ap = parse_assignment_expression();
6847 rem_anchor_token(',');
6849 expression_t *const expr = parse_assignment_expression();
6850 if (expr->kind == EXPR_REFERENCE) {
6851 declaration_t *const decl = expr->reference.declaration;
6852 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6853 errorf(&expr->base.source_position,
6854 "second argument of 'va_start' must be last parameter of the current function");
6856 expression->va_starte.parameter = decl;
6862 return create_invalid_expression();
6866 * Parses a _builtin_va_arg() expression.
6868 static expression_t *parse_va_arg(void)
6870 eat(T___builtin_va_arg);
6872 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6875 expression->va_arge.ap = parse_assignment_expression();
6877 expression->base.type = parse_typename();
6882 return create_invalid_expression();
6885 static expression_t *parse_builtin_symbol(void)
6887 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6889 symbol_t *symbol = token.v.symbol;
6891 expression->builtin_symbol.symbol = symbol;
6894 type_t *type = get_builtin_symbol_type(symbol);
6895 type = automatic_type_conversion(type);
6897 expression->base.type = type;
6902 * Parses a __builtin_constant() expression.
6904 static expression_t *parse_builtin_constant(void)
6906 eat(T___builtin_constant_p);
6908 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6911 add_anchor_token(')');
6912 expression->builtin_constant.value = parse_assignment_expression();
6913 rem_anchor_token(')');
6915 expression->base.type = type_int;
6919 return create_invalid_expression();
6923 * Parses a __builtin_prefetch() expression.
6925 static expression_t *parse_builtin_prefetch(void)
6927 eat(T___builtin_prefetch);
6929 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6932 add_anchor_token(')');
6933 expression->builtin_prefetch.adr = parse_assignment_expression();
6934 if (token.type == ',') {
6936 expression->builtin_prefetch.rw = parse_assignment_expression();
6938 if (token.type == ',') {
6940 expression->builtin_prefetch.locality = parse_assignment_expression();
6942 rem_anchor_token(')');
6944 expression->base.type = type_void;
6948 return create_invalid_expression();
6952 * Parses a __builtin_is_*() compare expression.
6954 static expression_t *parse_compare_builtin(void)
6956 expression_t *expression;
6958 switch(token.type) {
6959 case T___builtin_isgreater:
6960 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6962 case T___builtin_isgreaterequal:
6963 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6965 case T___builtin_isless:
6966 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6968 case T___builtin_islessequal:
6969 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6971 case T___builtin_islessgreater:
6972 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6974 case T___builtin_isunordered:
6975 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6978 internal_errorf(HERE, "invalid compare builtin found");
6980 expression->base.source_position = *HERE;
6984 expression->binary.left = parse_assignment_expression();
6986 expression->binary.right = parse_assignment_expression();
6989 type_t *const orig_type_left = expression->binary.left->base.type;
6990 type_t *const orig_type_right = expression->binary.right->base.type;
6992 type_t *const type_left = skip_typeref(orig_type_left);
6993 type_t *const type_right = skip_typeref(orig_type_right);
6994 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6995 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6996 type_error_incompatible("invalid operands in comparison",
6997 &expression->base.source_position, orig_type_left, orig_type_right);
7000 semantic_comparison(&expression->binary);
7005 return create_invalid_expression();
7010 * Parses a __builtin_expect() expression.
7012 static expression_t *parse_builtin_expect(void)
7014 eat(T___builtin_expect);
7016 expression_t *expression
7017 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7020 expression->binary.left = parse_assignment_expression();
7022 expression->binary.right = parse_constant_expression();
7025 expression->base.type = expression->binary.left->base.type;
7029 return create_invalid_expression();
7034 * Parses a MS assume() expression.
7036 static expression_t *parse_assume(void)
7040 expression_t *expression
7041 = allocate_expression_zero(EXPR_UNARY_ASSUME);
7044 add_anchor_token(')');
7045 expression->unary.value = parse_assignment_expression();
7046 rem_anchor_token(')');
7049 expression->base.type = type_void;
7052 return create_invalid_expression();
7056 * Return the declaration for a given label symbol or create a new one.
7058 * @param symbol the symbol of the label
7060 static declaration_t *get_label(symbol_t *symbol)
7062 declaration_t *candidate;
7063 assert(current_function != NULL);
7065 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
7066 /* if we found a local label, we already created the declaration */
7067 if (candidate != NULL) {
7068 if (candidate->parent_scope != scope) {
7069 assert(candidate->parent_scope->depth < scope->depth);
7070 current_function->goto_to_outer = true;
7075 candidate = get_declaration(symbol, NAMESPACE_LABEL);
7076 /* if we found a label in the same function, then we already created the
7078 if (candidate != NULL
7079 && candidate->parent_scope == ¤t_function->scope) {
7083 /* otherwise we need to create a new one */
7084 declaration_t *const declaration = allocate_declaration_zero();
7085 declaration->namespc = NAMESPACE_LABEL;
7086 declaration->symbol = symbol;
7088 label_push(declaration);
7094 * Parses a GNU && label address expression.
7096 static expression_t *parse_label_address(void)
7098 source_position_t source_position = token.source_position;
7100 if (token.type != T_IDENTIFIER) {
7101 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7104 symbol_t *symbol = token.v.symbol;
7107 declaration_t *label = get_label(symbol);
7110 label->address_taken = true;
7112 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7113 expression->base.source_position = source_position;
7115 /* label address is threaten as a void pointer */
7116 expression->base.type = type_void_ptr;
7117 expression->label_address.declaration = label;
7120 return create_invalid_expression();
7124 * Parse a microsoft __noop expression.
7126 static expression_t *parse_noop_expression(void)
7128 source_position_t source_position = *HERE;
7131 if (token.type == '(') {
7132 /* parse arguments */
7134 add_anchor_token(')');
7135 add_anchor_token(',');
7137 if (token.type != ')') {
7139 (void)parse_assignment_expression();
7140 if (token.type != ',')
7146 rem_anchor_token(',');
7147 rem_anchor_token(')');
7150 /* the result is a (int)0 */
7151 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7152 cnst->base.source_position = source_position;
7153 cnst->base.type = type_int;
7154 cnst->conste.v.int_value = 0;
7155 cnst->conste.is_ms_noop = true;
7160 return create_invalid_expression();
7164 * Parses a primary expression.
7166 static expression_t *parse_primary_expression(void)
7168 switch (token.type) {
7169 case T_INTEGER: return parse_int_const();
7170 case T_CHARACTER_CONSTANT: return parse_character_constant();
7171 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7172 case T_FLOATINGPOINT: return parse_float_const();
7173 case T_STRING_LITERAL:
7174 case T_WIDE_STRING_LITERAL: return parse_string_const();
7175 case T_IDENTIFIER: return parse_reference();
7176 case T___FUNCTION__:
7177 case T___func__: return parse_function_keyword();
7178 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7179 case T___FUNCSIG__: return parse_funcsig_keyword();
7180 case T___FUNCDNAME__: return parse_funcdname_keyword();
7181 case T___builtin_offsetof: return parse_offsetof();
7182 case T___builtin_va_start: return parse_va_start();
7183 case T___builtin_va_arg: return parse_va_arg();
7184 case T___builtin_expect:
7185 case T___builtin_alloca:
7186 case T___builtin_inf:
7187 case T___builtin_inff:
7188 case T___builtin_infl:
7189 case T___builtin_nan:
7190 case T___builtin_nanf:
7191 case T___builtin_nanl:
7192 case T___builtin_huge_val:
7193 case T___builtin_va_end: return parse_builtin_symbol();
7194 case T___builtin_isgreater:
7195 case T___builtin_isgreaterequal:
7196 case T___builtin_isless:
7197 case T___builtin_islessequal:
7198 case T___builtin_islessgreater:
7199 case T___builtin_isunordered: return parse_compare_builtin();
7200 case T___builtin_constant_p: return parse_builtin_constant();
7201 case T___builtin_prefetch: return parse_builtin_prefetch();
7202 case T__assume: return parse_assume();
7205 return parse_label_address();
7208 case '(': return parse_parenthesized_expression();
7209 case T___noop: return parse_noop_expression();
7212 errorf(HERE, "unexpected token %K, expected an expression", &token);
7213 return create_invalid_expression();
7217 * Check if the expression has the character type and issue a warning then.
7219 static void check_for_char_index_type(const expression_t *expression)
7221 type_t *const type = expression->base.type;
7222 const type_t *const base_type = skip_typeref(type);
7224 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7225 warning.char_subscripts) {
7226 warningf(&expression->base.source_position,
7227 "array subscript has type '%T'", type);
7231 static expression_t *parse_array_expression(expression_t *left)
7234 add_anchor_token(']');
7236 expression_t *inside = parse_expression();
7238 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7240 array_access_expression_t *array_access = &expression->array_access;
7242 type_t *const orig_type_left = left->base.type;
7243 type_t *const orig_type_inside = inside->base.type;
7245 type_t *const type_left = skip_typeref(orig_type_left);
7246 type_t *const type_inside = skip_typeref(orig_type_inside);
7248 type_t *return_type;
7249 if (is_type_pointer(type_left)) {
7250 return_type = type_left->pointer.points_to;
7251 array_access->array_ref = left;
7252 array_access->index = inside;
7253 check_for_char_index_type(inside);
7254 } else if (is_type_pointer(type_inside)) {
7255 return_type = type_inside->pointer.points_to;
7256 array_access->array_ref = inside;
7257 array_access->index = left;
7258 array_access->flipped = true;
7259 check_for_char_index_type(left);
7261 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7263 "array access on object with non-pointer types '%T', '%T'",
7264 orig_type_left, orig_type_inside);
7266 return_type = type_error_type;
7267 array_access->array_ref = left;
7268 array_access->index = inside;
7271 expression->base.type = automatic_type_conversion(return_type);
7273 rem_anchor_token(']');
7274 if (token.type == ']') {
7277 parse_error_expected("Problem while parsing array access", ']', NULL);
7282 static expression_t *parse_typeprop(expression_kind_t const kind,
7283 source_position_t const pos)
7285 expression_t *tp_expression = allocate_expression_zero(kind);
7286 tp_expression->base.type = type_size_t;
7287 tp_expression->base.source_position = pos;
7289 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7291 /* we only refer to a type property, mark this case */
7292 bool old = in_type_prop;
7293 in_type_prop = true;
7294 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7296 add_anchor_token(')');
7297 type_t* const orig_type = parse_typename();
7298 tp_expression->typeprop.type = orig_type;
7300 type_t const* const type = skip_typeref(orig_type);
7301 char const* const wrong_type =
7302 is_type_incomplete(type) ? "incomplete" :
7303 type->kind == TYPE_FUNCTION ? "function designator" :
7304 type->kind == TYPE_BITFIELD ? "bitfield" :
7306 if (wrong_type != NULL) {
7307 errorf(&pos, "operand of %s expression must not be %s type '%T'",
7308 what, wrong_type, type);
7311 rem_anchor_token(')');
7314 expression_t *expression = parse_sub_expression(PREC_UNARY);
7316 type_t* const orig_type = revert_automatic_type_conversion(expression);
7317 expression->base.type = orig_type;
7319 type_t const* const type = skip_typeref(orig_type);
7320 char const* const wrong_type =
7321 is_type_incomplete(type) ? "incomplete" :
7322 type->kind == TYPE_FUNCTION ? "function designator" :
7323 type->kind == TYPE_BITFIELD ? "bitfield" :
7325 if (wrong_type != NULL) {
7326 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
7329 tp_expression->typeprop.type = expression->base.type;
7330 tp_expression->typeprop.tp_expression = expression;
7335 return tp_expression;
7338 static expression_t *parse_sizeof(void)
7340 source_position_t pos = *HERE;
7342 return parse_typeprop(EXPR_SIZEOF, pos);
7345 static expression_t *parse_alignof(void)
7347 source_position_t pos = *HERE;
7349 return parse_typeprop(EXPR_ALIGNOF, pos);
7352 static expression_t *parse_select_expression(expression_t *compound)
7354 assert(token.type == '.' || token.type == T_MINUSGREATER);
7356 bool is_pointer = (token.type == T_MINUSGREATER);
7359 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7360 select->select.compound = compound;
7362 if (token.type != T_IDENTIFIER) {
7363 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7366 symbol_t *symbol = token.v.symbol;
7369 type_t *const orig_type = compound->base.type;
7370 type_t *const type = skip_typeref(orig_type);
7373 bool saw_error = false;
7374 if (is_type_pointer(type)) {
7377 "request for member '%Y' in something not a struct or union, but '%T'",
7381 type_left = skip_typeref(type->pointer.points_to);
7383 if (is_pointer && is_type_valid(type)) {
7384 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7390 declaration_t *entry;
7391 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7392 type_left->kind == TYPE_COMPOUND_UNION) {
7393 declaration_t *const declaration = type_left->compound.declaration;
7395 if (!declaration->init.complete) {
7396 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7398 goto create_error_entry;
7401 entry = find_compound_entry(declaration, symbol);
7402 if (entry == NULL) {
7403 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7404 goto create_error_entry;
7407 if (is_type_valid(type_left) && !saw_error) {
7409 "request for member '%Y' in something not a struct or union, but '%T'",
7413 entry = allocate_declaration_zero();
7414 entry->symbol = symbol;
7417 select->select.compound_entry = entry;
7419 type_t *const res_type =
7420 get_qualified_type(entry->type, type_left->base.qualifiers);
7422 /* we always do the auto-type conversions; the & and sizeof parser contains
7423 * code to revert this! */
7424 select->base.type = automatic_type_conversion(res_type);
7426 type_t *skipped = skip_typeref(res_type);
7427 if (skipped->kind == TYPE_BITFIELD) {
7428 select->base.type = skipped->bitfield.base_type;
7434 static void check_call_argument(const function_parameter_t *parameter,
7435 call_argument_t *argument, unsigned pos)
7437 type_t *expected_type = parameter->type;
7438 type_t *expected_type_skip = skip_typeref(expected_type);
7439 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7440 expression_t *arg_expr = argument->expression;
7441 type_t *arg_type = skip_typeref(arg_expr->base.type);
7443 /* handle transparent union gnu extension */
7444 if (is_type_union(expected_type_skip)
7445 && (expected_type_skip->base.modifiers
7446 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7447 declaration_t *union_decl = expected_type_skip->compound.declaration;
7449 declaration_t *declaration = union_decl->scope.declarations;
7450 type_t *best_type = NULL;
7451 for ( ; declaration != NULL; declaration = declaration->next) {
7452 type_t *decl_type = declaration->type;
7453 error = semantic_assign(decl_type, arg_expr);
7454 if (error == ASSIGN_ERROR_INCOMPATIBLE
7455 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7458 if (error == ASSIGN_SUCCESS) {
7459 best_type = decl_type;
7460 } else if (best_type == NULL) {
7461 best_type = decl_type;
7465 if (best_type != NULL) {
7466 expected_type = best_type;
7470 error = semantic_assign(expected_type, arg_expr);
7471 argument->expression = create_implicit_cast(argument->expression,
7474 if (error != ASSIGN_SUCCESS) {
7475 /* report exact scope in error messages (like "in argument 3") */
7477 snprintf(buf, sizeof(buf), "call argument %u", pos);
7478 report_assign_error(error, expected_type, arg_expr, buf,
7479 &arg_expr->base.source_position);
7480 } else if (warning.traditional || warning.conversion) {
7481 type_t *const promoted_type = get_default_promoted_type(arg_type);
7482 if (!types_compatible(expected_type_skip, promoted_type) &&
7483 !types_compatible(expected_type_skip, type_void_ptr) &&
7484 !types_compatible(type_void_ptr, promoted_type)) {
7485 /* Deliberately show the skipped types in this warning */
7486 warningf(&arg_expr->base.source_position,
7487 "passing call argument %u as '%T' rather than '%T' due to prototype",
7488 pos, expected_type_skip, promoted_type);
7494 * Parse a call expression, ie. expression '( ... )'.
7496 * @param expression the function address
7498 static expression_t *parse_call_expression(expression_t *expression)
7500 expression_t *result = allocate_expression_zero(EXPR_CALL);
7501 result->base.source_position = expression->base.source_position;
7503 call_expression_t *call = &result->call;
7504 call->function = expression;
7506 type_t *const orig_type = expression->base.type;
7507 type_t *const type = skip_typeref(orig_type);
7509 function_type_t *function_type = NULL;
7510 if (is_type_pointer(type)) {
7511 type_t *const to_type = skip_typeref(type->pointer.points_to);
7513 if (is_type_function(to_type)) {
7514 function_type = &to_type->function;
7515 call->base.type = function_type->return_type;
7519 if (function_type == NULL && is_type_valid(type)) {
7520 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7523 /* parse arguments */
7525 add_anchor_token(')');
7526 add_anchor_token(',');
7528 if (token.type != ')') {
7529 call_argument_t *last_argument = NULL;
7532 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7534 argument->expression = parse_assignment_expression();
7535 if (last_argument == NULL) {
7536 call->arguments = argument;
7538 last_argument->next = argument;
7540 last_argument = argument;
7542 if (token.type != ',')
7547 rem_anchor_token(',');
7548 rem_anchor_token(')');
7551 if (function_type == NULL)
7554 function_parameter_t *parameter = function_type->parameters;
7555 call_argument_t *argument = call->arguments;
7556 if (!function_type->unspecified_parameters) {
7557 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7558 parameter = parameter->next, argument = argument->next) {
7559 check_call_argument(parameter, argument, ++pos);
7562 if (parameter != NULL) {
7563 errorf(HERE, "too few arguments to function '%E'", expression);
7564 } else if (argument != NULL && !function_type->variadic) {
7565 errorf(HERE, "too many arguments to function '%E'", expression);
7569 /* do default promotion */
7570 for( ; argument != NULL; argument = argument->next) {
7571 type_t *type = argument->expression->base.type;
7573 type = get_default_promoted_type(type);
7575 argument->expression
7576 = create_implicit_cast(argument->expression, type);
7579 check_format(&result->call);
7581 if (warning.aggregate_return &&
7582 is_type_compound(skip_typeref(function_type->return_type))) {
7583 warningf(&result->base.source_position,
7584 "function call has aggregate value");
7591 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7593 static bool same_compound_type(const type_t *type1, const type_t *type2)
7596 is_type_compound(type1) &&
7597 type1->kind == type2->kind &&
7598 type1->compound.declaration == type2->compound.declaration;
7602 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7604 * @param expression the conditional expression
7606 static expression_t *parse_conditional_expression(expression_t *expression)
7608 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7610 conditional_expression_t *conditional = &result->conditional;
7611 conditional->base.source_position = *HERE;
7612 conditional->condition = expression;
7615 add_anchor_token(':');
7618 type_t *const condition_type_orig = expression->base.type;
7619 type_t *const condition_type = skip_typeref(condition_type_orig);
7620 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7621 type_error("expected a scalar type in conditional condition",
7622 &expression->base.source_position, condition_type_orig);
7625 expression_t *true_expression = expression;
7626 bool gnu_cond = false;
7627 if (GNU_MODE && token.type == ':') {
7630 true_expression = parse_expression();
7631 rem_anchor_token(':');
7633 expression_t *false_expression =
7634 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7636 type_t *const orig_true_type = true_expression->base.type;
7637 type_t *const orig_false_type = false_expression->base.type;
7638 type_t *const true_type = skip_typeref(orig_true_type);
7639 type_t *const false_type = skip_typeref(orig_false_type);
7642 type_t *result_type;
7643 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7644 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7645 /* ISO/IEC 14882:1998(E) §5.16:2 */
7646 if (true_expression->kind == EXPR_UNARY_THROW) {
7647 result_type = false_type;
7648 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7649 result_type = true_type;
7651 if (warning.other && (
7652 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7653 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7655 warningf(&conditional->base.source_position,
7656 "ISO C forbids conditional expression with only one void side");
7658 result_type = type_void;
7660 } else if (is_type_arithmetic(true_type)
7661 && is_type_arithmetic(false_type)) {
7662 result_type = semantic_arithmetic(true_type, false_type);
7664 true_expression = create_implicit_cast(true_expression, result_type);
7665 false_expression = create_implicit_cast(false_expression, result_type);
7667 conditional->true_expression = true_expression;
7668 conditional->false_expression = false_expression;
7669 conditional->base.type = result_type;
7670 } else if (same_compound_type(true_type, false_type)) {
7671 /* just take 1 of the 2 types */
7672 result_type = true_type;
7673 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7674 type_t *pointer_type;
7676 expression_t *other_expression;
7677 if (is_type_pointer(true_type) &&
7678 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7679 pointer_type = true_type;
7680 other_type = false_type;
7681 other_expression = false_expression;
7683 pointer_type = false_type;
7684 other_type = true_type;
7685 other_expression = true_expression;
7688 if (is_null_pointer_constant(other_expression)) {
7689 result_type = pointer_type;
7690 } else if (is_type_pointer(other_type)) {
7691 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7692 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7695 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7696 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7698 } else if (types_compatible(get_unqualified_type(to1),
7699 get_unqualified_type(to2))) {
7702 if (warning.other) {
7703 warningf(&conditional->base.source_position,
7704 "pointer types '%T' and '%T' in conditional expression are incompatible",
7705 true_type, false_type);
7710 type_t *const type =
7711 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7712 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7713 } else if (is_type_integer(other_type)) {
7714 if (warning.other) {
7715 warningf(&conditional->base.source_position,
7716 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7718 result_type = pointer_type;
7720 if (is_type_valid(other_type)) {
7721 type_error_incompatible("while parsing conditional",
7722 &expression->base.source_position, true_type, false_type);
7724 result_type = type_error_type;
7727 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7728 type_error_incompatible("while parsing conditional",
7729 &conditional->base.source_position, true_type,
7732 result_type = type_error_type;
7735 conditional->true_expression
7736 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7737 conditional->false_expression
7738 = create_implicit_cast(false_expression, result_type);
7739 conditional->base.type = result_type;
7742 return create_invalid_expression();
7746 * Parse an extension expression.
7748 static expression_t *parse_extension(void)
7750 eat(T___extension__);
7752 bool old_gcc_extension = in_gcc_extension;
7753 in_gcc_extension = true;
7754 expression_t *expression = parse_sub_expression(PREC_UNARY);
7755 in_gcc_extension = old_gcc_extension;
7760 * Parse a __builtin_classify_type() expression.
7762 static expression_t *parse_builtin_classify_type(void)
7764 eat(T___builtin_classify_type);
7766 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7767 result->base.type = type_int;
7770 add_anchor_token(')');
7771 expression_t *expression = parse_expression();
7772 rem_anchor_token(')');
7774 result->classify_type.type_expression = expression;
7778 return create_invalid_expression();
7782 * Parse a throw expression
7783 * ISO/IEC 14882:1998(E) §15:1
7785 static expression_t *parse_throw(void)
7787 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7788 result->base.source_position = *HERE;
7789 result->base.type = type_void;
7793 expression_t *value = NULL;
7794 switch (token.type) {
7796 value = parse_assignment_expression();
7797 /* ISO/IEC 14882:1998(E) §15.1:3 */
7798 type_t *const orig_type = value->base.type;
7799 type_t *const type = skip_typeref(orig_type);
7800 if (is_type_incomplete(type)) {
7801 errorf(&value->base.source_position,
7802 "cannot throw object of incomplete type '%T'", orig_type);
7803 } else if (is_type_pointer(type)) {
7804 type_t *const points_to = skip_typeref(type->pointer.points_to);
7805 if (is_type_incomplete(points_to) &&
7806 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7807 errorf(&value->base.source_position,
7808 "cannot throw pointer to incomplete type '%T'", orig_type);
7816 result->unary.value = value;
7821 static bool check_pointer_arithmetic(const source_position_t *source_position,
7822 type_t *pointer_type,
7823 type_t *orig_pointer_type)
7825 type_t *points_to = pointer_type->pointer.points_to;
7826 points_to = skip_typeref(points_to);
7828 if (is_type_incomplete(points_to)) {
7829 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7830 errorf(source_position,
7831 "arithmetic with pointer to incomplete type '%T' not allowed",
7834 } else if (warning.pointer_arith) {
7835 warningf(source_position,
7836 "pointer of type '%T' used in arithmetic",
7839 } else if (is_type_function(points_to)) {
7841 errorf(source_position,
7842 "arithmetic with pointer to function type '%T' not allowed",
7845 } else if (warning.pointer_arith) {
7846 warningf(source_position,
7847 "pointer to a function '%T' used in arithmetic",
7854 static bool is_lvalue(const expression_t *expression)
7856 switch (expression->kind) {
7857 case EXPR_REFERENCE:
7858 case EXPR_ARRAY_ACCESS:
7860 case EXPR_UNARY_DEREFERENCE:
7864 /* Claim it is an lvalue, if the type is invalid. There was a parse
7865 * error before, which maybe prevented properly recognizing it as
7867 return !is_type_valid(skip_typeref(expression->base.type));
7871 static void semantic_incdec(unary_expression_t *expression)
7873 type_t *const orig_type = expression->value->base.type;
7874 type_t *const type = skip_typeref(orig_type);
7875 if (is_type_pointer(type)) {
7876 if (!check_pointer_arithmetic(&expression->base.source_position,
7880 } else if (!is_type_real(type) && is_type_valid(type)) {
7881 /* TODO: improve error message */
7882 errorf(&expression->base.source_position,
7883 "operation needs an arithmetic or pointer type");
7886 if (!is_lvalue(expression->value)) {
7887 /* TODO: improve error message */
7888 errorf(&expression->base.source_position, "lvalue required as operand");
7890 expression->base.type = orig_type;
7893 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7895 type_t *const orig_type = expression->value->base.type;
7896 type_t *const type = skip_typeref(orig_type);
7897 if (!is_type_arithmetic(type)) {
7898 if (is_type_valid(type)) {
7899 /* TODO: improve error message */
7900 errorf(&expression->base.source_position,
7901 "operation needs an arithmetic type");
7906 expression->base.type = orig_type;
7909 static void semantic_unexpr_plus(unary_expression_t *expression)
7911 semantic_unexpr_arithmetic(expression);
7912 if (warning.traditional)
7913 warningf(&expression->base.source_position,
7914 "traditional C rejects the unary plus operator");
7917 static expression_t const *get_reference_address(expression_t const *expr)
7919 bool regular_take_address = true;
7921 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7922 expr = expr->unary.value;
7924 regular_take_address = false;
7927 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7930 expr = expr->unary.value;
7933 if (expr->kind != EXPR_REFERENCE)
7936 if (!regular_take_address &&
7937 !is_type_function(skip_typeref(expr->reference.declaration->type))) {
7944 static void warn_function_address_as_bool(expression_t const* expr)
7946 if (!warning.address)
7949 expr = get_reference_address(expr);
7951 warningf(&expr->base.source_position,
7952 "the address of '%Y' will always evaluate as 'true'",
7953 expr->reference.declaration->symbol);
7957 static void semantic_not(unary_expression_t *expression)
7959 type_t *const orig_type = expression->value->base.type;
7960 type_t *const type = skip_typeref(orig_type);
7961 if (!is_type_scalar(type) && is_type_valid(type)) {
7962 errorf(&expression->base.source_position,
7963 "operand of ! must be of scalar type");
7966 warn_function_address_as_bool(expression->value);
7968 expression->base.type = type_int;
7971 static void semantic_unexpr_integer(unary_expression_t *expression)
7973 type_t *const orig_type = expression->value->base.type;
7974 type_t *const type = skip_typeref(orig_type);
7975 if (!is_type_integer(type)) {
7976 if (is_type_valid(type)) {
7977 errorf(&expression->base.source_position,
7978 "operand of ~ must be of integer type");
7983 expression->base.type = orig_type;
7986 static void semantic_dereference(unary_expression_t *expression)
7988 type_t *const orig_type = expression->value->base.type;
7989 type_t *const type = skip_typeref(orig_type);
7990 if (!is_type_pointer(type)) {
7991 if (is_type_valid(type)) {
7992 errorf(&expression->base.source_position,
7993 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7998 type_t *result_type = type->pointer.points_to;
7999 result_type = automatic_type_conversion(result_type);
8000 expression->base.type = result_type;
8004 * Record that an address is taken (expression represents an lvalue).
8006 * @param expression the expression
8007 * @param may_be_register if true, the expression might be an register
8009 static void set_address_taken(expression_t *expression, bool may_be_register)
8011 if (expression->kind != EXPR_REFERENCE)
8014 declaration_t *const declaration = expression->reference.declaration;
8015 /* happens for parse errors */
8016 if (declaration == NULL)
8019 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
8020 errorf(&expression->base.source_position,
8021 "address of register variable '%Y' requested",
8022 declaration->symbol);
8024 declaration->address_taken = 1;
8029 * Check the semantic of the address taken expression.
8031 static void semantic_take_addr(unary_expression_t *expression)
8033 expression_t *value = expression->value;
8034 value->base.type = revert_automatic_type_conversion(value);
8036 type_t *orig_type = value->base.type;
8037 if (!is_type_valid(skip_typeref(orig_type)))
8040 set_address_taken(value, false);
8042 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8045 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8046 static expression_t *parse_##unexpression_type(void) \
8048 expression_t *unary_expression \
8049 = allocate_expression_zero(unexpression_type); \
8050 unary_expression->base.source_position = *HERE; \
8052 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8054 sfunc(&unary_expression->unary); \
8056 return unary_expression; \
8059 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8060 semantic_unexpr_arithmetic)
8061 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8062 semantic_unexpr_plus)
8063 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8065 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8066 semantic_dereference)
8067 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8069 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8070 semantic_unexpr_integer)
8071 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8073 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8076 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8078 static expression_t *parse_##unexpression_type(expression_t *left) \
8080 expression_t *unary_expression \
8081 = allocate_expression_zero(unexpression_type); \
8082 unary_expression->base.source_position = *HERE; \
8084 unary_expression->unary.value = left; \
8086 sfunc(&unary_expression->unary); \
8088 return unary_expression; \
8091 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8092 EXPR_UNARY_POSTFIX_INCREMENT,
8094 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8095 EXPR_UNARY_POSTFIX_DECREMENT,
8098 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8100 /* TODO: handle complex + imaginary types */
8102 type_left = get_unqualified_type(type_left);
8103 type_right = get_unqualified_type(type_right);
8105 /* § 6.3.1.8 Usual arithmetic conversions */
8106 if (type_left == type_long_double || type_right == type_long_double) {
8107 return type_long_double;
8108 } else if (type_left == type_double || type_right == type_double) {
8110 } else if (type_left == type_float || type_right == type_float) {
8114 type_left = promote_integer(type_left);
8115 type_right = promote_integer(type_right);
8117 if (type_left == type_right)
8120 bool const signed_left = is_type_signed(type_left);
8121 bool const signed_right = is_type_signed(type_right);
8122 int const rank_left = get_rank(type_left);
8123 int const rank_right = get_rank(type_right);
8125 if (signed_left == signed_right)
8126 return rank_left >= rank_right ? type_left : type_right;
8135 u_rank = rank_right;
8136 u_type = type_right;
8138 s_rank = rank_right;
8139 s_type = type_right;
8144 if (u_rank >= s_rank)
8147 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8149 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8150 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8154 case ATOMIC_TYPE_INT: return type_unsigned_int;
8155 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8156 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8158 default: panic("invalid atomic type");
8163 * Check the semantic restrictions for a binary expression.
8165 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8167 expression_t *const left = expression->left;
8168 expression_t *const right = expression->right;
8169 type_t *const orig_type_left = left->base.type;
8170 type_t *const orig_type_right = right->base.type;
8171 type_t *const type_left = skip_typeref(orig_type_left);
8172 type_t *const type_right = skip_typeref(orig_type_right);
8174 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8175 /* TODO: improve error message */
8176 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8177 errorf(&expression->base.source_position,
8178 "operation needs arithmetic types");
8183 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8184 expression->left = create_implicit_cast(left, arithmetic_type);
8185 expression->right = create_implicit_cast(right, arithmetic_type);
8186 expression->base.type = arithmetic_type;
8189 static void warn_div_by_zero(binary_expression_t const *const expression)
8191 if (!warning.div_by_zero ||
8192 !is_type_integer(expression->base.type))
8195 expression_t const *const right = expression->right;
8196 /* The type of the right operand can be different for /= */
8197 if (is_type_integer(right->base.type) &&
8198 is_constant_expression(right) &&
8199 fold_constant(right) == 0) {
8200 warningf(&expression->base.source_position, "division by zero");
8205 * Check the semantic restrictions for a div/mod expression.
8207 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8208 semantic_binexpr_arithmetic(expression);
8209 warn_div_by_zero(expression);
8212 static void semantic_shift_op(binary_expression_t *expression)
8214 expression_t *const left = expression->left;
8215 expression_t *const right = expression->right;
8216 type_t *const orig_type_left = left->base.type;
8217 type_t *const orig_type_right = right->base.type;
8218 type_t * type_left = skip_typeref(orig_type_left);
8219 type_t * type_right = skip_typeref(orig_type_right);
8221 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8222 /* TODO: improve error message */
8223 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8224 errorf(&expression->base.source_position,
8225 "operands of shift operation must have integer types");
8230 type_left = promote_integer(type_left);
8231 type_right = promote_integer(type_right);
8233 expression->left = create_implicit_cast(left, type_left);
8234 expression->right = create_implicit_cast(right, type_right);
8235 expression->base.type = type_left;
8238 static void semantic_add(binary_expression_t *expression)
8240 expression_t *const left = expression->left;
8241 expression_t *const right = expression->right;
8242 type_t *const orig_type_left = left->base.type;
8243 type_t *const orig_type_right = right->base.type;
8244 type_t *const type_left = skip_typeref(orig_type_left);
8245 type_t *const type_right = skip_typeref(orig_type_right);
8248 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8249 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8250 expression->left = create_implicit_cast(left, arithmetic_type);
8251 expression->right = create_implicit_cast(right, arithmetic_type);
8252 expression->base.type = arithmetic_type;
8254 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8255 check_pointer_arithmetic(&expression->base.source_position,
8256 type_left, orig_type_left);
8257 expression->base.type = type_left;
8258 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8259 check_pointer_arithmetic(&expression->base.source_position,
8260 type_right, orig_type_right);
8261 expression->base.type = type_right;
8262 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8263 errorf(&expression->base.source_position,
8264 "invalid operands to binary + ('%T', '%T')",
8265 orig_type_left, orig_type_right);
8269 static void semantic_sub(binary_expression_t *expression)
8271 expression_t *const left = expression->left;
8272 expression_t *const right = expression->right;
8273 type_t *const orig_type_left = left->base.type;
8274 type_t *const orig_type_right = right->base.type;
8275 type_t *const type_left = skip_typeref(orig_type_left);
8276 type_t *const type_right = skip_typeref(orig_type_right);
8277 source_position_t const *const pos = &expression->base.source_position;
8280 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8281 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8282 expression->left = create_implicit_cast(left, arithmetic_type);
8283 expression->right = create_implicit_cast(right, arithmetic_type);
8284 expression->base.type = arithmetic_type;
8286 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8287 check_pointer_arithmetic(&expression->base.source_position,
8288 type_left, orig_type_left);
8289 expression->base.type = type_left;
8290 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8291 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8292 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8293 if (!types_compatible(unqual_left, unqual_right)) {
8295 "subtracting pointers to incompatible types '%T' and '%T'",
8296 orig_type_left, orig_type_right);
8297 } else if (!is_type_object(unqual_left)) {
8298 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8299 errorf(pos, "subtracting pointers to non-object types '%T'",
8301 } else if (warning.other) {
8302 warningf(pos, "subtracting pointers to void");
8305 expression->base.type = type_ptrdiff_t;
8306 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8307 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8308 orig_type_left, orig_type_right);
8312 static void warn_string_literal_address(expression_t const* expr)
8314 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8315 expr = expr->unary.value;
8316 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8318 expr = expr->unary.value;
8321 if (expr->kind == EXPR_STRING_LITERAL ||
8322 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8323 warningf(&expr->base.source_position,
8324 "comparison with string literal results in unspecified behaviour");
8329 * Check the semantics of comparison expressions.
8331 * @param expression The expression to check.
8333 static void semantic_comparison(binary_expression_t *expression)
8335 expression_t *left = expression->left;
8336 expression_t *right = expression->right;
8338 if (warning.address) {
8339 warn_string_literal_address(left);
8340 warn_string_literal_address(right);
8342 expression_t const* const func_left = get_reference_address(left);
8343 if (func_left != NULL && is_null_pointer_constant(right)) {
8344 warningf(&expression->base.source_position,
8345 "the address of '%Y' will never be NULL",
8346 func_left->reference.declaration->symbol);
8349 expression_t const* const func_right = get_reference_address(right);
8350 if (func_right != NULL && is_null_pointer_constant(right)) {
8351 warningf(&expression->base.source_position,
8352 "the address of '%Y' will never be NULL",
8353 func_right->reference.declaration->symbol);
8357 type_t *orig_type_left = left->base.type;
8358 type_t *orig_type_right = right->base.type;
8359 type_t *type_left = skip_typeref(orig_type_left);
8360 type_t *type_right = skip_typeref(orig_type_right);
8362 /* TODO non-arithmetic types */
8363 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8364 /* test for signed vs unsigned compares */
8365 if (warning.sign_compare &&
8366 (expression->base.kind != EXPR_BINARY_EQUAL &&
8367 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8368 (is_type_signed(type_left) != is_type_signed(type_right))) {
8370 /* check if 1 of the operands is a constant, in this case we just
8371 * check wether we can safely represent the resulting constant in
8372 * the type of the other operand. */
8373 expression_t *const_expr = NULL;
8374 expression_t *other_expr = NULL;
8376 if (is_constant_expression(left)) {
8379 } else if (is_constant_expression(right)) {
8384 if (const_expr != NULL) {
8385 type_t *other_type = skip_typeref(other_expr->base.type);
8386 long val = fold_constant(const_expr);
8387 /* TODO: check if val can be represented by other_type */
8391 warningf(&expression->base.source_position,
8392 "comparison between signed and unsigned");
8394 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8395 expression->left = create_implicit_cast(left, arithmetic_type);
8396 expression->right = create_implicit_cast(right, arithmetic_type);
8397 expression->base.type = arithmetic_type;
8398 if (warning.float_equal &&
8399 (expression->base.kind == EXPR_BINARY_EQUAL ||
8400 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8401 is_type_float(arithmetic_type)) {
8402 warningf(&expression->base.source_position,
8403 "comparing floating point with == or != is unsafe");
8405 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8406 /* TODO check compatibility */
8407 } else if (is_type_pointer(type_left)) {
8408 expression->right = create_implicit_cast(right, type_left);
8409 } else if (is_type_pointer(type_right)) {
8410 expression->left = create_implicit_cast(left, type_right);
8411 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8412 type_error_incompatible("invalid operands in comparison",
8413 &expression->base.source_position,
8414 type_left, type_right);
8416 expression->base.type = type_int;
8420 * Checks if a compound type has constant fields.
8422 static bool has_const_fields(const compound_type_t *type)
8424 const scope_t *scope = &type->declaration->scope;
8425 const declaration_t *declaration = scope->declarations;
8427 for (; declaration != NULL; declaration = declaration->next) {
8428 if (declaration->namespc != NAMESPACE_NORMAL)
8431 const type_t *decl_type = skip_typeref(declaration->type);
8432 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8439 static bool is_valid_assignment_lhs(expression_t const* const left)
8441 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8442 type_t *const type_left = skip_typeref(orig_type_left);
8444 if (!is_lvalue(left)) {
8445 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8450 if (is_type_array(type_left)) {
8451 errorf(HERE, "cannot assign to arrays ('%E')", left);
8454 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8455 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8459 if (is_type_incomplete(type_left)) {
8460 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8461 left, orig_type_left);
8464 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8465 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8466 left, orig_type_left);
8473 static void semantic_arithmetic_assign(binary_expression_t *expression)
8475 expression_t *left = expression->left;
8476 expression_t *right = expression->right;
8477 type_t *orig_type_left = left->base.type;
8478 type_t *orig_type_right = right->base.type;
8480 if (!is_valid_assignment_lhs(left))
8483 type_t *type_left = skip_typeref(orig_type_left);
8484 type_t *type_right = skip_typeref(orig_type_right);
8486 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8487 /* TODO: improve error message */
8488 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8489 errorf(&expression->base.source_position,
8490 "operation needs arithmetic types");
8495 /* combined instructions are tricky. We can't create an implicit cast on
8496 * the left side, because we need the uncasted form for the store.
8497 * The ast2firm pass has to know that left_type must be right_type
8498 * for the arithmetic operation and create a cast by itself */
8499 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8500 expression->right = create_implicit_cast(right, arithmetic_type);
8501 expression->base.type = type_left;
8504 static void semantic_divmod_assign(binary_expression_t *expression)
8506 semantic_arithmetic_assign(expression);
8507 warn_div_by_zero(expression);
8510 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8512 expression_t *const left = expression->left;
8513 expression_t *const right = expression->right;
8514 type_t *const orig_type_left = left->base.type;
8515 type_t *const orig_type_right = right->base.type;
8516 type_t *const type_left = skip_typeref(orig_type_left);
8517 type_t *const type_right = skip_typeref(orig_type_right);
8519 if (!is_valid_assignment_lhs(left))
8522 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8523 /* combined instructions are tricky. We can't create an implicit cast on
8524 * the left side, because we need the uncasted form for the store.
8525 * The ast2firm pass has to know that left_type must be right_type
8526 * for the arithmetic operation and create a cast by itself */
8527 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8528 expression->right = create_implicit_cast(right, arithmetic_type);
8529 expression->base.type = type_left;
8530 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8531 check_pointer_arithmetic(&expression->base.source_position,
8532 type_left, orig_type_left);
8533 expression->base.type = type_left;
8534 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8535 errorf(&expression->base.source_position,
8536 "incompatible types '%T' and '%T' in assignment",
8537 orig_type_left, orig_type_right);
8542 * Check the semantic restrictions of a logical expression.
8544 static void semantic_logical_op(binary_expression_t *expression)
8546 expression_t *const left = expression->left;
8547 expression_t *const right = expression->right;
8548 type_t *const orig_type_left = left->base.type;
8549 type_t *const orig_type_right = right->base.type;
8550 type_t *const type_left = skip_typeref(orig_type_left);
8551 type_t *const type_right = skip_typeref(orig_type_right);
8553 warn_function_address_as_bool(left);
8554 warn_function_address_as_bool(right);
8556 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8557 /* TODO: improve error message */
8558 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8559 errorf(&expression->base.source_position,
8560 "operation needs scalar types");
8565 expression->base.type = type_int;
8569 * Check the semantic restrictions of a binary assign expression.
8571 static void semantic_binexpr_assign(binary_expression_t *expression)
8573 expression_t *left = expression->left;
8574 type_t *orig_type_left = left->base.type;
8576 if (!is_valid_assignment_lhs(left))
8579 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8580 report_assign_error(error, orig_type_left, expression->right,
8581 "assignment", &left->base.source_position);
8582 expression->right = create_implicit_cast(expression->right, orig_type_left);
8583 expression->base.type = orig_type_left;
8587 * Determine if the outermost operation (or parts thereof) of the given
8588 * expression has no effect in order to generate a warning about this fact.
8589 * Therefore in some cases this only examines some of the operands of the
8590 * expression (see comments in the function and examples below).
8592 * f() + 23; // warning, because + has no effect
8593 * x || f(); // no warning, because x controls execution of f()
8594 * x ? y : f(); // warning, because y has no effect
8595 * (void)x; // no warning to be able to suppress the warning
8596 * This function can NOT be used for an "expression has definitely no effect"-
8598 static bool expression_has_effect(const expression_t *const expr)
8600 switch (expr->kind) {
8601 case EXPR_UNKNOWN: break;
8602 case EXPR_INVALID: return true; /* do NOT warn */
8603 case EXPR_REFERENCE: return false;
8604 /* suppress the warning for microsoft __noop operations */
8605 case EXPR_CONST: return expr->conste.is_ms_noop;
8606 case EXPR_CHARACTER_CONSTANT: return false;
8607 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8608 case EXPR_STRING_LITERAL: return false;
8609 case EXPR_WIDE_STRING_LITERAL: return false;
8610 case EXPR_LABEL_ADDRESS: return false;
8613 const call_expression_t *const call = &expr->call;
8614 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8617 switch (call->function->builtin_symbol.symbol->ID) {
8618 case T___builtin_va_end: return true;
8619 default: return false;
8623 /* Generate the warning if either the left or right hand side of a
8624 * conditional expression has no effect */
8625 case EXPR_CONDITIONAL: {
8626 const conditional_expression_t *const cond = &expr->conditional;
8628 expression_has_effect(cond->true_expression) &&
8629 expression_has_effect(cond->false_expression);
8632 case EXPR_SELECT: return false;
8633 case EXPR_ARRAY_ACCESS: return false;
8634 case EXPR_SIZEOF: return false;
8635 case EXPR_CLASSIFY_TYPE: return false;
8636 case EXPR_ALIGNOF: return false;
8638 case EXPR_FUNCNAME: return false;
8639 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8640 case EXPR_BUILTIN_CONSTANT_P: return false;
8641 case EXPR_BUILTIN_PREFETCH: return true;
8642 case EXPR_OFFSETOF: return false;
8643 case EXPR_VA_START: return true;
8644 case EXPR_VA_ARG: return true;
8645 case EXPR_STATEMENT: return true; // TODO
8646 case EXPR_COMPOUND_LITERAL: return false;
8648 case EXPR_UNARY_NEGATE: return false;
8649 case EXPR_UNARY_PLUS: return false;
8650 case EXPR_UNARY_BITWISE_NEGATE: return false;
8651 case EXPR_UNARY_NOT: return false;
8652 case EXPR_UNARY_DEREFERENCE: return false;
8653 case EXPR_UNARY_TAKE_ADDRESS: return false;
8654 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8655 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8656 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8657 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8659 /* Treat void casts as if they have an effect in order to being able to
8660 * suppress the warning */
8661 case EXPR_UNARY_CAST: {
8662 type_t *const type = skip_typeref(expr->base.type);
8663 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8666 case EXPR_UNARY_CAST_IMPLICIT: return true;
8667 case EXPR_UNARY_ASSUME: return true;
8668 case EXPR_UNARY_THROW: return true;
8670 case EXPR_BINARY_ADD: return false;
8671 case EXPR_BINARY_SUB: return false;
8672 case EXPR_BINARY_MUL: return false;
8673 case EXPR_BINARY_DIV: return false;
8674 case EXPR_BINARY_MOD: return false;
8675 case EXPR_BINARY_EQUAL: return false;
8676 case EXPR_BINARY_NOTEQUAL: return false;
8677 case EXPR_BINARY_LESS: return false;
8678 case EXPR_BINARY_LESSEQUAL: return false;
8679 case EXPR_BINARY_GREATER: return false;
8680 case EXPR_BINARY_GREATEREQUAL: return false;
8681 case EXPR_BINARY_BITWISE_AND: return false;
8682 case EXPR_BINARY_BITWISE_OR: return false;
8683 case EXPR_BINARY_BITWISE_XOR: return false;
8684 case EXPR_BINARY_SHIFTLEFT: return false;
8685 case EXPR_BINARY_SHIFTRIGHT: return false;
8686 case EXPR_BINARY_ASSIGN: return true;
8687 case EXPR_BINARY_MUL_ASSIGN: return true;
8688 case EXPR_BINARY_DIV_ASSIGN: return true;
8689 case EXPR_BINARY_MOD_ASSIGN: return true;
8690 case EXPR_BINARY_ADD_ASSIGN: return true;
8691 case EXPR_BINARY_SUB_ASSIGN: return true;
8692 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8693 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8694 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8695 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8696 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8698 /* Only examine the right hand side of && and ||, because the left hand
8699 * side already has the effect of controlling the execution of the right
8701 case EXPR_BINARY_LOGICAL_AND:
8702 case EXPR_BINARY_LOGICAL_OR:
8703 /* Only examine the right hand side of a comma expression, because the left
8704 * hand side has a separate warning */
8705 case EXPR_BINARY_COMMA:
8706 return expression_has_effect(expr->binary.right);
8708 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8709 case EXPR_BINARY_ISGREATER: return false;
8710 case EXPR_BINARY_ISGREATEREQUAL: return false;
8711 case EXPR_BINARY_ISLESS: return false;
8712 case EXPR_BINARY_ISLESSEQUAL: return false;
8713 case EXPR_BINARY_ISLESSGREATER: return false;
8714 case EXPR_BINARY_ISUNORDERED: return false;
8717 internal_errorf(HERE, "unexpected expression");
8720 static void semantic_comma(binary_expression_t *expression)
8722 if (warning.unused_value) {
8723 const expression_t *const left = expression->left;
8724 if (!expression_has_effect(left)) {
8725 warningf(&left->base.source_position,
8726 "left-hand operand of comma expression has no effect");
8729 expression->base.type = expression->right->base.type;
8733 * @param prec_r precedence of the right operand
8735 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8736 static expression_t *parse_##binexpression_type(expression_t *left) \
8738 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8739 binexpr->base.source_position = *HERE; \
8740 binexpr->binary.left = left; \
8743 expression_t *right = parse_sub_expression(prec_r); \
8745 binexpr->binary.right = right; \
8746 sfunc(&binexpr->binary); \
8751 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8752 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8753 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8754 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8755 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8756 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8757 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8758 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8759 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8760 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8761 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8762 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8763 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8764 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8765 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8766 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8767 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8768 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8769 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8770 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8771 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8772 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8773 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8774 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8775 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8776 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8777 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8778 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8779 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8780 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8783 static expression_t *parse_sub_expression(precedence_t precedence)
8785 if (token.type < 0) {
8786 return expected_expression_error();
8789 expression_parser_function_t *parser
8790 = &expression_parsers[token.type];
8791 source_position_t source_position = token.source_position;
8794 if (parser->parser != NULL) {
8795 left = parser->parser();
8797 left = parse_primary_expression();
8799 assert(left != NULL);
8800 left->base.source_position = source_position;
8803 if (token.type < 0) {
8804 return expected_expression_error();
8807 parser = &expression_parsers[token.type];
8808 if (parser->infix_parser == NULL)
8810 if (parser->infix_precedence < precedence)
8813 left = parser->infix_parser(left);
8815 assert(left != NULL);
8816 assert(left->kind != EXPR_UNKNOWN);
8817 left->base.source_position = source_position;
8824 * Parse an expression.
8826 static expression_t *parse_expression(void)
8828 return parse_sub_expression(PREC_EXPRESSION);
8832 * Register a parser for a prefix-like operator.
8834 * @param parser the parser function
8835 * @param token_type the token type of the prefix token
8837 static void register_expression_parser(parse_expression_function parser,
8840 expression_parser_function_t *entry = &expression_parsers[token_type];
8842 if (entry->parser != NULL) {
8843 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8844 panic("trying to register multiple expression parsers for a token");
8846 entry->parser = parser;
8850 * Register a parser for an infix operator with given precedence.
8852 * @param parser the parser function
8853 * @param token_type the token type of the infix operator
8854 * @param precedence the precedence of the operator
8856 static void register_infix_parser(parse_expression_infix_function parser,
8857 int token_type, unsigned precedence)
8859 expression_parser_function_t *entry = &expression_parsers[token_type];
8861 if (entry->infix_parser != NULL) {
8862 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8863 panic("trying to register multiple infix expression parsers for a "
8866 entry->infix_parser = parser;
8867 entry->infix_precedence = precedence;
8871 * Initialize the expression parsers.
8873 static void init_expression_parsers(void)
8875 memset(&expression_parsers, 0, sizeof(expression_parsers));
8877 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8878 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8879 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8880 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8881 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8882 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8883 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8884 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8885 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8886 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8887 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8888 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8889 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8890 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8891 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8892 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8893 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8894 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8895 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8896 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8897 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8898 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8899 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8900 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8901 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8902 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8903 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8904 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8905 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8906 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8907 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8908 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8909 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8910 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8911 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8912 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8913 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8915 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8916 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8917 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8918 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8919 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8920 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8921 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8922 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8923 register_expression_parser(parse_sizeof, T_sizeof);
8924 register_expression_parser(parse_alignof, T___alignof__);
8925 register_expression_parser(parse_extension, T___extension__);
8926 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8927 register_expression_parser(parse_throw, T_throw);
8931 * Parse a asm statement arguments specification.
8933 static asm_argument_t *parse_asm_arguments(bool is_out)
8935 asm_argument_t *result = NULL;
8936 asm_argument_t *last = NULL;
8938 while (token.type == T_STRING_LITERAL || token.type == '[') {
8939 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8940 memset(argument, 0, sizeof(argument[0]));
8942 if (token.type == '[') {
8944 if (token.type != T_IDENTIFIER) {
8945 parse_error_expected("while parsing asm argument",
8946 T_IDENTIFIER, NULL);
8949 argument->symbol = token.v.symbol;
8954 argument->constraints = parse_string_literals();
8956 add_anchor_token(')');
8957 expression_t *expression = parse_expression();
8958 rem_anchor_token(')');
8960 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8961 * change size or type representation (e.g. int -> long is ok, but
8962 * int -> float is not) */
8963 if (expression->kind == EXPR_UNARY_CAST) {
8964 type_t *const type = expression->base.type;
8965 type_kind_t const kind = type->kind;
8966 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8969 if (kind == TYPE_ATOMIC) {
8970 atomic_type_kind_t const akind = type->atomic.akind;
8971 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8972 size = get_atomic_type_size(akind);
8974 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8975 size = get_atomic_type_size(get_intptr_kind());
8979 expression_t *const value = expression->unary.value;
8980 type_t *const value_type = value->base.type;
8981 type_kind_t const value_kind = value_type->kind;
8983 unsigned value_flags;
8984 unsigned value_size;
8985 if (value_kind == TYPE_ATOMIC) {
8986 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8987 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8988 value_size = get_atomic_type_size(value_akind);
8989 } else if (value_kind == TYPE_POINTER) {
8990 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8991 value_size = get_atomic_type_size(get_intptr_kind());
8996 if (value_flags != flags || value_size != size)
9000 } while (expression->kind == EXPR_UNARY_CAST);
9004 if (!is_lvalue(expression)) {
9005 errorf(&expression->base.source_position,
9006 "asm output argument is not an lvalue");
9009 if (argument->constraints.begin[0] == '+')
9010 mark_decls_read(expression, NULL);
9012 mark_decls_read(expression, NULL);
9014 argument->expression = expression;
9017 set_address_taken(expression, true);
9020 last->next = argument;
9026 if (token.type != ',')
9037 * Parse a asm statement clobber specification.
9039 static asm_clobber_t *parse_asm_clobbers(void)
9041 asm_clobber_t *result = NULL;
9042 asm_clobber_t *last = NULL;
9044 while(token.type == T_STRING_LITERAL) {
9045 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9046 clobber->clobber = parse_string_literals();
9049 last->next = clobber;
9055 if (token.type != ',')
9064 * Parse an asm statement.
9066 static statement_t *parse_asm_statement(void)
9068 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9069 asm_statement_t *asm_statement = &statement->asms;
9073 if (token.type == T_volatile) {
9075 asm_statement->is_volatile = true;
9079 add_anchor_token(')');
9080 add_anchor_token(':');
9081 asm_statement->asm_text = parse_string_literals();
9083 if (token.type != ':') {
9084 rem_anchor_token(':');
9089 asm_statement->outputs = parse_asm_arguments(true);
9090 if (token.type != ':') {
9091 rem_anchor_token(':');
9096 asm_statement->inputs = parse_asm_arguments(false);
9097 if (token.type != ':') {
9098 rem_anchor_token(':');
9101 rem_anchor_token(':');
9104 asm_statement->clobbers = parse_asm_clobbers();
9107 rem_anchor_token(')');
9111 if (asm_statement->outputs == NULL) {
9112 /* GCC: An 'asm' instruction without any output operands will be treated
9113 * identically to a volatile 'asm' instruction. */
9114 asm_statement->is_volatile = true;
9119 return create_invalid_statement();
9123 * Parse a case statement.
9125 static statement_t *parse_case_statement(void)
9127 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9128 source_position_t *const pos = &statement->base.source_position;
9132 expression_t *const expression = parse_expression();
9133 statement->case_label.expression = expression;
9134 if (!is_constant_expression(expression)) {
9135 /* This check does not prevent the error message in all cases of an
9136 * prior error while parsing the expression. At least it catches the
9137 * common case of a mistyped enum entry. */
9138 if (is_type_valid(skip_typeref(expression->base.type))) {
9139 errorf(pos, "case label does not reduce to an integer constant");
9141 statement->case_label.is_bad = true;
9143 long const val = fold_constant(expression);
9144 statement->case_label.first_case = val;
9145 statement->case_label.last_case = val;
9149 if (token.type == T_DOTDOTDOT) {
9151 expression_t *const end_range = parse_expression();
9152 statement->case_label.end_range = end_range;
9153 if (!is_constant_expression(end_range)) {
9154 /* This check does not prevent the error message in all cases of an
9155 * prior error while parsing the expression. At least it catches the
9156 * common case of a mistyped enum entry. */
9157 if (is_type_valid(skip_typeref(end_range->base.type))) {
9158 errorf(pos, "case range does not reduce to an integer constant");
9160 statement->case_label.is_bad = true;
9162 long const val = fold_constant(end_range);
9163 statement->case_label.last_case = val;
9165 if (warning.other && val < statement->case_label.first_case) {
9166 statement->case_label.is_empty_range = true;
9167 warningf(pos, "empty range specified");
9173 PUSH_PARENT(statement);
9177 if (current_switch != NULL) {
9178 if (! statement->case_label.is_bad) {
9179 /* Check for duplicate case values */
9180 case_label_statement_t *c = &statement->case_label;
9181 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9182 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9185 if (c->last_case < l->first_case || c->first_case > l->last_case)
9188 errorf(pos, "duplicate case value (previously used %P)",
9189 &l->base.source_position);
9193 /* link all cases into the switch statement */
9194 if (current_switch->last_case == NULL) {
9195 current_switch->first_case = &statement->case_label;
9197 current_switch->last_case->next = &statement->case_label;
9199 current_switch->last_case = &statement->case_label;
9201 errorf(pos, "case label not within a switch statement");
9204 statement_t *const inner_stmt = parse_statement();
9205 statement->case_label.statement = inner_stmt;
9206 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9207 errorf(&inner_stmt->base.source_position, "declaration after case label");
9214 return create_invalid_statement();
9218 * Parse a default statement.
9220 static statement_t *parse_default_statement(void)
9222 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9226 PUSH_PARENT(statement);
9229 if (current_switch != NULL) {
9230 const case_label_statement_t *def_label = current_switch->default_label;
9231 if (def_label != NULL) {
9232 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9233 &def_label->base.source_position);
9235 current_switch->default_label = &statement->case_label;
9237 /* link all cases into the switch statement */
9238 if (current_switch->last_case == NULL) {
9239 current_switch->first_case = &statement->case_label;
9241 current_switch->last_case->next = &statement->case_label;
9243 current_switch->last_case = &statement->case_label;
9246 errorf(&statement->base.source_position,
9247 "'default' label not within a switch statement");
9250 statement_t *const inner_stmt = parse_statement();
9251 statement->case_label.statement = inner_stmt;
9252 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9253 errorf(&inner_stmt->base.source_position, "declaration after default label");
9260 return create_invalid_statement();
9264 * Parse a label statement.
9266 static statement_t *parse_label_statement(void)
9268 assert(token.type == T_IDENTIFIER);
9269 symbol_t *symbol = token.v.symbol;
9270 declaration_t *label = get_label(symbol);
9272 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9273 statement->label.label = label;
9277 PUSH_PARENT(statement);
9279 /* if statement is already set then the label is defined twice,
9280 * otherwise it was just mentioned in a goto/local label declaration so far */
9281 if (label->init.statement != NULL) {
9282 errorf(HERE, "duplicate label '%Y' (declared %P)",
9283 symbol, &label->source_position);
9285 label->source_position = token.source_position;
9286 label->init.statement = statement;
9291 if (token.type == '}') {
9292 /* TODO only warn? */
9293 if (warning.other && false) {
9294 warningf(HERE, "label at end of compound statement");
9295 statement->label.statement = create_empty_statement();
9297 errorf(HERE, "label at end of compound statement");
9298 statement->label.statement = create_invalid_statement();
9300 } else if (token.type == ';') {
9301 /* Eat an empty statement here, to avoid the warning about an empty
9302 * statement after a label. label:; is commonly used to have a label
9303 * before a closing brace. */
9304 statement->label.statement = create_empty_statement();
9307 statement_t *const inner_stmt = parse_statement();
9308 statement->label.statement = inner_stmt;
9309 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9310 errorf(&inner_stmt->base.source_position, "declaration after label");
9314 /* remember the labels in a list for later checking */
9315 if (label_last == NULL) {
9316 label_first = &statement->label;
9318 label_last->next = &statement->label;
9320 label_last = &statement->label;
9327 * Parse an if statement.
9329 static statement_t *parse_if(void)
9331 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9335 PUSH_PARENT(statement);
9337 add_anchor_token('{');
9340 add_anchor_token(')');
9341 expression_t *const expr = parse_expression();
9342 statement->ifs.condition = expr;
9343 mark_decls_read(expr, NULL);
9344 rem_anchor_token(')');
9348 rem_anchor_token('{');
9350 add_anchor_token(T_else);
9351 statement->ifs.true_statement = parse_statement();
9352 rem_anchor_token(T_else);
9354 if (token.type == T_else) {
9356 statement->ifs.false_statement = parse_statement();
9364 * Check that all enums are handled in a switch.
9366 * @param statement the switch statement to check
9368 static void check_enum_cases(const switch_statement_t *statement) {
9369 const type_t *type = skip_typeref(statement->expression->base.type);
9370 if (! is_type_enum(type))
9372 const enum_type_t *enumt = &type->enumt;
9374 /* if we have a default, no warnings */
9375 if (statement->default_label != NULL)
9378 /* FIXME: calculation of value should be done while parsing */
9379 const declaration_t *declaration;
9380 long last_value = -1;
9381 for (declaration = enumt->declaration->next;
9382 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
9383 declaration = declaration->next) {
9384 const expression_t *expression = declaration->init.enum_value;
9385 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9387 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9388 if (l->expression == NULL)
9390 if (l->first_case <= value && value <= l->last_case) {
9396 warningf(&statement->base.source_position,
9397 "enumeration value '%Y' not handled in switch", declaration->symbol);
9404 * Parse a switch statement.
9406 static statement_t *parse_switch(void)
9408 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9412 PUSH_PARENT(statement);
9415 add_anchor_token(')');
9416 expression_t *const expr = parse_expression();
9417 mark_decls_read(expr, NULL);
9418 type_t * type = skip_typeref(expr->base.type);
9419 if (is_type_integer(type)) {
9420 type = promote_integer(type);
9421 if (warning.traditional) {
9422 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9423 warningf(&expr->base.source_position,
9424 "'%T' switch expression not converted to '%T' in ISO C",
9428 } else if (is_type_valid(type)) {
9429 errorf(&expr->base.source_position,
9430 "switch quantity is not an integer, but '%T'", type);
9431 type = type_error_type;
9433 statement->switchs.expression = create_implicit_cast(expr, type);
9435 rem_anchor_token(')');
9437 switch_statement_t *rem = current_switch;
9438 current_switch = &statement->switchs;
9439 statement->switchs.body = parse_statement();
9440 current_switch = rem;
9442 if (warning.switch_default &&
9443 statement->switchs.default_label == NULL) {
9444 warningf(&statement->base.source_position, "switch has no default case");
9446 if (warning.switch_enum)
9447 check_enum_cases(&statement->switchs);
9453 return create_invalid_statement();
9456 static statement_t *parse_loop_body(statement_t *const loop)
9458 statement_t *const rem = current_loop;
9459 current_loop = loop;
9461 statement_t *const body = parse_statement();
9468 * Parse a while statement.
9470 static statement_t *parse_while(void)
9472 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9476 PUSH_PARENT(statement);
9479 add_anchor_token(')');
9480 expression_t *const cond = parse_expression();
9481 statement->whiles.condition = cond;
9482 mark_decls_read(cond, NULL);
9483 rem_anchor_token(')');
9486 statement->whiles.body = parse_loop_body(statement);
9492 return create_invalid_statement();
9496 * Parse a do statement.
9498 static statement_t *parse_do(void)
9500 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9504 PUSH_PARENT(statement);
9506 add_anchor_token(T_while);
9507 statement->do_while.body = parse_loop_body(statement);
9508 rem_anchor_token(T_while);
9512 add_anchor_token(')');
9513 expression_t *const cond = parse_expression();
9514 statement->do_while.condition = cond;
9515 mark_decls_read(cond, NULL);
9516 rem_anchor_token(')');
9524 return create_invalid_statement();
9528 * Parse a for statement.
9530 static statement_t *parse_for(void)
9532 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9536 PUSH_PARENT(statement);
9538 size_t const top = environment_top();
9539 scope_push(&statement->fors.scope);
9542 add_anchor_token(')');
9544 if (token.type != ';') {
9545 if (is_declaration_specifier(&token, false)) {
9546 parse_declaration(record_declaration);
9548 add_anchor_token(';');
9549 expression_t *const init = parse_expression();
9550 statement->fors.initialisation = init;
9551 mark_decls_read(init, DECL_ANY);
9552 if (warning.unused_value && !expression_has_effect(init)) {
9553 warningf(&init->base.source_position,
9554 "initialisation of 'for'-statement has no effect");
9556 rem_anchor_token(';');
9563 if (token.type != ';') {
9564 add_anchor_token(';');
9565 expression_t *const cond = parse_expression();
9566 statement->fors.condition = cond;
9567 mark_decls_read(cond, NULL);
9568 rem_anchor_token(';');
9571 if (token.type != ')') {
9572 expression_t *const step = parse_expression();
9573 statement->fors.step = step;
9574 mark_decls_read(step, DECL_ANY);
9575 if (warning.unused_value && !expression_has_effect(step)) {
9576 warningf(&step->base.source_position,
9577 "step of 'for'-statement has no effect");
9580 rem_anchor_token(')');
9582 statement->fors.body = parse_loop_body(statement);
9584 assert(scope == &statement->fors.scope);
9586 environment_pop_to(top);
9593 rem_anchor_token(')');
9594 assert(scope == &statement->fors.scope);
9596 environment_pop_to(top);
9598 return create_invalid_statement();
9602 * Parse a goto statement.
9604 static statement_t *parse_goto(void)
9606 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9609 if (GNU_MODE && token.type == '*') {
9611 expression_t *expression = parse_expression();
9612 mark_decls_read(expression, NULL);
9614 /* Argh: although documentation say the expression must be of type void *,
9615 * gcc excepts anything that can be casted into void * without error */
9616 type_t *type = expression->base.type;
9618 if (type != type_error_type) {
9619 if (!is_type_pointer(type) && !is_type_integer(type)) {
9620 errorf(&expression->base.source_position,
9621 "cannot convert to a pointer type");
9622 } else if (warning.other && type != type_void_ptr) {
9623 warningf(&expression->base.source_position,
9624 "type of computed goto expression should be 'void*' not '%T'", type);
9626 expression = create_implicit_cast(expression, type_void_ptr);
9629 statement->gotos.expression = expression;
9631 if (token.type != T_IDENTIFIER) {
9633 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9635 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9639 symbol_t *symbol = token.v.symbol;
9642 statement->gotos.label = get_label(symbol);
9645 /* remember the goto's in a list for later checking */
9646 if (goto_last == NULL) {
9647 goto_first = &statement->gotos;
9649 goto_last->next = &statement->gotos;
9651 goto_last = &statement->gotos;
9657 return create_invalid_statement();
9661 * Parse a continue statement.
9663 static statement_t *parse_continue(void)
9665 if (current_loop == NULL) {
9666 errorf(HERE, "continue statement not within loop");
9669 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9679 * Parse a break statement.
9681 static statement_t *parse_break(void)
9683 if (current_switch == NULL && current_loop == NULL) {
9684 errorf(HERE, "break statement not within loop or switch");
9687 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9697 * Parse a __leave statement.
9699 static statement_t *parse_leave_statement(void)
9701 if (current_try == NULL) {
9702 errorf(HERE, "__leave statement not within __try");
9705 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9715 * Check if a given declaration represents a local variable.
9717 static bool is_local_var_declaration(const declaration_t *declaration)
9719 switch ((storage_class_tag_t) declaration->storage_class) {
9720 case STORAGE_CLASS_AUTO:
9721 case STORAGE_CLASS_REGISTER: {
9722 const type_t *type = skip_typeref(declaration->type);
9723 if (is_type_function(type)) {
9735 * Check if a given declaration represents a variable.
9737 static bool is_var_declaration(const declaration_t *declaration)
9739 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9742 const type_t *type = skip_typeref(declaration->type);
9743 return !is_type_function(type);
9747 * Check if a given expression represents a local variable.
9749 static bool is_local_variable(const expression_t *expression)
9751 if (expression->base.kind != EXPR_REFERENCE) {
9754 const declaration_t *declaration = expression->reference.declaration;
9755 return is_local_var_declaration(declaration);
9759 * Check if a given expression represents a local variable and
9760 * return its declaration then, else return NULL.
9762 declaration_t *expr_is_variable(const expression_t *expression)
9764 if (expression->base.kind != EXPR_REFERENCE) {
9767 declaration_t *declaration = expression->reference.declaration;
9768 if (is_var_declaration(declaration))
9774 * Parse a return statement.
9776 static statement_t *parse_return(void)
9780 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9782 expression_t *return_value = NULL;
9783 if (token.type != ';') {
9784 return_value = parse_expression();
9785 mark_decls_read(return_value, NULL);
9788 const type_t *const func_type = current_function->type;
9789 assert(is_type_function(func_type));
9790 type_t *const return_type = skip_typeref(func_type->function.return_type);
9792 if (return_value != NULL) {
9793 type_t *return_value_type = skip_typeref(return_value->base.type);
9795 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
9796 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9797 if (warning.other) {
9798 warningf(&statement->base.source_position,
9799 "'return' with a value, in function returning void");
9801 return_value = NULL;
9803 assign_error_t error = semantic_assign(return_type, return_value);
9804 report_assign_error(error, return_type, return_value, "'return'",
9805 &statement->base.source_position);
9806 return_value = create_implicit_cast(return_value, return_type);
9808 /* check for returning address of a local var */
9809 if (warning.other &&
9810 return_value != NULL &&
9811 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9812 const expression_t *expression = return_value->unary.value;
9813 if (is_local_variable(expression)) {
9814 warningf(&statement->base.source_position,
9815 "function returns address of local variable");
9818 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9819 warningf(&statement->base.source_position,
9820 "'return' without value, in function returning non-void");
9822 statement->returns.value = return_value;
9831 * Parse a declaration statement.
9833 static statement_t *parse_declaration_statement(void)
9835 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9837 declaration_t *before = last_declaration;
9839 parse_external_declaration();
9841 parse_declaration(record_declaration);
9843 if (before == NULL) {
9844 statement->declaration.declarations_begin = scope->declarations;
9846 statement->declaration.declarations_begin = before->next;
9848 statement->declaration.declarations_end = last_declaration;
9854 * Parse an expression statement, ie. expr ';'.
9856 static statement_t *parse_expression_statement(void)
9858 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9860 expression_t *const expr = parse_expression();
9861 statement->expression.expression = expr;
9862 mark_decls_read(expr, DECL_ANY);
9871 * Parse a microsoft __try { } __finally { } or
9872 * __try{ } __except() { }
9874 static statement_t *parse_ms_try_statment(void)
9876 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9879 PUSH_PARENT(statement);
9881 ms_try_statement_t *rem = current_try;
9882 current_try = &statement->ms_try;
9883 statement->ms_try.try_statement = parse_compound_statement(false);
9888 if (token.type == T___except) {
9891 add_anchor_token(')');
9892 expression_t *const expr = parse_expression();
9893 mark_decls_read(expr, NULL);
9894 type_t * type = skip_typeref(expr->base.type);
9895 if (is_type_integer(type)) {
9896 type = promote_integer(type);
9897 } else if (is_type_valid(type)) {
9898 errorf(&expr->base.source_position,
9899 "__expect expression is not an integer, but '%T'", type);
9900 type = type_error_type;
9902 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9903 rem_anchor_token(')');
9905 statement->ms_try.final_statement = parse_compound_statement(false);
9906 } else if (token.type == T__finally) {
9908 statement->ms_try.final_statement = parse_compound_statement(false);
9910 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9911 return create_invalid_statement();
9915 return create_invalid_statement();
9918 static statement_t *parse_empty_statement(void)
9920 if (warning.empty_statement) {
9921 warningf(HERE, "statement is empty");
9923 statement_t *const statement = create_empty_statement();
9928 static statement_t *parse_local_label_declaration(void) {
9929 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9933 declaration_t *begin = NULL, *end = NULL;
9936 if (token.type != T_IDENTIFIER) {
9937 parse_error_expected("while parsing local label declaration",
9938 T_IDENTIFIER, NULL);
9941 symbol_t *symbol = token.v.symbol;
9942 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9943 if (declaration != NULL) {
9944 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9945 symbol, &declaration->source_position);
9947 declaration = allocate_declaration_zero();
9948 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9949 declaration->source_position = token.source_position;
9950 declaration->symbol = symbol;
9951 declaration->parent_scope = scope;
9952 declaration->init.statement = NULL;
9955 end->next = declaration;
9958 begin = declaration;
9960 local_label_push(declaration);
9964 if (token.type != ',')
9970 statement->declaration.declarations_begin = begin;
9971 statement->declaration.declarations_end = end;
9976 * Parse a statement.
9977 * There's also parse_statement() which additionally checks for
9978 * "statement has no effect" warnings
9980 static statement_t *intern_parse_statement(void)
9982 statement_t *statement = NULL;
9984 /* declaration or statement */
9985 add_anchor_token(';');
9986 switch (token.type) {
9987 case T_IDENTIFIER: {
9988 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9989 if (la1_type == ':') {
9990 statement = parse_label_statement();
9991 } else if (is_typedef_symbol(token.v.symbol)) {
9992 statement = parse_declaration_statement();
9993 } else switch (la1_type) {
9995 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9996 goto expression_statment;
10001 statement = parse_declaration_statement();
10005 expression_statment:
10006 statement = parse_expression_statement();
10012 case T___extension__:
10013 /* This can be a prefix to a declaration or an expression statement.
10014 * We simply eat it now and parse the rest with tail recursion. */
10017 } while (token.type == T___extension__);
10018 bool old_gcc_extension = in_gcc_extension;
10019 in_gcc_extension = true;
10020 statement = parse_statement();
10021 in_gcc_extension = old_gcc_extension;
10025 statement = parse_declaration_statement();
10029 statement = parse_local_label_declaration();
10032 case ';': statement = parse_empty_statement(); break;
10033 case '{': statement = parse_compound_statement(false); break;
10034 case T___leave: statement = parse_leave_statement(); break;
10035 case T___try: statement = parse_ms_try_statment(); break;
10036 case T_asm: statement = parse_asm_statement(); break;
10037 case T_break: statement = parse_break(); break;
10038 case T_case: statement = parse_case_statement(); break;
10039 case T_continue: statement = parse_continue(); break;
10040 case T_default: statement = parse_default_statement(); break;
10041 case T_do: statement = parse_do(); break;
10042 case T_for: statement = parse_for(); break;
10043 case T_goto: statement = parse_goto(); break;
10044 case T_if: statement = parse_if(); break;
10045 case T_return: statement = parse_return(); break;
10046 case T_switch: statement = parse_switch(); break;
10047 case T_while: statement = parse_while(); break;
10050 statement = parse_expression_statement();
10054 errorf(HERE, "unexpected token %K while parsing statement", &token);
10055 statement = create_invalid_statement();
10060 rem_anchor_token(';');
10062 assert(statement != NULL
10063 && statement->base.source_position.input_name != NULL);
10069 * parse a statement and emits "statement has no effect" warning if needed
10070 * (This is really a wrapper around intern_parse_statement with check for 1
10071 * single warning. It is needed, because for statement expressions we have
10072 * to avoid the warning on the last statement)
10074 static statement_t *parse_statement(void)
10076 statement_t *statement = intern_parse_statement();
10078 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10079 expression_t *expression = statement->expression.expression;
10080 if (!expression_has_effect(expression)) {
10081 warningf(&expression->base.source_position,
10082 "statement has no effect");
10090 * Parse a compound statement.
10092 static statement_t *parse_compound_statement(bool inside_expression_statement)
10094 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10096 PUSH_PARENT(statement);
10099 add_anchor_token('}');
10101 size_t const top = environment_top();
10102 size_t const top_local = local_label_top();
10103 scope_push(&statement->compound.scope);
10105 statement_t **anchor = &statement->compound.statements;
10106 bool only_decls_so_far = true;
10107 while (token.type != '}') {
10108 if (token.type == T_EOF) {
10109 errorf(&statement->base.source_position,
10110 "EOF while parsing compound statement");
10113 statement_t *sub_statement = intern_parse_statement();
10114 if (is_invalid_statement(sub_statement)) {
10115 /* an error occurred. if we are at an anchor, return */
10121 if (warning.declaration_after_statement) {
10122 if (sub_statement->kind != STATEMENT_DECLARATION) {
10123 only_decls_so_far = false;
10124 } else if (!only_decls_so_far) {
10125 warningf(&sub_statement->base.source_position,
10126 "ISO C90 forbids mixed declarations and code");
10130 *anchor = sub_statement;
10132 while (sub_statement->base.next != NULL)
10133 sub_statement = sub_statement->base.next;
10135 anchor = &sub_statement->base.next;
10139 /* look over all statements again to produce no effect warnings */
10140 if (warning.unused_value) {
10141 statement_t *sub_statement = statement->compound.statements;
10142 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10143 if (sub_statement->kind != STATEMENT_EXPRESSION)
10145 /* don't emit a warning for the last expression in an expression
10146 * statement as it has always an effect */
10147 if (inside_expression_statement && sub_statement->base.next == NULL)
10150 expression_t *expression = sub_statement->expression.expression;
10151 if (!expression_has_effect(expression)) {
10152 warningf(&expression->base.source_position,
10153 "statement has no effect");
10159 rem_anchor_token('}');
10160 assert(scope == &statement->compound.scope);
10162 environment_pop_to(top);
10163 local_label_pop_to(top_local);
10170 * Initialize builtin types.
10172 static void initialize_builtin_types(void)
10174 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
10175 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
10176 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
10177 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
10178 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
10179 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
10180 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
10181 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
10183 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
10184 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
10185 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
10186 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
10188 /* const version of wchar_t */
10189 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF);
10190 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
10191 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
10193 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
10197 * Check for unused global static functions and variables
10199 static void check_unused_globals(void)
10201 if (!warning.unused_function && !warning.unused_variable)
10204 for (const declaration_t *decl = file_scope->declarations; decl != NULL; decl = decl->next) {
10206 decl->modifiers & DM_UNUSED ||
10207 decl->modifiers & DM_USED ||
10208 decl->storage_class != STORAGE_CLASS_STATIC)
10211 type_t *const type = decl->type;
10213 if (is_type_function(skip_typeref(type))) {
10214 if (!warning.unused_function || decl->is_inline)
10217 s = (decl->init.statement != NULL ? "defined" : "declared");
10219 if (!warning.unused_variable)
10225 warningf(&decl->source_position, "'%#T' %s but not used",
10226 type, decl->symbol, s);
10230 static void parse_global_asm(void)
10232 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10237 statement->asms.asm_text = parse_string_literals();
10238 statement->base.next = unit->global_asm;
10239 unit->global_asm = statement;
10248 * Parse a translation unit.
10250 static void parse_translation_unit(void)
10252 add_anchor_token(T_EOF);
10255 unsigned char token_anchor_copy[T_LAST_TOKEN];
10256 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10260 bool anchor_leak = false;
10261 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10262 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10264 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10265 anchor_leak = true;
10268 if (in_gcc_extension) {
10269 errorf(HERE, "Leaked __extension__");
10270 anchor_leak = true;
10277 switch (token.type) {
10280 case T___extension__:
10281 parse_external_declaration();
10285 parse_global_asm();
10289 rem_anchor_token(T_EOF);
10293 if (!strict_mode) {
10295 warningf(HERE, "stray ';' outside of function");
10302 errorf(HERE, "stray %K outside of function", &token);
10303 if (token.type == '(' || token.type == '{' || token.type == '[')
10304 eat_until_matching_token(token.type);
10314 * @return the translation unit or NULL if errors occurred.
10316 void start_parsing(void)
10318 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10319 label_stack = NEW_ARR_F(stack_entry_t, 0);
10320 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10321 diagnostic_count = 0;
10325 type_set_output(stderr);
10326 ast_set_output(stderr);
10328 assert(unit == NULL);
10329 unit = allocate_ast_zero(sizeof(unit[0]));
10331 assert(file_scope == NULL);
10332 file_scope = &unit->scope;
10334 assert(scope == NULL);
10335 scope_push(&unit->scope);
10337 initialize_builtin_types();
10340 translation_unit_t *finish_parsing(void)
10342 /* do NOT use scope_pop() here, this will crash, will it by hand */
10343 assert(scope == &unit->scope);
10345 last_declaration = NULL;
10347 assert(file_scope == &unit->scope);
10348 check_unused_globals();
10351 DEL_ARR_F(environment_stack);
10352 DEL_ARR_F(label_stack);
10353 DEL_ARR_F(local_label_stack);
10355 translation_unit_t *result = unit;
10362 lookahead_bufpos = 0;
10363 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10366 parse_translation_unit();
10370 * Initialize the parser.
10372 void init_parser(void)
10374 sym_anonymous = symbol_table_insert("<anonymous>");
10376 if (c_mode & _MS) {
10377 /* add predefined symbols for extended-decl-modifier */
10378 sym_align = symbol_table_insert("align");
10379 sym_allocate = symbol_table_insert("allocate");
10380 sym_dllimport = symbol_table_insert("dllimport");
10381 sym_dllexport = symbol_table_insert("dllexport");
10382 sym_naked = symbol_table_insert("naked");
10383 sym_noinline = symbol_table_insert("noinline");
10384 sym_noreturn = symbol_table_insert("noreturn");
10385 sym_nothrow = symbol_table_insert("nothrow");
10386 sym_novtable = symbol_table_insert("novtable");
10387 sym_property = symbol_table_insert("property");
10388 sym_get = symbol_table_insert("get");
10389 sym_put = symbol_table_insert("put");
10390 sym_selectany = symbol_table_insert("selectany");
10391 sym_thread = symbol_table_insert("thread");
10392 sym_uuid = symbol_table_insert("uuid");
10393 sym_deprecated = symbol_table_insert("deprecated");
10394 sym_restrict = symbol_table_insert("restrict");
10395 sym_noalias = symbol_table_insert("noalias");
10397 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10399 init_expression_parsers();
10400 obstack_init(&temp_obst);
10402 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10403 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10407 * Terminate the parser.
10409 void exit_parser(void)
10411 obstack_free(&temp_obst, NULL);