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: \
303 * Allocate an AST node with given size and
304 * initialize all fields with zero.
306 static void *allocate_ast_zero(size_t size)
308 void *res = allocate_ast(size);
309 memset(res, 0, size);
313 static declaration_t *allocate_declaration_zero(void)
315 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
316 declaration->type = type_error_type;
317 declaration->alignment = 0;
322 * Returns the size of a statement node.
324 * @param kind the statement kind
326 static size_t get_statement_struct_size(statement_kind_t kind)
328 static const size_t sizes[] = {
329 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
330 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
331 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
332 [STATEMENT_RETURN] = sizeof(return_statement_t),
333 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
334 [STATEMENT_IF] = sizeof(if_statement_t),
335 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
336 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
337 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
338 [STATEMENT_BREAK] = sizeof(statement_base_t),
339 [STATEMENT_GOTO] = sizeof(goto_statement_t),
340 [STATEMENT_LABEL] = sizeof(label_statement_t),
341 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
342 [STATEMENT_WHILE] = sizeof(while_statement_t),
343 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
344 [STATEMENT_FOR] = sizeof(for_statement_t),
345 [STATEMENT_ASM] = sizeof(asm_statement_t),
346 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
347 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
349 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
350 assert(sizes[kind] != 0);
355 * Returns the size of an expression node.
357 * @param kind the expression kind
359 static size_t get_expression_struct_size(expression_kind_t kind)
361 static const size_t sizes[] = {
362 [EXPR_INVALID] = sizeof(expression_base_t),
363 [EXPR_REFERENCE] = sizeof(reference_expression_t),
364 [EXPR_CONST] = sizeof(const_expression_t),
365 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
366 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
367 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
368 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
369 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
370 [EXPR_CALL] = sizeof(call_expression_t),
371 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
372 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
373 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
374 [EXPR_SELECT] = sizeof(select_expression_t),
375 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
376 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
377 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
378 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
379 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
380 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
381 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
382 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
383 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
384 [EXPR_VA_START] = sizeof(va_start_expression_t),
385 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
386 [EXPR_STATEMENT] = sizeof(statement_expression_t),
387 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
389 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
390 return sizes[EXPR_UNARY_FIRST];
392 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
393 return sizes[EXPR_BINARY_FIRST];
395 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
396 assert(sizes[kind] != 0);
401 * Allocate a statement node of given kind and initialize all
404 static statement_t *allocate_statement_zero(statement_kind_t kind)
406 size_t size = get_statement_struct_size(kind);
407 statement_t *res = allocate_ast_zero(size);
409 res->base.kind = kind;
410 res->base.parent = current_parent;
411 res->base.source_position = token.source_position;
416 * Allocate an expression node of given kind and initialize all
419 static expression_t *allocate_expression_zero(expression_kind_t kind)
421 size_t size = get_expression_struct_size(kind);
422 expression_t *res = allocate_ast_zero(size);
424 res->base.kind = kind;
425 res->base.type = type_error_type;
430 * Creates a new invalid expression.
432 static expression_t *create_invalid_expression(void)
434 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
435 expression->base.source_position = token.source_position;
440 * Creates a new invalid statement.
442 static statement_t *create_invalid_statement(void)
444 return allocate_statement_zero(STATEMENT_INVALID);
448 * Allocate a new empty statement.
450 static statement_t *create_empty_statement(void)
452 return allocate_statement_zero(STATEMENT_EMPTY);
456 * Returns the size of a type node.
458 * @param kind the type kind
460 static size_t get_type_struct_size(type_kind_t kind)
462 static const size_t sizes[] = {
463 [TYPE_ATOMIC] = sizeof(atomic_type_t),
464 [TYPE_COMPLEX] = sizeof(complex_type_t),
465 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
466 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
467 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
468 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
469 [TYPE_ENUM] = sizeof(enum_type_t),
470 [TYPE_FUNCTION] = sizeof(function_type_t),
471 [TYPE_POINTER] = sizeof(pointer_type_t),
472 [TYPE_ARRAY] = sizeof(array_type_t),
473 [TYPE_BUILTIN] = sizeof(builtin_type_t),
474 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
475 [TYPE_TYPEOF] = sizeof(typeof_type_t),
477 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
478 assert(kind <= TYPE_TYPEOF);
479 assert(sizes[kind] != 0);
484 * Allocate a type node of given kind and initialize all
487 * @param kind type kind to allocate
489 static type_t *allocate_type_zero(type_kind_t kind)
491 size_t size = get_type_struct_size(kind);
492 type_t *res = obstack_alloc(type_obst, size);
493 memset(res, 0, size);
494 res->base.kind = kind;
500 * Returns the size of an initializer node.
502 * @param kind the initializer kind
504 static size_t get_initializer_size(initializer_kind_t kind)
506 static const size_t sizes[] = {
507 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
508 [INITIALIZER_STRING] = sizeof(initializer_string_t),
509 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
510 [INITIALIZER_LIST] = sizeof(initializer_list_t),
511 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
513 assert(kind < sizeof(sizes) / sizeof(*sizes));
514 assert(sizes[kind] != 0);
519 * Allocate an initializer node of given kind and initialize all
522 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
524 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
531 * Free a type from the type obstack.
533 static void free_type(void *type)
535 obstack_free(type_obst, type);
539 * Returns the index of the top element of the environment stack.
541 static size_t environment_top(void)
543 return ARR_LEN(environment_stack);
547 * Returns the index of the top element of the global label stack.
549 static size_t label_top(void)
551 return ARR_LEN(label_stack);
555 * Returns the index of the top element of the local label stack.
557 static size_t local_label_top(void)
559 return ARR_LEN(local_label_stack);
563 * Return the next token.
565 static inline void next_token(void)
567 token = lookahead_buffer[lookahead_bufpos];
568 lookahead_buffer[lookahead_bufpos] = lexer_token;
571 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
574 print_token(stderr, &token);
575 fprintf(stderr, "\n");
580 * Return the next token with a given lookahead.
582 static inline const token_t *look_ahead(int num)
584 assert(num > 0 && num <= MAX_LOOKAHEAD);
585 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
586 return &lookahead_buffer[pos];
590 * Adds a token to the token anchor set (a multi-set).
592 static void add_anchor_token(int token_type)
594 assert(0 <= token_type && token_type < T_LAST_TOKEN);
595 ++token_anchor_set[token_type];
598 static int save_and_reset_anchor_state(int token_type)
600 assert(0 <= token_type && token_type < T_LAST_TOKEN);
601 int count = token_anchor_set[token_type];
602 token_anchor_set[token_type] = 0;
606 static void restore_anchor_state(int token_type, int count)
608 assert(0 <= token_type && token_type < T_LAST_TOKEN);
609 token_anchor_set[token_type] = count;
613 * Remove a token from the token anchor set (a multi-set).
615 static void rem_anchor_token(int token_type)
617 assert(0 <= token_type && token_type < T_LAST_TOKEN);
618 assert(token_anchor_set[token_type] != 0);
619 --token_anchor_set[token_type];
622 static bool at_anchor(void)
626 return token_anchor_set[token.type];
630 * Eat tokens until a matching token is found.
632 static void eat_until_matching_token(int type)
636 case '(': end_token = ')'; break;
637 case '{': end_token = '}'; break;
638 case '[': end_token = ']'; break;
639 default: end_token = type; break;
642 unsigned parenthesis_count = 0;
643 unsigned brace_count = 0;
644 unsigned bracket_count = 0;
645 while (token.type != end_token ||
646 parenthesis_count != 0 ||
648 bracket_count != 0) {
649 switch (token.type) {
651 case '(': ++parenthesis_count; break;
652 case '{': ++brace_count; break;
653 case '[': ++bracket_count; break;
656 if (parenthesis_count > 0)
666 if (bracket_count > 0)
669 if (token.type == end_token &&
670 parenthesis_count == 0 &&
684 * Eat input tokens until an anchor is found.
686 static void eat_until_anchor(void)
688 while (token_anchor_set[token.type] == 0) {
689 if (token.type == '(' || token.type == '{' || token.type == '[')
690 eat_until_matching_token(token.type);
695 static void eat_block(void)
697 eat_until_matching_token('{');
698 if (token.type == '}')
702 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
705 * Report a parse error because an expected token was not found.
708 #if defined __GNUC__ && __GNUC__ >= 4
709 __attribute__((sentinel))
711 void parse_error_expected(const char *message, ...)
713 if (message != NULL) {
714 errorf(HERE, "%s", message);
717 va_start(ap, message);
718 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
723 * Report a type error.
725 static void type_error(const char *msg, const source_position_t *source_position,
728 errorf(source_position, "%s, but found type '%T'", msg, type);
732 * Report an incompatible type.
734 static void type_error_incompatible(const char *msg,
735 const source_position_t *source_position, type_t *type1, type_t *type2)
737 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
742 * Expect the the current token is the expected token.
743 * If not, generate an error, eat the current statement,
744 * and goto the end_error label.
746 #define expect(expected) \
748 if (UNLIKELY(token.type != (expected))) { \
749 parse_error_expected(NULL, (expected), NULL); \
750 add_anchor_token(expected); \
751 eat_until_anchor(); \
752 if (token.type == expected) \
754 rem_anchor_token(expected); \
760 static void scope_push(scope_t *new_scope)
763 scope->last_declaration = last_declaration;
764 new_scope->depth = scope->depth + 1;
766 new_scope->parent = scope;
769 last_declaration = new_scope->last_declaration;
772 static void scope_pop(void)
774 scope->last_declaration = last_declaration;
775 scope = scope->parent;
776 last_declaration = scope->last_declaration;
780 * Search a symbol in a given namespace and returns its declaration or
781 * NULL if this symbol was not found.
783 static declaration_t *get_declaration(const symbol_t *const symbol,
784 const namespace_t namespc)
786 declaration_t *declaration = symbol->declaration;
787 for( ; declaration != NULL; declaration = declaration->symbol_next) {
788 if (declaration->namespc == namespc)
796 * pushs an environment_entry on the environment stack and links the
797 * corresponding symbol to the new entry
799 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
801 symbol_t *symbol = declaration->symbol;
802 namespace_t namespc = (namespace_t) declaration->namespc;
804 /* replace/add declaration into declaration list of the symbol */
805 declaration_t **anchor;
807 for (anchor = &symbol->declaration;; anchor = &iter->symbol_next) {
812 /* replace an entry? */
813 if (iter->namespc == namespc) {
814 declaration->symbol_next = iter->symbol_next;
818 *anchor = declaration;
820 /* remember old declaration */
822 entry.symbol = symbol;
823 entry.old_declaration = iter;
824 entry.namespc = (unsigned short) namespc;
825 ARR_APP1(stack_entry_t, *stack_ptr, entry);
829 * Push a declaration on the environment stack.
831 * @param declaration the declaration
833 static void environment_push(declaration_t *declaration)
835 assert(declaration->source_position.input_name != NULL);
836 assert(declaration->parent_scope != NULL);
837 stack_push(&environment_stack, declaration);
841 * Push a declaration on the global label stack.
843 * @param declaration the declaration
845 static void label_push(declaration_t *declaration)
847 declaration->parent_scope = ¤t_function->scope;
848 stack_push(&label_stack, declaration);
852 * Push a declaration of the local label stack.
854 * @param declaration the declaration
856 static void local_label_push(declaration_t *declaration)
858 assert(declaration->parent_scope != NULL);
859 stack_push(&local_label_stack, declaration);
863 * pops symbols from the environment stack until @p new_top is the top element
865 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
867 stack_entry_t *stack = *stack_ptr;
868 size_t top = ARR_LEN(stack);
871 assert(new_top <= top);
875 for(i = top; i > new_top; --i) {
876 stack_entry_t *entry = &stack[i - 1];
878 declaration_t *old_declaration = entry->old_declaration;
879 symbol_t *symbol = entry->symbol;
880 namespace_t namespc = (namespace_t)entry->namespc;
882 /* replace/remove declaration */
883 declaration_t **anchor;
885 for (anchor = &symbol->declaration;; anchor = &iter->symbol_next) {
887 assert(iter != NULL);
888 /* replace an entry? */
889 if (iter->namespc == namespc)
893 /* Not all declarations adhere scopes (e.g. jump labels), so this
894 * correction is necessary */
895 if (old_declaration != NULL) {
896 old_declaration->symbol_next = iter->symbol_next;
897 *anchor = old_declaration;
899 *anchor = iter->symbol_next;
903 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
907 * Pop all entries from the environment stack until the new_top
910 * @param new_top the new stack top
912 static void environment_pop_to(size_t new_top)
914 stack_pop_to(&environment_stack, new_top);
918 * Pop all entries from the global label stack until the new_top
921 * @param new_top the new stack top
923 static void label_pop_to(size_t new_top)
925 stack_pop_to(&label_stack, new_top);
929 * Pop all entries from the local label stack until the new_top
932 * @param new_top the new stack top
934 static void local_label_pop_to(size_t new_top)
936 stack_pop_to(&local_label_stack, new_top);
940 static int get_akind_rank(atomic_type_kind_t akind)
945 static int get_rank(const type_t *type)
947 assert(!is_typeref(type));
948 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
949 * and esp. footnote 108). However we can't fold constants (yet), so we
950 * can't decide whether unsigned int is possible, while int always works.
951 * (unsigned int would be preferable when possible... for stuff like
952 * struct { enum { ... } bla : 4; } ) */
953 if (type->kind == TYPE_ENUM)
954 return get_akind_rank(ATOMIC_TYPE_INT);
956 assert(type->kind == TYPE_ATOMIC);
957 return get_akind_rank(type->atomic.akind);
960 static type_t *promote_integer(type_t *type)
962 if (type->kind == TYPE_BITFIELD)
963 type = type->bitfield.base_type;
965 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
972 * Create a cast expression.
974 * @param expression the expression to cast
975 * @param dest_type the destination type
977 static expression_t *create_cast_expression(expression_t *expression,
980 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
982 cast->unary.value = expression;
983 cast->base.type = dest_type;
989 * Check if a given expression represents the 0 pointer constant.
991 static bool is_null_pointer_constant(const expression_t *expression)
993 /* skip void* cast */
994 if (expression->kind == EXPR_UNARY_CAST
995 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
996 expression = expression->unary.value;
999 /* TODO: not correct yet, should be any constant integer expression
1000 * which evaluates to 0 */
1001 if (expression->kind != EXPR_CONST)
1004 type_t *const type = skip_typeref(expression->base.type);
1005 if (!is_type_integer(type))
1008 return expression->conste.v.int_value == 0;
1012 * Create an implicit cast expression.
1014 * @param expression the expression to cast
1015 * @param dest_type the destination type
1017 static expression_t *create_implicit_cast(expression_t *expression,
1020 type_t *const source_type = expression->base.type;
1022 if (source_type == dest_type)
1025 return create_cast_expression(expression, dest_type);
1028 typedef enum assign_error_t {
1030 ASSIGN_ERROR_INCOMPATIBLE,
1031 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1032 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1033 ASSIGN_WARNING_POINTER_FROM_INT,
1034 ASSIGN_WARNING_INT_FROM_POINTER
1037 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1038 const expression_t *const right,
1039 const char *context,
1040 const source_position_t *source_position)
1042 type_t *const orig_type_right = right->base.type;
1043 type_t *const type_left = skip_typeref(orig_type_left);
1044 type_t *const type_right = skip_typeref(orig_type_right);
1047 case ASSIGN_SUCCESS:
1049 case ASSIGN_ERROR_INCOMPATIBLE:
1050 errorf(source_position,
1051 "destination type '%T' in %s is incompatible with type '%T'",
1052 orig_type_left, context, orig_type_right);
1055 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1056 if (warning.other) {
1057 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1058 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1060 /* the left type has all qualifiers from the right type */
1061 unsigned missing_qualifiers
1062 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1063 warningf(source_position,
1064 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1065 orig_type_left, context, orig_type_right, missing_qualifiers);
1070 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1071 if (warning.other) {
1072 warningf(source_position,
1073 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1074 orig_type_left, context, right, orig_type_right);
1078 case ASSIGN_WARNING_POINTER_FROM_INT:
1079 if (warning.other) {
1080 warningf(source_position,
1081 "%s makes pointer '%T' from integer '%T' without a cast",
1082 context, orig_type_left, orig_type_right);
1086 case ASSIGN_WARNING_INT_FROM_POINTER:
1087 if (warning.other) {
1088 warningf(source_position,
1089 "%s makes integer '%T' from pointer '%T' without a cast",
1090 context, orig_type_left, orig_type_right);
1095 panic("invalid error value");
1099 /** Implements the rules from § 6.5.16.1 */
1100 static assign_error_t semantic_assign(type_t *orig_type_left,
1101 const expression_t *const right)
1103 type_t *const orig_type_right = right->base.type;
1104 type_t *const type_left = skip_typeref(orig_type_left);
1105 type_t *const type_right = skip_typeref(orig_type_right);
1107 if (is_type_pointer(type_left)) {
1108 if (is_null_pointer_constant(right)) {
1109 return ASSIGN_SUCCESS;
1110 } else if (is_type_pointer(type_right)) {
1111 type_t *points_to_left
1112 = skip_typeref(type_left->pointer.points_to);
1113 type_t *points_to_right
1114 = skip_typeref(type_right->pointer.points_to);
1115 assign_error_t res = ASSIGN_SUCCESS;
1117 /* the left type has all qualifiers from the right type */
1118 unsigned missing_qualifiers
1119 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1120 if (missing_qualifiers != 0) {
1121 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1124 points_to_left = get_unqualified_type(points_to_left);
1125 points_to_right = get_unqualified_type(points_to_right);
1127 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1130 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1131 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1132 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1135 if (!types_compatible(points_to_left, points_to_right)) {
1136 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1140 } else if (is_type_integer(type_right)) {
1141 return ASSIGN_WARNING_POINTER_FROM_INT;
1143 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1144 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1145 && is_type_pointer(type_right))) {
1146 return ASSIGN_SUCCESS;
1147 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1148 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1149 type_t *const unqual_type_left = get_unqualified_type(type_left);
1150 type_t *const unqual_type_right = get_unqualified_type(type_right);
1151 if (types_compatible(unqual_type_left, unqual_type_right)) {
1152 return ASSIGN_SUCCESS;
1154 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1155 return ASSIGN_WARNING_INT_FROM_POINTER;
1158 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1159 return ASSIGN_SUCCESS;
1161 return ASSIGN_ERROR_INCOMPATIBLE;
1164 static expression_t *parse_constant_expression(void)
1166 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1168 if (!is_constant_expression(result)) {
1169 errorf(&result->base.source_position,
1170 "expression '%E' is not constant\n", result);
1176 static expression_t *parse_assignment_expression(void)
1178 return parse_sub_expression(PREC_ASSIGNMENT);
1181 static type_t *make_global_typedef(const char *name, type_t *type)
1183 symbol_t *const symbol = symbol_table_insert(name);
1185 declaration_t *const declaration = allocate_declaration_zero();
1186 declaration->namespc = NAMESPACE_NORMAL;
1187 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1188 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1189 declaration->type = type;
1190 declaration->symbol = symbol;
1191 declaration->source_position = builtin_source_position;
1192 declaration->implicit = true;
1194 record_declaration(declaration, false);
1196 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF);
1197 typedef_type->typedeft.declaration = declaration;
1199 return typedef_type;
1202 static string_t parse_string_literals(void)
1204 assert(token.type == T_STRING_LITERAL);
1205 string_t result = token.v.string;
1209 while (token.type == T_STRING_LITERAL) {
1210 result = concat_strings(&result, &token.v.string);
1217 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1218 [GNU_AK_CONST] = "const",
1219 [GNU_AK_VOLATILE] = "volatile",
1220 [GNU_AK_CDECL] = "cdecl",
1221 [GNU_AK_STDCALL] = "stdcall",
1222 [GNU_AK_FASTCALL] = "fastcall",
1223 [GNU_AK_DEPRECATED] = "deprecated",
1224 [GNU_AK_NOINLINE] = "noinline",
1225 [GNU_AK_NORETURN] = "noreturn",
1226 [GNU_AK_NAKED] = "naked",
1227 [GNU_AK_PURE] = "pure",
1228 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1229 [GNU_AK_MALLOC] = "malloc",
1230 [GNU_AK_WEAK] = "weak",
1231 [GNU_AK_CONSTRUCTOR] = "constructor",
1232 [GNU_AK_DESTRUCTOR] = "destructor",
1233 [GNU_AK_NOTHROW] = "nothrow",
1234 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1235 [GNU_AK_COMMON] = "common",
1236 [GNU_AK_NOCOMMON] = "nocommon",
1237 [GNU_AK_PACKED] = "packed",
1238 [GNU_AK_SHARED] = "shared",
1239 [GNU_AK_NOTSHARED] = "notshared",
1240 [GNU_AK_USED] = "used",
1241 [GNU_AK_UNUSED] = "unused",
1242 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1243 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1244 [GNU_AK_LONGCALL] = "longcall",
1245 [GNU_AK_SHORTCALL] = "shortcall",
1246 [GNU_AK_LONG_CALL] = "long_call",
1247 [GNU_AK_SHORT_CALL] = "short_call",
1248 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1249 [GNU_AK_INTERRUPT] = "interrupt",
1250 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1251 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1252 [GNU_AK_NESTING] = "nesting",
1253 [GNU_AK_NEAR] = "near",
1254 [GNU_AK_FAR] = "far",
1255 [GNU_AK_SIGNAL] = "signal",
1256 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1257 [GNU_AK_TINY_DATA] = "tiny_data",
1258 [GNU_AK_SAVEALL] = "saveall",
1259 [GNU_AK_FLATTEN] = "flatten",
1260 [GNU_AK_SSEREGPARM] = "sseregparm",
1261 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1262 [GNU_AK_RETURN_TWICE] = "return_twice",
1263 [GNU_AK_MAY_ALIAS] = "may_alias",
1264 [GNU_AK_MS_STRUCT] = "ms_struct",
1265 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1266 [GNU_AK_DLLIMPORT] = "dllimport",
1267 [GNU_AK_DLLEXPORT] = "dllexport",
1268 [GNU_AK_ALIGNED] = "aligned",
1269 [GNU_AK_ALIAS] = "alias",
1270 [GNU_AK_SECTION] = "section",
1271 [GNU_AK_FORMAT] = "format",
1272 [GNU_AK_FORMAT_ARG] = "format_arg",
1273 [GNU_AK_WEAKREF] = "weakref",
1274 [GNU_AK_NONNULL] = "nonnull",
1275 [GNU_AK_TLS_MODEL] = "tls_model",
1276 [GNU_AK_VISIBILITY] = "visibility",
1277 [GNU_AK_REGPARM] = "regparm",
1278 [GNU_AK_MODE] = "mode",
1279 [GNU_AK_MODEL] = "model",
1280 [GNU_AK_TRAP_EXIT] = "trap_exit",
1281 [GNU_AK_SP_SWITCH] = "sp_switch",
1282 [GNU_AK_SENTINEL] = "sentinel"
1286 * compare two string, ignoring double underscores on the second.
1288 static int strcmp_underscore(const char *s1, const char *s2)
1290 if (s2[0] == '_' && s2[1] == '_') {
1291 size_t len2 = strlen(s2);
1292 size_t len1 = strlen(s1);
1293 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1294 return strncmp(s1, s2+2, len2-4);
1298 return strcmp(s1, s2);
1302 * Allocate a new gnu temporal attribute.
1304 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1306 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1307 attribute->kind = kind;
1308 attribute->next = NULL;
1309 attribute->invalid = false;
1310 attribute->have_arguments = false;
1316 * parse one constant expression argument.
1318 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1320 expression_t *expression;
1321 add_anchor_token(')');
1322 expression = parse_constant_expression();
1323 rem_anchor_token(')');
1325 attribute->u.argument = fold_constant(expression);
1328 attribute->invalid = true;
1332 * parse a list of constant expressions arguments.
1334 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1336 argument_list_t **list = &attribute->u.arguments;
1337 argument_list_t *entry;
1338 expression_t *expression;
1339 add_anchor_token(')');
1340 add_anchor_token(',');
1342 expression = parse_constant_expression();
1343 entry = obstack_alloc(&temp_obst, sizeof(entry));
1344 entry->argument = fold_constant(expression);
1347 list = &entry->next;
1348 if (token.type != ',')
1352 rem_anchor_token(',');
1353 rem_anchor_token(')');
1357 attribute->invalid = true;
1361 * parse one string literal argument.
1363 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1366 add_anchor_token('(');
1367 if (token.type != T_STRING_LITERAL) {
1368 parse_error_expected("while parsing attribute directive",
1369 T_STRING_LITERAL, NULL);
1372 *string = parse_string_literals();
1373 rem_anchor_token('(');
1377 attribute->invalid = true;
1381 * parse one tls model.
1383 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1385 static const char *const tls_models[] = {
1391 string_t string = { NULL, 0 };
1392 parse_gnu_attribute_string_arg(attribute, &string);
1393 if (string.begin != NULL) {
1394 for(size_t i = 0; i < 4; ++i) {
1395 if (strcmp(tls_models[i], string.begin) == 0) {
1396 attribute->u.value = i;
1400 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1402 attribute->invalid = true;
1406 * parse one tls model.
1408 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1410 static const char *const visibilities[] = {
1416 string_t string = { NULL, 0 };
1417 parse_gnu_attribute_string_arg(attribute, &string);
1418 if (string.begin != NULL) {
1419 for(size_t i = 0; i < 4; ++i) {
1420 if (strcmp(visibilities[i], string.begin) == 0) {
1421 attribute->u.value = i;
1425 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1427 attribute->invalid = true;
1431 * parse one (code) model.
1433 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1435 static const char *const visibilities[] = {
1440 string_t string = { NULL, 0 };
1441 parse_gnu_attribute_string_arg(attribute, &string);
1442 if (string.begin != NULL) {
1443 for(int i = 0; i < 3; ++i) {
1444 if (strcmp(visibilities[i], string.begin) == 0) {
1445 attribute->u.value = i;
1449 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1451 attribute->invalid = true;
1454 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1456 /* TODO: find out what is allowed here... */
1458 /* at least: byte, word, pointer, list of machine modes
1459 * __XXX___ is interpreted as XXX */
1460 add_anchor_token(')');
1462 if (token.type != T_IDENTIFIER) {
1463 expect(T_IDENTIFIER);
1466 /* This isn't really correct, the backend should provide a list of machine
1467 * specific modes (according to gcc philosophy that is...) */
1468 const char *symbol_str = token.v.symbol->string;
1469 if (strcmp_underscore("QI", symbol_str) == 0 ||
1470 strcmp_underscore("byte", symbol_str) == 0) {
1471 attribute->u.akind = ATOMIC_TYPE_CHAR;
1472 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1473 attribute->u.akind = ATOMIC_TYPE_SHORT;
1474 } else if (strcmp_underscore("SI", symbol_str) == 0
1475 || strcmp_underscore("word", symbol_str) == 0
1476 || strcmp_underscore("pointer", symbol_str) == 0) {
1477 attribute->u.akind = ATOMIC_TYPE_INT;
1478 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1479 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1482 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1483 attribute->invalid = true;
1487 rem_anchor_token(')');
1491 attribute->invalid = true;
1495 * parse one interrupt argument.
1497 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1499 static const char *const interrupts[] = {
1506 string_t string = { NULL, 0 };
1507 parse_gnu_attribute_string_arg(attribute, &string);
1508 if (string.begin != NULL) {
1509 for(size_t i = 0; i < 5; ++i) {
1510 if (strcmp(interrupts[i], string.begin) == 0) {
1511 attribute->u.value = i;
1515 errorf(HERE, "'%s' is not an interrupt", string.begin);
1517 attribute->invalid = true;
1521 * parse ( identifier, const expression, const expression )
1523 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1525 static const char *const format_names[] = {
1533 if (token.type != T_IDENTIFIER) {
1534 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1537 const char *name = token.v.symbol->string;
1538 for(i = 0; i < 4; ++i) {
1539 if (strcmp_underscore(format_names[i], name) == 0)
1543 if (warning.attribute)
1544 warningf(HERE, "'%s' is an unrecognized format function type", name);
1549 add_anchor_token(')');
1550 add_anchor_token(',');
1551 parse_constant_expression();
1552 rem_anchor_token(',');
1553 rem_anchor_token(')');
1556 add_anchor_token(')');
1557 parse_constant_expression();
1558 rem_anchor_token(')');
1562 attribute->u.value = true;
1565 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1567 if (!attribute->have_arguments)
1570 /* should have no arguments */
1571 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1572 eat_until_matching_token('(');
1573 /* we have already consumed '(', so we stop before ')', eat it */
1575 attribute->invalid = true;
1579 * Parse one GNU attribute.
1581 * Note that attribute names can be specified WITH or WITHOUT
1582 * double underscores, ie const or __const__.
1584 * The following attributes are parsed without arguments
1609 * no_instrument_function
1610 * warn_unused_result
1627 * externally_visible
1635 * The following attributes are parsed with arguments
1636 * aligned( const expression )
1637 * alias( string literal )
1638 * section( string literal )
1639 * format( identifier, const expression, const expression )
1640 * format_arg( const expression )
1641 * tls_model( string literal )
1642 * visibility( string literal )
1643 * regparm( const expression )
1644 * model( string leteral )
1645 * trap_exit( const expression )
1646 * sp_switch( string literal )
1648 * The following attributes might have arguments
1649 * weak_ref( string literal )
1650 * non_null( const expression // ',' )
1651 * interrupt( string literal )
1652 * sentinel( constant expression )
1654 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1656 gnu_attribute_t *head = *attributes;
1657 gnu_attribute_t *last = *attributes;
1658 decl_modifiers_t modifiers = 0;
1659 gnu_attribute_t *attribute;
1661 eat(T___attribute__);
1665 if (token.type != ')') {
1666 /* find the end of the list */
1668 while (last->next != NULL)
1672 /* non-empty attribute list */
1675 if (token.type == T_const) {
1677 } else if (token.type == T_volatile) {
1679 } else if (token.type == T_cdecl) {
1680 /* __attribute__((cdecl)), WITH ms mode */
1682 } else if (token.type == T_IDENTIFIER) {
1683 const symbol_t *sym = token.v.symbol;
1686 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1693 for(i = 0; i < GNU_AK_LAST; ++i) {
1694 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1697 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1700 if (kind == GNU_AK_LAST) {
1701 if (warning.attribute)
1702 warningf(HERE, "'%s' attribute directive ignored", name);
1704 /* skip possible arguments */
1705 if (token.type == '(') {
1706 eat_until_matching_token(')');
1709 /* check for arguments */
1710 attribute = allocate_gnu_attribute(kind);
1711 if (token.type == '(') {
1713 if (token.type == ')') {
1714 /* empty args are allowed */
1717 attribute->have_arguments = true;
1721 case GNU_AK_VOLATILE:
1726 case GNU_AK_NOCOMMON:
1728 case GNU_AK_NOTSHARED:
1729 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1730 case GNU_AK_WARN_UNUSED_RESULT:
1731 case GNU_AK_LONGCALL:
1732 case GNU_AK_SHORTCALL:
1733 case GNU_AK_LONG_CALL:
1734 case GNU_AK_SHORT_CALL:
1735 case GNU_AK_FUNCTION_VECTOR:
1736 case GNU_AK_INTERRUPT_HANDLER:
1737 case GNU_AK_NMI_HANDLER:
1738 case GNU_AK_NESTING:
1742 case GNU_AK_EIGTHBIT_DATA:
1743 case GNU_AK_TINY_DATA:
1744 case GNU_AK_SAVEALL:
1745 case GNU_AK_FLATTEN:
1746 case GNU_AK_SSEREGPARM:
1747 case GNU_AK_EXTERNALLY_VISIBLE:
1748 case GNU_AK_RETURN_TWICE:
1749 case GNU_AK_MAY_ALIAS:
1750 case GNU_AK_MS_STRUCT:
1751 case GNU_AK_GCC_STRUCT:
1754 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1755 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1756 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1757 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1758 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1759 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1760 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1761 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1762 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1763 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1764 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1765 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1766 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1767 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1768 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1769 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1770 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1771 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1773 case GNU_AK_ALIGNED:
1774 /* __align__ may be used without an argument */
1775 if (attribute->have_arguments) {
1776 parse_gnu_attribute_const_arg(attribute);
1780 case GNU_AK_FORMAT_ARG:
1781 case GNU_AK_REGPARM:
1782 case GNU_AK_TRAP_EXIT:
1783 if (!attribute->have_arguments) {
1784 /* should have arguments */
1785 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1786 attribute->invalid = true;
1788 parse_gnu_attribute_const_arg(attribute);
1791 case GNU_AK_SECTION:
1792 case GNU_AK_SP_SWITCH:
1793 if (!attribute->have_arguments) {
1794 /* should have arguments */
1795 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1796 attribute->invalid = true;
1798 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1801 if (!attribute->have_arguments) {
1802 /* should have arguments */
1803 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1804 attribute->invalid = true;
1806 parse_gnu_attribute_format_args(attribute);
1808 case GNU_AK_WEAKREF:
1809 /* may have one string argument */
1810 if (attribute->have_arguments)
1811 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1813 case GNU_AK_NONNULL:
1814 if (attribute->have_arguments)
1815 parse_gnu_attribute_const_arg_list(attribute);
1817 case GNU_AK_TLS_MODEL:
1818 if (!attribute->have_arguments) {
1819 /* should have arguments */
1820 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1822 parse_gnu_attribute_tls_model_arg(attribute);
1824 case GNU_AK_VISIBILITY:
1825 if (!attribute->have_arguments) {
1826 /* should have arguments */
1827 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1829 parse_gnu_attribute_visibility_arg(attribute);
1832 if (!attribute->have_arguments) {
1833 /* should have arguments */
1834 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1836 parse_gnu_attribute_model_arg(attribute);
1840 if (!attribute->have_arguments) {
1841 /* should have arguments */
1842 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1844 parse_gnu_attribute_mode_arg(attribute);
1847 case GNU_AK_INTERRUPT:
1848 /* may have one string argument */
1849 if (attribute->have_arguments)
1850 parse_gnu_attribute_interrupt_arg(attribute);
1852 case GNU_AK_SENTINEL:
1853 /* may have one string argument */
1854 if (attribute->have_arguments)
1855 parse_gnu_attribute_const_arg(attribute);
1858 /* already handled */
1862 check_no_argument(attribute, name);
1865 if (attribute != NULL) {
1867 last->next = attribute;
1870 head = last = attribute;
1874 if (token.type != ',')
1888 * Parse GNU attributes.
1890 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1892 decl_modifiers_t modifiers = 0;
1895 switch(token.type) {
1896 case T___attribute__:
1897 modifiers |= parse_gnu_attribute(attributes);
1903 if (token.type != T_STRING_LITERAL) {
1904 parse_error_expected("while parsing assembler attribute",
1905 T_STRING_LITERAL, NULL);
1906 eat_until_matching_token('(');
1909 parse_string_literals();
1914 case T_cdecl: modifiers |= DM_CDECL; break;
1915 case T__fastcall: modifiers |= DM_FASTCALL; break;
1916 case T__stdcall: modifiers |= DM_STDCALL; break;
1919 /* TODO record modifier */
1921 warningf(HERE, "Ignoring declaration modifier %K", &token);
1925 default: return modifiers;
1932 static void mark_decls_read(expression_t *expr, declaration_t *lhs_decl);
1934 static declaration_t *determine_lhs_decl(expression_t *const expr, declaration_t *lhs_decl)
1936 switch (expr->kind) {
1937 case EXPR_REFERENCE: {
1938 declaration_t *const decl = expr->reference.declaration;
1942 case EXPR_ARRAY_ACCESS: {
1943 expression_t *const ref = expr->array_access.array_ref;
1944 declaration_t * decl = NULL;
1945 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1946 decl = determine_lhs_decl(ref, lhs_decl);
1949 mark_decls_read(expr->select.compound, lhs_decl);
1951 mark_decls_read(expr->array_access.index, lhs_decl);
1956 if (is_type_compound(skip_typeref(expr->base.type))) {
1957 return determine_lhs_decl(expr->select.compound, lhs_decl);
1959 mark_decls_read(expr->select.compound, lhs_decl);
1964 case EXPR_UNARY_DEREFERENCE: {
1965 expression_t *const val = expr->unary.value;
1966 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1968 return determine_lhs_decl(val->unary.value, lhs_decl);
1970 mark_decls_read(val, NULL);
1976 mark_decls_read(expr, NULL);
1981 #define DECL_ANY ((declaration_t*)-1)
1984 * Mark declarations, which are read. This is used to deted variables, which
1988 * x is not marked as "read", because it is only read to calculate its own new
1992 * x and y are not detected as "not read", because multiple variables are
1995 static void mark_decls_read(expression_t *const expr, declaration_t *lhs_decl)
1997 switch (expr->kind) {
1998 case EXPR_REFERENCE: {
1999 declaration_t *const decl = expr->reference.declaration;
2000 if (lhs_decl != decl && lhs_decl != DECL_ANY)
2006 // TODO respect pure/const
2007 mark_decls_read(expr->call.function, NULL);
2008 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2009 mark_decls_read(arg->expression, NULL);
2013 case EXPR_CONDITIONAL:
2014 // TODO lhs_decl should depend on whether true/false have an effect
2015 mark_decls_read(expr->conditional.condition, NULL);
2016 if (expr->conditional.true_expression != NULL)
2017 mark_decls_read(expr->conditional.true_expression, lhs_decl);
2018 mark_decls_read(expr->conditional.false_expression, lhs_decl);
2022 if (lhs_decl == DECL_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2024 mark_decls_read(expr->select.compound, lhs_decl);
2027 case EXPR_ARRAY_ACCESS: {
2028 expression_t *const ref = expr->array_access.array_ref;
2029 mark_decls_read(ref, lhs_decl);
2030 lhs_decl = determine_lhs_decl(ref, lhs_decl);
2031 mark_decls_read(expr->array_access.index, lhs_decl);
2036 mark_decls_read(expr->va_arge.ap, lhs_decl);
2039 case EXPR_UNARY_CAST:
2040 /* Special case: Use void cast to mark a variable as "read" */
2041 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2046 case EXPR_UNARY_THROW:
2047 if (expr->unary.value == NULL)
2050 case EXPR_UNARY_DEREFERENCE:
2051 case EXPR_UNARY_DELETE:
2052 case EXPR_UNARY_DELETE_ARRAY:
2053 if (lhs_decl == DECL_ANY)
2057 case EXPR_UNARY_NEGATE:
2058 case EXPR_UNARY_PLUS:
2059 case EXPR_UNARY_BITWISE_NEGATE:
2060 case EXPR_UNARY_NOT:
2061 case EXPR_UNARY_TAKE_ADDRESS:
2062 case EXPR_UNARY_POSTFIX_INCREMENT:
2063 case EXPR_UNARY_POSTFIX_DECREMENT:
2064 case EXPR_UNARY_PREFIX_INCREMENT:
2065 case EXPR_UNARY_PREFIX_DECREMENT:
2066 case EXPR_UNARY_CAST_IMPLICIT:
2067 case EXPR_UNARY_ASSUME:
2069 mark_decls_read(expr->unary.value, lhs_decl);
2072 case EXPR_BINARY_ADD:
2073 case EXPR_BINARY_SUB:
2074 case EXPR_BINARY_MUL:
2075 case EXPR_BINARY_DIV:
2076 case EXPR_BINARY_MOD:
2077 case EXPR_BINARY_EQUAL:
2078 case EXPR_BINARY_NOTEQUAL:
2079 case EXPR_BINARY_LESS:
2080 case EXPR_BINARY_LESSEQUAL:
2081 case EXPR_BINARY_GREATER:
2082 case EXPR_BINARY_GREATEREQUAL:
2083 case EXPR_BINARY_BITWISE_AND:
2084 case EXPR_BINARY_BITWISE_OR:
2085 case EXPR_BINARY_BITWISE_XOR:
2086 case EXPR_BINARY_LOGICAL_AND:
2087 case EXPR_BINARY_LOGICAL_OR:
2088 case EXPR_BINARY_SHIFTLEFT:
2089 case EXPR_BINARY_SHIFTRIGHT:
2090 case EXPR_BINARY_COMMA:
2091 case EXPR_BINARY_ISGREATER:
2092 case EXPR_BINARY_ISGREATEREQUAL:
2093 case EXPR_BINARY_ISLESS:
2094 case EXPR_BINARY_ISLESSEQUAL:
2095 case EXPR_BINARY_ISLESSGREATER:
2096 case EXPR_BINARY_ISUNORDERED:
2097 mark_decls_read(expr->binary.left, lhs_decl);
2098 mark_decls_read(expr->binary.right, lhs_decl);
2101 case EXPR_BINARY_ASSIGN:
2102 case EXPR_BINARY_MUL_ASSIGN:
2103 case EXPR_BINARY_DIV_ASSIGN:
2104 case EXPR_BINARY_MOD_ASSIGN:
2105 case EXPR_BINARY_ADD_ASSIGN:
2106 case EXPR_BINARY_SUB_ASSIGN:
2107 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2108 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2109 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2110 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2111 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2112 if (lhs_decl == DECL_ANY)
2114 lhs_decl = determine_lhs_decl(expr->binary.left, lhs_decl);
2115 mark_decls_read(expr->binary.right, lhs_decl);
2120 determine_lhs_decl(expr->va_starte.ap, lhs_decl);
2126 case EXPR_CHARACTER_CONSTANT:
2127 case EXPR_WIDE_CHARACTER_CONSTANT:
2128 case EXPR_STRING_LITERAL:
2129 case EXPR_WIDE_STRING_LITERAL:
2130 case EXPR_COMPOUND_LITERAL: // TODO init?
2132 case EXPR_CLASSIFY_TYPE:
2135 case EXPR_BUILTIN_SYMBOL:
2136 case EXPR_BUILTIN_CONSTANT_P:
2137 case EXPR_BUILTIN_PREFETCH:
2139 case EXPR_STATEMENT: // TODO
2140 case EXPR_LABEL_ADDRESS:
2141 case EXPR_BINARY_BUILTIN_EXPECT:
2145 panic("unhandled expression");
2148 static designator_t *parse_designation(void)
2150 designator_t *result = NULL;
2151 designator_t *last = NULL;
2154 designator_t *designator;
2155 switch(token.type) {
2157 designator = allocate_ast_zero(sizeof(designator[0]));
2158 designator->source_position = token.source_position;
2160 add_anchor_token(']');
2161 designator->array_index = parse_constant_expression();
2162 rem_anchor_token(']');
2166 designator = allocate_ast_zero(sizeof(designator[0]));
2167 designator->source_position = token.source_position;
2169 if (token.type != T_IDENTIFIER) {
2170 parse_error_expected("while parsing designator",
2171 T_IDENTIFIER, NULL);
2174 designator->symbol = token.v.symbol;
2182 assert(designator != NULL);
2184 last->next = designator;
2186 result = designator;
2194 static initializer_t *initializer_from_string(array_type_t *type,
2195 const string_t *const string)
2197 /* TODO: check len vs. size of array type */
2200 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2201 initializer->string.string = *string;
2206 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2207 wide_string_t *const string)
2209 /* TODO: check len vs. size of array type */
2212 initializer_t *const initializer =
2213 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2214 initializer->wide_string.string = *string;
2220 * Build an initializer from a given expression.
2222 static initializer_t *initializer_from_expression(type_t *orig_type,
2223 expression_t *expression)
2225 /* TODO check that expression is a constant expression */
2227 /* § 6.7.8.14/15 char array may be initialized by string literals */
2228 type_t *type = skip_typeref(orig_type);
2229 type_t *expr_type_orig = expression->base.type;
2230 type_t *expr_type = skip_typeref(expr_type_orig);
2231 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2232 array_type_t *const array_type = &type->array;
2233 type_t *const element_type = skip_typeref(array_type->element_type);
2235 if (element_type->kind == TYPE_ATOMIC) {
2236 atomic_type_kind_t akind = element_type->atomic.akind;
2237 switch (expression->kind) {
2238 case EXPR_STRING_LITERAL:
2239 if (akind == ATOMIC_TYPE_CHAR
2240 || akind == ATOMIC_TYPE_SCHAR
2241 || akind == ATOMIC_TYPE_UCHAR) {
2242 return initializer_from_string(array_type,
2243 &expression->string.value);
2246 case EXPR_WIDE_STRING_LITERAL: {
2247 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2248 if (get_unqualified_type(element_type) == bare_wchar_type) {
2249 return initializer_from_wide_string(array_type,
2250 &expression->wide_string.value);
2260 assign_error_t error = semantic_assign(type, expression);
2261 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2263 report_assign_error(error, type, expression, "initializer",
2264 &expression->base.source_position);
2266 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2268 if (type->kind == TYPE_BITFIELD) {
2269 type = type->bitfield.base_type;
2272 result->value.value = create_implicit_cast(expression, type);
2278 * Checks if a given expression can be used as an constant initializer.
2280 static bool is_initializer_constant(const expression_t *expression)
2282 return is_constant_expression(expression)
2283 || is_address_constant(expression);
2287 * Parses an scalar initializer.
2289 * § 6.7.8.11; eat {} without warning
2291 static initializer_t *parse_scalar_initializer(type_t *type,
2292 bool must_be_constant)
2294 /* there might be extra {} hierarchies */
2296 if (token.type == '{') {
2298 warningf(HERE, "extra curly braces around scalar initializer");
2302 } while (token.type == '{');
2305 expression_t *expression = parse_assignment_expression();
2306 mark_decls_read(expression, NULL);
2307 if (must_be_constant && !is_initializer_constant(expression)) {
2308 errorf(&expression->base.source_position,
2309 "Initialisation expression '%E' is not constant\n",
2313 initializer_t *initializer = initializer_from_expression(type, expression);
2315 if (initializer == NULL) {
2316 errorf(&expression->base.source_position,
2317 "expression '%E' (type '%T') doesn't match expected type '%T'",
2318 expression, expression->base.type, type);
2323 bool additional_warning_displayed = false;
2324 while (braces > 0) {
2325 if (token.type == ',') {
2328 if (token.type != '}') {
2329 if (!additional_warning_displayed && warning.other) {
2330 warningf(HERE, "additional elements in scalar initializer");
2331 additional_warning_displayed = true;
2342 * An entry in the type path.
2344 typedef struct type_path_entry_t type_path_entry_t;
2345 struct type_path_entry_t {
2346 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2348 size_t index; /**< For array types: the current index. */
2349 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2354 * A type path expression a position inside compound or array types.
2356 typedef struct type_path_t type_path_t;
2357 struct type_path_t {
2358 type_path_entry_t *path; /**< An flexible array containing the current path. */
2359 type_t *top_type; /**< type of the element the path points */
2360 size_t max_index; /**< largest index in outermost array */
2364 * Prints a type path for debugging.
2366 static __attribute__((unused)) void debug_print_type_path(
2367 const type_path_t *path)
2369 size_t len = ARR_LEN(path->path);
2371 for(size_t i = 0; i < len; ++i) {
2372 const type_path_entry_t *entry = & path->path[i];
2374 type_t *type = skip_typeref(entry->type);
2375 if (is_type_compound(type)) {
2376 /* in gcc mode structs can have no members */
2377 if (entry->v.compound_entry == NULL) {
2381 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2382 } else if (is_type_array(type)) {
2383 fprintf(stderr, "[%zu]", entry->v.index);
2385 fprintf(stderr, "-INVALID-");
2388 if (path->top_type != NULL) {
2389 fprintf(stderr, " (");
2390 print_type(path->top_type);
2391 fprintf(stderr, ")");
2396 * Return the top type path entry, ie. in a path
2397 * (type).a.b returns the b.
2399 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2401 size_t len = ARR_LEN(path->path);
2403 return &path->path[len-1];
2407 * Enlarge the type path by an (empty) element.
2409 static type_path_entry_t *append_to_type_path(type_path_t *path)
2411 size_t len = ARR_LEN(path->path);
2412 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2414 type_path_entry_t *result = & path->path[len];
2415 memset(result, 0, sizeof(result[0]));
2420 * Descending into a sub-type. Enter the scope of the current
2423 static void descend_into_subtype(type_path_t *path)
2425 type_t *orig_top_type = path->top_type;
2426 type_t *top_type = skip_typeref(orig_top_type);
2428 type_path_entry_t *top = append_to_type_path(path);
2429 top->type = top_type;
2431 if (is_type_compound(top_type)) {
2432 declaration_t *declaration = top_type->compound.declaration;
2433 declaration_t *entry = declaration->scope.declarations;
2434 top->v.compound_entry = entry;
2436 if (entry != NULL) {
2437 path->top_type = entry->type;
2439 path->top_type = NULL;
2441 } else if (is_type_array(top_type)) {
2443 path->top_type = top_type->array.element_type;
2445 assert(!is_type_valid(top_type));
2450 * Pop an entry from the given type path, ie. returning from
2451 * (type).a.b to (type).a
2453 static void ascend_from_subtype(type_path_t *path)
2455 type_path_entry_t *top = get_type_path_top(path);
2457 path->top_type = top->type;
2459 size_t len = ARR_LEN(path->path);
2460 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2464 * Pop entries from the given type path until the given
2465 * path level is reached.
2467 static void ascend_to(type_path_t *path, size_t top_path_level)
2469 size_t len = ARR_LEN(path->path);
2471 while (len > top_path_level) {
2472 ascend_from_subtype(path);
2473 len = ARR_LEN(path->path);
2477 static bool walk_designator(type_path_t *path, const designator_t *designator,
2478 bool used_in_offsetof)
2480 for( ; designator != NULL; designator = designator->next) {
2481 type_path_entry_t *top = get_type_path_top(path);
2482 type_t *orig_type = top->type;
2484 type_t *type = skip_typeref(orig_type);
2486 if (designator->symbol != NULL) {
2487 symbol_t *symbol = designator->symbol;
2488 if (!is_type_compound(type)) {
2489 if (is_type_valid(type)) {
2490 errorf(&designator->source_position,
2491 "'.%Y' designator used for non-compound type '%T'",
2495 top->type = type_error_type;
2496 top->v.compound_entry = NULL;
2497 orig_type = type_error_type;
2499 declaration_t *declaration = type->compound.declaration;
2500 declaration_t *iter = declaration->scope.declarations;
2501 for( ; iter != NULL; iter = iter->next) {
2502 if (iter->symbol == symbol) {
2507 errorf(&designator->source_position,
2508 "'%T' has no member named '%Y'", orig_type, symbol);
2511 if (used_in_offsetof) {
2512 type_t *real_type = skip_typeref(iter->type);
2513 if (real_type->kind == TYPE_BITFIELD) {
2514 errorf(&designator->source_position,
2515 "offsetof designator '%Y' may not specify bitfield",
2521 top->type = orig_type;
2522 top->v.compound_entry = iter;
2523 orig_type = iter->type;
2526 expression_t *array_index = designator->array_index;
2527 assert(designator->array_index != NULL);
2529 if (!is_type_array(type)) {
2530 if (is_type_valid(type)) {
2531 errorf(&designator->source_position,
2532 "[%E] designator used for non-array type '%T'",
2533 array_index, orig_type);
2538 long index = fold_constant(array_index);
2539 if (!used_in_offsetof) {
2541 errorf(&designator->source_position,
2542 "array index [%E] must be positive", array_index);
2543 } else if (type->array.size_constant) {
2544 long array_size = type->array.size;
2545 if (index >= array_size) {
2546 errorf(&designator->source_position,
2547 "designator [%E] (%d) exceeds array size %d",
2548 array_index, index, array_size);
2553 top->type = orig_type;
2554 top->v.index = (size_t) index;
2555 orig_type = type->array.element_type;
2557 path->top_type = orig_type;
2559 if (designator->next != NULL) {
2560 descend_into_subtype(path);
2569 static void advance_current_object(type_path_t *path, size_t top_path_level)
2571 type_path_entry_t *top = get_type_path_top(path);
2573 type_t *type = skip_typeref(top->type);
2574 if (is_type_union(type)) {
2575 /* in unions only the first element is initialized */
2576 top->v.compound_entry = NULL;
2577 } else if (is_type_struct(type)) {
2578 declaration_t *entry = top->v.compound_entry;
2580 entry = entry->next;
2581 top->v.compound_entry = entry;
2582 if (entry != NULL) {
2583 path->top_type = entry->type;
2586 } else if (is_type_array(type)) {
2587 assert(is_type_array(type));
2591 if (!type->array.size_constant || top->v.index < type->array.size) {
2595 assert(!is_type_valid(type));
2599 /* we're past the last member of the current sub-aggregate, try if we
2600 * can ascend in the type hierarchy and continue with another subobject */
2601 size_t len = ARR_LEN(path->path);
2603 if (len > top_path_level) {
2604 ascend_from_subtype(path);
2605 advance_current_object(path, top_path_level);
2607 path->top_type = NULL;
2612 * skip until token is found.
2614 static void skip_until(int type)
2616 while (token.type != type) {
2617 if (token.type == T_EOF)
2624 * skip any {...} blocks until a closing bracket is reached.
2626 static void skip_initializers(void)
2628 if (token.type == '{')
2631 while (token.type != '}') {
2632 if (token.type == T_EOF)
2634 if (token.type == '{') {
2642 static initializer_t *create_empty_initializer(void)
2644 static initializer_t empty_initializer
2645 = { .list = { { INITIALIZER_LIST }, 0 } };
2646 return &empty_initializer;
2650 * Parse a part of an initialiser for a struct or union,
2652 static initializer_t *parse_sub_initializer(type_path_t *path,
2653 type_t *outer_type, size_t top_path_level,
2654 parse_initializer_env_t *env)
2656 if (token.type == '}') {
2657 /* empty initializer */
2658 return create_empty_initializer();
2661 type_t *orig_type = path->top_type;
2662 type_t *type = NULL;
2664 if (orig_type == NULL) {
2665 /* We are initializing an empty compound. */
2667 type = skip_typeref(orig_type);
2670 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2673 designator_t *designator = NULL;
2674 if (token.type == '.' || token.type == '[') {
2675 designator = parse_designation();
2676 goto finish_designator;
2677 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2678 /* GNU-style designator ("identifier: value") */
2679 designator = allocate_ast_zero(sizeof(designator[0]));
2680 designator->source_position = token.source_position;
2681 designator->symbol = token.v.symbol;
2686 /* reset path to toplevel, evaluate designator from there */
2687 ascend_to(path, top_path_level);
2688 if (!walk_designator(path, designator, false)) {
2689 /* can't continue after designation error */
2693 initializer_t *designator_initializer
2694 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2695 designator_initializer->designator.designator = designator;
2696 ARR_APP1(initializer_t*, initializers, designator_initializer);
2698 orig_type = path->top_type;
2699 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2704 if (token.type == '{') {
2705 if (type != NULL && is_type_scalar(type)) {
2706 sub = parse_scalar_initializer(type, env->must_be_constant);
2710 if (env->declaration != NULL) {
2711 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2712 env->declaration->symbol);
2714 errorf(HERE, "extra brace group at end of initializer");
2717 descend_into_subtype(path);
2719 add_anchor_token('}');
2720 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2722 rem_anchor_token('}');
2725 ascend_from_subtype(path);
2729 goto error_parse_next;
2733 /* must be an expression */
2734 expression_t *expression = parse_assignment_expression();
2736 if (env->must_be_constant && !is_initializer_constant(expression)) {
2737 errorf(&expression->base.source_position,
2738 "Initialisation expression '%E' is not constant\n",
2743 /* we are already outside, ... */
2744 type_t *const outer_type_skip = skip_typeref(outer_type);
2745 if (is_type_compound(outer_type_skip) &&
2746 !outer_type_skip->compound.declaration->init.complete) {
2747 goto error_parse_next;
2752 /* handle { "string" } special case */
2753 if ((expression->kind == EXPR_STRING_LITERAL
2754 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2755 && outer_type != NULL) {
2756 sub = initializer_from_expression(outer_type, expression);
2758 if (token.type == ',') {
2761 if (token.type != '}' && warning.other) {
2762 warningf(HERE, "excessive elements in initializer for type '%T'",
2765 /* TODO: eat , ... */
2770 /* descend into subtypes until expression matches type */
2772 orig_type = path->top_type;
2773 type = skip_typeref(orig_type);
2775 sub = initializer_from_expression(orig_type, expression);
2779 if (!is_type_valid(type)) {
2782 if (is_type_scalar(type)) {
2783 errorf(&expression->base.source_position,
2784 "expression '%E' doesn't match expected type '%T'",
2785 expression, orig_type);
2789 descend_into_subtype(path);
2793 /* update largest index of top array */
2794 const type_path_entry_t *first = &path->path[0];
2795 type_t *first_type = first->type;
2796 first_type = skip_typeref(first_type);
2797 if (is_type_array(first_type)) {
2798 size_t index = first->v.index;
2799 if (index > path->max_index)
2800 path->max_index = index;
2804 /* append to initializers list */
2805 ARR_APP1(initializer_t*, initializers, sub);
2808 if (warning.other) {
2809 if (env->declaration != NULL) {
2810 warningf(HERE, "excess elements in struct initializer for '%Y'",
2811 env->declaration->symbol);
2813 warningf(HERE, "excess elements in struct initializer");
2819 if (token.type == '}') {
2823 if (token.type == '}') {
2828 /* advance to the next declaration if we are not at the end */
2829 advance_current_object(path, top_path_level);
2830 orig_type = path->top_type;
2831 if (orig_type != NULL)
2832 type = skip_typeref(orig_type);
2838 size_t len = ARR_LEN(initializers);
2839 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2840 initializer_t *result = allocate_ast_zero(size);
2841 result->kind = INITIALIZER_LIST;
2842 result->list.len = len;
2843 memcpy(&result->list.initializers, initializers,
2844 len * sizeof(initializers[0]));
2846 DEL_ARR_F(initializers);
2847 ascend_to(path, top_path_level+1);
2852 skip_initializers();
2853 DEL_ARR_F(initializers);
2854 ascend_to(path, top_path_level+1);
2859 * Parses an initializer. Parsers either a compound literal
2860 * (env->declaration == NULL) or an initializer of a declaration.
2862 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2864 type_t *type = skip_typeref(env->type);
2865 initializer_t *result = NULL;
2868 if (is_type_scalar(type)) {
2869 result = parse_scalar_initializer(type, env->must_be_constant);
2870 } else if (token.type == '{') {
2874 memset(&path, 0, sizeof(path));
2875 path.top_type = env->type;
2876 path.path = NEW_ARR_F(type_path_entry_t, 0);
2878 descend_into_subtype(&path);
2880 add_anchor_token('}');
2881 result = parse_sub_initializer(&path, env->type, 1, env);
2882 rem_anchor_token('}');
2884 max_index = path.max_index;
2885 DEL_ARR_F(path.path);
2889 /* parse_scalar_initializer() also works in this case: we simply
2890 * have an expression without {} around it */
2891 result = parse_scalar_initializer(type, env->must_be_constant);
2894 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2895 * the array type size */
2896 if (is_type_array(type) && type->array.size_expression == NULL
2897 && result != NULL) {
2899 switch (result->kind) {
2900 case INITIALIZER_LIST:
2901 size = max_index + 1;
2904 case INITIALIZER_STRING:
2905 size = result->string.string.size;
2908 case INITIALIZER_WIDE_STRING:
2909 size = result->wide_string.string.size;
2912 case INITIALIZER_DESIGNATOR:
2913 case INITIALIZER_VALUE:
2914 /* can happen for parse errors */
2919 internal_errorf(HERE, "invalid initializer type");
2922 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2923 cnst->base.type = type_size_t;
2924 cnst->conste.v.int_value = size;
2926 type_t *new_type = duplicate_type(type);
2928 new_type->array.size_expression = cnst;
2929 new_type->array.size_constant = true;
2930 new_type->array.size = size;
2931 env->type = new_type;
2939 static declaration_t *append_declaration(declaration_t *declaration);
2941 static declaration_t *parse_compound_type_specifier(bool is_struct)
2943 gnu_attribute_t *attributes = NULL;
2944 decl_modifiers_t modifiers = 0;
2951 symbol_t *symbol = NULL;
2952 declaration_t *declaration = NULL;
2954 if (token.type == T___attribute__) {
2955 modifiers |= parse_attributes(&attributes);
2958 if (token.type == T_IDENTIFIER) {
2959 symbol = token.v.symbol;
2962 namespace_t const namespc =
2963 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2964 declaration = get_declaration(symbol, namespc);
2965 if (declaration != NULL) {
2966 if (declaration->parent_scope != scope &&
2967 (token.type == '{' || token.type == ';')) {
2969 } else if (declaration->init.complete &&
2970 token.type == '{') {
2971 assert(symbol != NULL);
2972 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2973 is_struct ? "struct" : "union", symbol,
2974 &declaration->source_position);
2975 declaration->scope.declarations = NULL;
2978 } else if (token.type != '{') {
2980 parse_error_expected("while parsing struct type specifier",
2981 T_IDENTIFIER, '{', NULL);
2983 parse_error_expected("while parsing union type specifier",
2984 T_IDENTIFIER, '{', NULL);
2990 if (declaration == NULL) {
2991 declaration = allocate_declaration_zero();
2992 declaration->namespc =
2993 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2994 declaration->source_position = token.source_position;
2995 declaration->symbol = symbol;
2996 declaration->parent_scope = scope;
2997 if (symbol != NULL) {
2998 environment_push(declaration);
3000 append_declaration(declaration);
3003 if (token.type == '{') {
3004 declaration->init.complete = true;
3006 parse_compound_type_entries(declaration);
3007 modifiers |= parse_attributes(&attributes);
3010 declaration->modifiers |= modifiers;
3014 static void parse_enum_entries(type_t *const enum_type)
3018 if (token.type == '}') {
3020 errorf(HERE, "empty enum not allowed");
3024 add_anchor_token('}');
3026 if (token.type != T_IDENTIFIER) {
3027 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3029 rem_anchor_token('}');
3033 declaration_t *const entry = allocate_declaration_zero();
3034 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
3035 entry->type = enum_type;
3036 entry->symbol = token.v.symbol;
3037 entry->source_position = token.source_position;
3040 if (token.type == '=') {
3042 expression_t *value = parse_constant_expression();
3044 value = create_implicit_cast(value, enum_type);
3045 entry->init.enum_value = value;
3050 record_declaration(entry, false);
3052 if (token.type != ',')
3055 } while (token.type != '}');
3056 rem_anchor_token('}');
3064 static type_t *parse_enum_specifier(void)
3066 gnu_attribute_t *attributes = NULL;
3067 declaration_t *declaration;
3071 if (token.type == T_IDENTIFIER) {
3072 symbol = token.v.symbol;
3075 declaration = get_declaration(symbol, NAMESPACE_ENUM);
3076 } else if (token.type != '{') {
3077 parse_error_expected("while parsing enum type specifier",
3078 T_IDENTIFIER, '{', NULL);
3085 if (declaration == NULL) {
3086 declaration = allocate_declaration_zero();
3087 declaration->namespc = NAMESPACE_ENUM;
3088 declaration->source_position = token.source_position;
3089 declaration->symbol = symbol;
3090 declaration->parent_scope = scope;
3093 type_t *const type = allocate_type_zero(TYPE_ENUM);
3094 type->enumt.declaration = declaration;
3096 if (token.type == '{') {
3097 if (declaration->init.complete) {
3098 errorf(HERE, "multiple definitions of enum %Y", symbol);
3100 if (symbol != NULL) {
3101 environment_push(declaration);
3103 append_declaration(declaration);
3104 declaration->init.complete = true;
3106 parse_enum_entries(type);
3107 parse_attributes(&attributes);
3114 * if a symbol is a typedef to another type, return true
3116 static bool is_typedef_symbol(symbol_t *symbol)
3118 const declaration_t *const declaration =
3119 get_declaration(symbol, NAMESPACE_NORMAL);
3121 declaration != NULL &&
3122 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
3125 static type_t *parse_typeof(void)
3132 add_anchor_token(')');
3134 expression_t *expression = NULL;
3136 bool old_type_prop = in_type_prop;
3137 bool old_gcc_extension = in_gcc_extension;
3138 in_type_prop = true;
3140 while (token.type == T___extension__) {
3141 /* This can be a prefix to a typename or an expression. */
3143 in_gcc_extension = true;
3145 switch (token.type) {
3147 if (is_typedef_symbol(token.v.symbol)) {
3148 type = parse_typename();
3150 expression = parse_expression();
3151 type = expression->base.type;
3156 type = parse_typename();
3160 expression = parse_expression();
3161 type = expression->base.type;
3164 in_type_prop = old_type_prop;
3165 in_gcc_extension = old_gcc_extension;
3167 rem_anchor_token(')');
3170 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3171 typeof_type->typeoft.expression = expression;
3172 typeof_type->typeoft.typeof_type = type;
3179 typedef enum specifiers_t {
3180 SPECIFIER_SIGNED = 1 << 0,
3181 SPECIFIER_UNSIGNED = 1 << 1,
3182 SPECIFIER_LONG = 1 << 2,
3183 SPECIFIER_INT = 1 << 3,
3184 SPECIFIER_DOUBLE = 1 << 4,
3185 SPECIFIER_CHAR = 1 << 5,
3186 SPECIFIER_SHORT = 1 << 6,
3187 SPECIFIER_LONG_LONG = 1 << 7,
3188 SPECIFIER_FLOAT = 1 << 8,
3189 SPECIFIER_BOOL = 1 << 9,
3190 SPECIFIER_VOID = 1 << 10,
3191 SPECIFIER_INT8 = 1 << 11,
3192 SPECIFIER_INT16 = 1 << 12,
3193 SPECIFIER_INT32 = 1 << 13,
3194 SPECIFIER_INT64 = 1 << 14,
3195 SPECIFIER_INT128 = 1 << 15,
3196 SPECIFIER_COMPLEX = 1 << 16,
3197 SPECIFIER_IMAGINARY = 1 << 17,
3200 static type_t *create_builtin_type(symbol_t *const symbol,
3201 type_t *const real_type)
3203 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3204 type->builtin.symbol = symbol;
3205 type->builtin.real_type = real_type;
3207 type_t *result = typehash_insert(type);
3208 if (type != result) {
3215 static type_t *get_typedef_type(symbol_t *symbol)
3217 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
3218 if (declaration == NULL ||
3219 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
3222 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3223 type->typedeft.declaration = declaration;
3229 * check for the allowed MS alignment values.
3231 static bool check_alignment_value(long long intvalue)
3233 if (intvalue < 1 || intvalue > 8192) {
3234 errorf(HERE, "illegal alignment value");
3237 unsigned v = (unsigned)intvalue;
3238 for (unsigned i = 1; i <= 8192; i += i) {
3242 errorf(HERE, "alignment must be power of two");
3246 #define DET_MOD(name, tag) do { \
3247 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3248 *modifiers |= tag; \
3251 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3253 decl_modifiers_t *modifiers = &specifiers->modifiers;
3256 if (token.type == T_restrict) {
3258 DET_MOD(restrict, DM_RESTRICT);
3260 } else if (token.type != T_IDENTIFIER)
3262 symbol_t *symbol = token.v.symbol;
3263 if (symbol == sym_align) {
3266 if (token.type != T_INTEGER)
3268 if (check_alignment_value(token.v.intvalue)) {
3269 if (specifiers->alignment != 0 && warning.other)
3270 warningf(HERE, "align used more than once");
3271 specifiers->alignment = (unsigned char)token.v.intvalue;
3275 } else if (symbol == sym_allocate) {
3278 if (token.type != T_IDENTIFIER)
3280 (void)token.v.symbol;
3282 } else if (symbol == sym_dllimport) {
3284 DET_MOD(dllimport, DM_DLLIMPORT);
3285 } else if (symbol == sym_dllexport) {
3287 DET_MOD(dllexport, DM_DLLEXPORT);
3288 } else if (symbol == sym_thread) {
3290 DET_MOD(thread, DM_THREAD);
3291 } else if (symbol == sym_naked) {
3293 DET_MOD(naked, DM_NAKED);
3294 } else if (symbol == sym_noinline) {
3296 DET_MOD(noinline, DM_NOINLINE);
3297 } else if (symbol == sym_noreturn) {
3299 DET_MOD(noreturn, DM_NORETURN);
3300 } else if (symbol == sym_nothrow) {
3302 DET_MOD(nothrow, DM_NOTHROW);
3303 } else if (symbol == sym_novtable) {
3305 DET_MOD(novtable, DM_NOVTABLE);
3306 } else if (symbol == sym_property) {
3310 bool is_get = false;
3311 if (token.type != T_IDENTIFIER)
3313 if (token.v.symbol == sym_get) {
3315 } else if (token.v.symbol == sym_put) {
3317 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3322 if (token.type != T_IDENTIFIER)
3325 if (specifiers->get_property_sym != NULL) {
3326 errorf(HERE, "get property name already specified");
3328 specifiers->get_property_sym = token.v.symbol;
3331 if (specifiers->put_property_sym != NULL) {
3332 errorf(HERE, "put property name already specified");
3334 specifiers->put_property_sym = token.v.symbol;
3338 if (token.type == ',') {
3345 } else if (symbol == sym_selectany) {
3347 DET_MOD(selectany, DM_SELECTANY);
3348 } else if (symbol == sym_uuid) {
3351 if (token.type != T_STRING_LITERAL)
3355 } else if (symbol == sym_deprecated) {
3357 if (specifiers->deprecated != 0 && warning.other)
3358 warningf(HERE, "deprecated used more than once");
3359 specifiers->deprecated = 1;
3360 if (token.type == '(') {
3362 if (token.type == T_STRING_LITERAL) {
3363 specifiers->deprecated_string = token.v.string.begin;
3366 errorf(HERE, "string literal expected");
3370 } else if (symbol == sym_noalias) {
3372 DET_MOD(noalias, DM_NOALIAS);
3375 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3377 if (token.type == '(')
3381 if (token.type == ',')
3388 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3390 declaration_t *const decl = allocate_declaration_zero();
3391 decl->source_position = *HERE;
3392 decl->declared_storage_class = storage_class;
3393 decl->storage_class =
3394 storage_class != STORAGE_CLASS_NONE || scope == file_scope ?
3395 storage_class : STORAGE_CLASS_AUTO;
3396 decl->symbol = symbol;
3397 decl->implicit = true;
3398 record_declaration(decl, false);
3403 * Finish the construction of a struct type by calculating
3404 * its size, offsets, alignment.
3406 static void finish_struct_type(compound_type_t *type) {
3407 if (type->declaration == NULL)
3409 declaration_t *struct_decl = type->declaration;
3410 if (! struct_decl->init.complete)
3415 il_alignment_t alignment = 1;
3416 bool need_pad = false;
3418 declaration_t *entry = struct_decl->scope.declarations;
3419 for (; entry != NULL; entry = entry->next) {
3420 if (entry->namespc != NAMESPACE_NORMAL)
3423 type_t *m_type = skip_typeref(entry->type);
3424 if (! is_type_valid(m_type)) {
3425 /* simply ignore errors here */
3428 il_alignment_t m_alignment = m_type->base.alignment;
3429 if (m_alignment > alignment)
3430 alignment = m_alignment;
3432 offset = (size + m_alignment - 1) & -m_alignment;
3436 entry->offset = offset;
3437 size = offset + m_type->base.size;
3439 if (type->base.alignment != 0) {
3440 alignment = type->base.alignment;
3443 offset = (size + alignment - 1) & -alignment;
3447 if (warning.padded && need_pad) {
3448 warningf(&struct_decl->source_position,
3449 "'%#T' needs padding", type, struct_decl->symbol);
3451 if (warning.packed && !need_pad) {
3452 warningf(&struct_decl->source_position,
3453 "superfluous packed attribute on '%#T'",
3454 type, struct_decl->symbol);
3457 type->base.size = offset;
3458 type->base.alignment = alignment;
3462 * Finish the construction of an union type by calculating
3463 * its size and alignment.
3465 static void finish_union_type(compound_type_t *type) {
3466 if (type->declaration == NULL)
3468 declaration_t *union_decl = type->declaration;
3469 if (! union_decl->init.complete)
3473 il_alignment_t alignment = 1;
3475 declaration_t *entry = union_decl->scope.declarations;
3476 for (; entry != NULL; entry = entry->next) {
3477 if (entry->namespc != NAMESPACE_NORMAL)
3480 type_t *m_type = skip_typeref(entry->type);
3481 if (! is_type_valid(m_type))
3485 if (m_type->base.size > size)
3486 size = m_type->base.size;
3487 if (m_type->base.alignment > alignment)
3488 alignment = m_type->base.alignment;
3490 if (type->base.alignment != 0) {
3491 alignment = type->base.alignment;
3493 size = (size + alignment - 1) & -alignment;
3494 type->base.size = size;
3495 type->base.alignment = alignment;
3498 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3500 type_t *type = NULL;
3501 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3502 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3503 unsigned type_specifiers = 0;
3504 bool newtype = false;
3505 bool saw_error = false;
3506 bool old_gcc_extension = in_gcc_extension;
3508 specifiers->source_position = token.source_position;
3511 specifiers->modifiers
3512 |= parse_attributes(&specifiers->gnu_attributes);
3513 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3514 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3516 switch (token.type) {
3519 #define MATCH_STORAGE_CLASS(token, class) \
3521 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3522 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3524 specifiers->declared_storage_class = class; \
3528 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3529 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3530 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3531 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3532 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3537 add_anchor_token(')');
3538 parse_microsoft_extended_decl_modifier(specifiers);
3539 rem_anchor_token(')');
3544 switch (specifiers->declared_storage_class) {
3545 case STORAGE_CLASS_NONE:
3546 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3549 case STORAGE_CLASS_EXTERN:
3550 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3553 case STORAGE_CLASS_STATIC:
3554 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3558 errorf(HERE, "multiple storage classes in declaration specifiers");
3564 /* type qualifiers */
3565 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3567 qualifiers |= qualifier; \
3571 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3572 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3573 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3574 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3575 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3576 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3577 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3578 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3580 case T___extension__:
3582 in_gcc_extension = true;
3585 /* type specifiers */
3586 #define MATCH_SPECIFIER(token, specifier, name) \
3589 if (type_specifiers & specifier) { \
3590 errorf(HERE, "multiple " name " type specifiers given"); \
3592 type_specifiers |= specifier; \
3596 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3597 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3598 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3599 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3600 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3601 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3602 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3603 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3604 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3605 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3606 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3607 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3608 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3609 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3610 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3611 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3613 case T__forceinline:
3614 /* only in microsoft mode */
3615 specifiers->modifiers |= DM_FORCEINLINE;
3620 specifiers->is_inline = true;
3625 if (type_specifiers & SPECIFIER_LONG_LONG) {
3626 errorf(HERE, "multiple type specifiers given");
3627 } else if (type_specifiers & SPECIFIER_LONG) {
3628 type_specifiers |= SPECIFIER_LONG_LONG;
3630 type_specifiers |= SPECIFIER_LONG;
3635 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3637 type->compound.declaration = parse_compound_type_specifier(true);
3638 finish_struct_type(&type->compound);
3642 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3643 type->compound.declaration = parse_compound_type_specifier(false);
3644 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3645 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3646 finish_union_type(&type->compound);
3650 type = parse_enum_specifier();
3653 type = parse_typeof();
3655 case T___builtin_va_list:
3656 type = duplicate_type(type_valist);
3660 case T_IDENTIFIER: {
3661 /* only parse identifier if we haven't found a type yet */
3662 if (type != NULL || type_specifiers != 0) {
3663 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3664 * declaration, so it doesn't generate errors about expecting '(' or
3666 switch (look_ahead(1)->type) {
3673 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3676 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3681 goto finish_specifiers;
3685 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3686 if (typedef_type == NULL) {
3687 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3688 * declaration, so it doesn't generate 'implicit int' followed by more
3689 * errors later on. */
3690 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3695 errorf(HERE, "%K does not name a type", &token);
3697 declaration_t *const decl =
3698 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3700 type = allocate_type_zero(TYPE_TYPEDEF);
3701 type->typedeft.declaration = decl;
3705 if (la1_type == '*')
3706 goto finish_specifiers;
3711 goto finish_specifiers;
3716 type = typedef_type;
3720 /* function specifier */
3722 goto finish_specifiers;
3727 in_gcc_extension = old_gcc_extension;
3729 if (type == NULL || (saw_error && type_specifiers != 0)) {
3730 atomic_type_kind_t atomic_type;
3732 /* match valid basic types */
3733 switch(type_specifiers) {
3734 case SPECIFIER_VOID:
3735 atomic_type = ATOMIC_TYPE_VOID;
3737 case SPECIFIER_CHAR:
3738 atomic_type = ATOMIC_TYPE_CHAR;
3740 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3741 atomic_type = ATOMIC_TYPE_SCHAR;
3743 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3744 atomic_type = ATOMIC_TYPE_UCHAR;
3746 case SPECIFIER_SHORT:
3747 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3748 case SPECIFIER_SHORT | SPECIFIER_INT:
3749 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3750 atomic_type = ATOMIC_TYPE_SHORT;
3752 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3753 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3754 atomic_type = ATOMIC_TYPE_USHORT;
3757 case SPECIFIER_SIGNED:
3758 case SPECIFIER_SIGNED | SPECIFIER_INT:
3759 atomic_type = ATOMIC_TYPE_INT;
3761 case SPECIFIER_UNSIGNED:
3762 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3763 atomic_type = ATOMIC_TYPE_UINT;
3765 case SPECIFIER_LONG:
3766 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3767 case SPECIFIER_LONG | SPECIFIER_INT:
3768 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3769 atomic_type = ATOMIC_TYPE_LONG;
3771 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3772 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3773 atomic_type = ATOMIC_TYPE_ULONG;
3776 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3777 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3778 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3779 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3781 atomic_type = ATOMIC_TYPE_LONGLONG;
3782 goto warn_about_long_long;
3784 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3785 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3787 atomic_type = ATOMIC_TYPE_ULONGLONG;
3788 warn_about_long_long:
3789 if (warning.long_long) {
3790 warningf(&specifiers->source_position,
3791 "ISO C90 does not support 'long long'");
3795 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3796 atomic_type = unsigned_int8_type_kind;
3799 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3800 atomic_type = unsigned_int16_type_kind;
3803 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3804 atomic_type = unsigned_int32_type_kind;
3807 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3808 atomic_type = unsigned_int64_type_kind;
3811 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3812 atomic_type = unsigned_int128_type_kind;
3815 case SPECIFIER_INT8:
3816 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3817 atomic_type = int8_type_kind;
3820 case SPECIFIER_INT16:
3821 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3822 atomic_type = int16_type_kind;
3825 case SPECIFIER_INT32:
3826 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3827 atomic_type = int32_type_kind;
3830 case SPECIFIER_INT64:
3831 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3832 atomic_type = int64_type_kind;
3835 case SPECIFIER_INT128:
3836 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3837 atomic_type = int128_type_kind;
3840 case SPECIFIER_FLOAT:
3841 atomic_type = ATOMIC_TYPE_FLOAT;
3843 case SPECIFIER_DOUBLE:
3844 atomic_type = ATOMIC_TYPE_DOUBLE;
3846 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3847 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3849 case SPECIFIER_BOOL:
3850 atomic_type = ATOMIC_TYPE_BOOL;
3852 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3853 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3854 atomic_type = ATOMIC_TYPE_FLOAT;
3856 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3857 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3858 atomic_type = ATOMIC_TYPE_DOUBLE;
3860 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3861 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3862 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3865 /* invalid specifier combination, give an error message */
3866 if (type_specifiers == 0) {
3870 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3871 if (!(c_mode & _CXX) && !strict_mode) {
3872 if (warning.implicit_int) {
3873 warningf(HERE, "no type specifiers in declaration, using 'int'");
3875 atomic_type = ATOMIC_TYPE_INT;
3878 errorf(HERE, "no type specifiers given in declaration");
3880 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3881 (type_specifiers & SPECIFIER_UNSIGNED)) {
3882 errorf(HERE, "signed and unsigned specifiers given");
3883 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3884 errorf(HERE, "only integer types can be signed or unsigned");
3886 errorf(HERE, "multiple datatypes in declaration");
3891 if (type_specifiers & SPECIFIER_COMPLEX) {
3892 type = allocate_type_zero(TYPE_COMPLEX);
3893 type->complex.akind = atomic_type;
3894 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3895 type = allocate_type_zero(TYPE_IMAGINARY);
3896 type->imaginary.akind = atomic_type;
3898 type = allocate_type_zero(TYPE_ATOMIC);
3899 type->atomic.akind = atomic_type;
3902 } else if (type_specifiers != 0) {
3903 errorf(HERE, "multiple datatypes in declaration");
3906 /* FIXME: check type qualifiers here */
3908 type->base.qualifiers = qualifiers;
3909 type->base.modifiers = modifiers;
3911 type_t *result = typehash_insert(type);
3912 if (newtype && result != type) {
3916 specifiers->type = result;
3920 specifiers->type = type_error_type;
3924 static type_qualifiers_t parse_type_qualifiers(void)
3926 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3929 switch(token.type) {
3930 /* type qualifiers */
3931 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3932 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3933 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3934 /* microsoft extended type modifiers */
3935 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3936 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3937 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3938 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3939 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3948 * Parses an K&R identifier list and return a list of declarations.
3950 * @param last points to the last declaration in the list
3951 * @return the list of declarations
3953 static declaration_t *parse_identifier_list(declaration_t **last)
3955 declaration_t *declarations = NULL;
3956 declaration_t *last_declaration = NULL;
3958 declaration_t *const declaration = allocate_declaration_zero();
3959 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3960 declaration->source_position = token.source_position;
3961 declaration->symbol = token.v.symbol;
3964 if (last_declaration != NULL) {
3965 last_declaration->next = declaration;
3967 declarations = declaration;
3969 last_declaration = declaration;
3971 if (token.type != ',') {
3975 } while (token.type == T_IDENTIFIER);
3977 *last = last_declaration;
3978 return declarations;
3981 static type_t *automatic_type_conversion(type_t *orig_type);
3983 static void semantic_parameter(declaration_t *declaration)
3985 /* TODO: improve error messages */
3986 source_position_t const* const pos = &declaration->source_position;
3988 switch (declaration->declared_storage_class) {
3989 case STORAGE_CLASS_TYPEDEF:
3990 errorf(pos, "typedef not allowed in parameter list");
3993 /* Allowed storage classes */
3994 case STORAGE_CLASS_NONE:
3995 case STORAGE_CLASS_REGISTER:
3999 errorf(pos, "parameter may only have none or register storage class");
4003 type_t *const orig_type = declaration->type;
4004 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
4005 * sugar. Turn it into a pointer.
4006 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4007 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4009 type_t *const type = automatic_type_conversion(orig_type);
4010 declaration->type = type;
4012 if (is_type_incomplete(skip_typeref(type))) {
4013 errorf(pos, "parameter '%#T' is of incomplete type",
4014 orig_type, declaration->symbol);
4018 static declaration_t *parse_parameter(void)
4020 declaration_specifiers_t specifiers;
4021 memset(&specifiers, 0, sizeof(specifiers));
4023 parse_declaration_specifiers(&specifiers);
4025 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
4031 * Parses a function type parameter list and return a list of declarations.
4033 * @param last point to the last element of the list
4034 * @return the parameter list
4036 static declaration_t *parse_parameters(function_type_t *type, declaration_t **last)
4038 declaration_t *declarations = NULL;
4041 add_anchor_token(')');
4042 int saved_comma_state = save_and_reset_anchor_state(',');
4044 if (token.type == T_IDENTIFIER &&
4045 !is_typedef_symbol(token.v.symbol)) {
4046 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4047 if (la1_type == ',' || la1_type == ')') {
4048 type->kr_style_parameters = true;
4049 declarations = parse_identifier_list(last);
4050 goto parameters_finished;
4054 if (token.type == ')') {
4055 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4056 if (!(c_mode & _CXX))
4057 type->unspecified_parameters = 1;
4058 goto parameters_finished;
4061 declaration_t *declaration;
4062 declaration_t *last_declaration = NULL;
4063 function_parameter_t *parameter;
4064 function_parameter_t *last_parameter = NULL;
4067 switch(token.type) {
4071 goto parameters_finished;
4074 case T___extension__:
4076 declaration = parse_parameter();
4078 /* func(void) is not a parameter */
4079 if (last_parameter == NULL
4080 && token.type == ')'
4081 && declaration->symbol == NULL
4082 && skip_typeref(declaration->type) == type_void) {
4083 goto parameters_finished;
4085 semantic_parameter(declaration);
4087 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4088 memset(parameter, 0, sizeof(parameter[0]));
4089 parameter->type = declaration->type;
4091 if (last_parameter != NULL) {
4092 last_declaration->next = declaration;
4093 last_parameter->next = parameter;
4095 type->parameters = parameter;
4096 declarations = declaration;
4098 last_parameter = parameter;
4099 last_declaration = declaration;
4103 goto parameters_finished;
4105 if (token.type != ',') {
4106 goto parameters_finished;
4112 parameters_finished:
4113 rem_anchor_token(')');
4116 restore_anchor_state(',', saved_comma_state);
4117 *last = last_declaration;
4118 return declarations;
4121 restore_anchor_state(',', saved_comma_state);
4126 typedef enum construct_type_kind_t {
4131 } construct_type_kind_t;
4133 typedef struct construct_type_t construct_type_t;
4134 struct construct_type_t {
4135 construct_type_kind_t kind;
4136 construct_type_t *next;
4139 typedef struct parsed_pointer_t parsed_pointer_t;
4140 struct parsed_pointer_t {
4141 construct_type_t construct_type;
4142 type_qualifiers_t type_qualifiers;
4145 typedef struct construct_function_type_t construct_function_type_t;
4146 struct construct_function_type_t {
4147 construct_type_t construct_type;
4148 type_t *function_type;
4151 typedef struct parsed_array_t parsed_array_t;
4152 struct parsed_array_t {
4153 construct_type_t construct_type;
4154 type_qualifiers_t type_qualifiers;
4160 typedef struct construct_base_type_t construct_base_type_t;
4161 struct construct_base_type_t {
4162 construct_type_t construct_type;
4166 static construct_type_t *parse_pointer_declarator(void)
4170 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4171 memset(pointer, 0, sizeof(pointer[0]));
4172 pointer->construct_type.kind = CONSTRUCT_POINTER;
4173 pointer->type_qualifiers = parse_type_qualifiers();
4175 return (construct_type_t*) pointer;
4178 static construct_type_t *parse_array_declarator(void)
4181 add_anchor_token(']');
4183 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4184 memset(array, 0, sizeof(array[0]));
4185 array->construct_type.kind = CONSTRUCT_ARRAY;
4187 if (token.type == T_static) {
4188 array->is_static = true;
4192 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4193 if (type_qualifiers != 0) {
4194 if (token.type == T_static) {
4195 array->is_static = true;
4199 array->type_qualifiers = type_qualifiers;
4201 if (token.type == '*' && look_ahead(1)->type == ']') {
4202 array->is_variable = true;
4204 } else if (token.type != ']') {
4205 array->size = parse_assignment_expression();
4208 rem_anchor_token(']');
4212 return (construct_type_t*) array;
4215 static construct_type_t *parse_function_declarator(declaration_t *declaration)
4218 if (declaration != NULL) {
4219 type = allocate_type_zero(TYPE_FUNCTION);
4221 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
4223 if (mask & (mask-1)) {
4224 const char *first = NULL, *second = NULL;
4226 /* more than one calling convention set */
4227 if (declaration->modifiers & DM_CDECL) {
4228 if (first == NULL) first = "cdecl";
4229 else if (second == NULL) second = "cdecl";
4231 if (declaration->modifiers & DM_STDCALL) {
4232 if (first == NULL) first = "stdcall";
4233 else if (second == NULL) second = "stdcall";
4235 if (declaration->modifiers & DM_FASTCALL) {
4236 if (first == NULL) first = "fastcall";
4237 else if (second == NULL) second = "fastcall";
4239 if (declaration->modifiers & DM_THISCALL) {
4240 if (first == NULL) first = "thiscall";
4241 else if (second == NULL) second = "thiscall";
4243 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
4246 if (declaration->modifiers & DM_CDECL)
4247 type->function.calling_convention = CC_CDECL;
4248 else if (declaration->modifiers & DM_STDCALL)
4249 type->function.calling_convention = CC_STDCALL;
4250 else if (declaration->modifiers & DM_FASTCALL)
4251 type->function.calling_convention = CC_FASTCALL;
4252 else if (declaration->modifiers & DM_THISCALL)
4253 type->function.calling_convention = CC_THISCALL;
4255 type = allocate_type_zero(TYPE_FUNCTION);
4258 declaration_t *last;
4259 declaration_t *parameters = parse_parameters(&type->function, &last);
4260 if (declaration != NULL) {
4261 declaration->scope.declarations = parameters;
4262 declaration->scope.last_declaration = last;
4265 construct_function_type_t *construct_function_type =
4266 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4267 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4268 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4269 construct_function_type->function_type = type;
4271 return &construct_function_type->construct_type;
4274 static void fix_declaration_type(declaration_t *declaration)
4276 decl_modifiers_t declaration_modifiers = declaration->modifiers;
4277 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
4279 if (declaration_modifiers & DM_TRANSPARENT_UNION)
4280 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4282 if (declaration->type->base.modifiers == type_modifiers)
4285 type_t *copy = duplicate_type(declaration->type);
4286 copy->base.modifiers = type_modifiers;
4288 type_t *result = typehash_insert(copy);
4289 if (result != copy) {
4290 obstack_free(type_obst, copy);
4293 declaration->type = result;
4296 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
4297 bool may_be_abstract)
4299 /* construct a single linked list of construct_type_t's which describe
4300 * how to construct the final declarator type */
4301 construct_type_t *first = NULL;
4302 construct_type_t *last = NULL;
4303 gnu_attribute_t *attributes = NULL;
4305 decl_modifiers_t modifiers = parse_attributes(&attributes);
4308 while (token.type == '*') {
4309 construct_type_t *type = parse_pointer_declarator();
4319 /* TODO: find out if this is correct */
4320 modifiers |= parse_attributes(&attributes);
4323 if (declaration != NULL)
4324 declaration->modifiers |= modifiers;
4326 construct_type_t *inner_types = NULL;
4328 switch(token.type) {
4330 if (declaration == NULL) {
4331 errorf(HERE, "no identifier expected in typename");
4333 declaration->symbol = token.v.symbol;
4334 declaration->source_position = token.source_position;
4340 add_anchor_token(')');
4341 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4342 if (inner_types != NULL) {
4343 /* All later declarators only modify the return type, not declaration */
4346 rem_anchor_token(')');
4350 if (may_be_abstract)
4352 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4357 construct_type_t *p = last;
4360 construct_type_t *type;
4361 switch(token.type) {
4363 type = parse_function_declarator(declaration);
4366 type = parse_array_declarator();
4369 goto declarator_finished;
4372 /* insert in the middle of the list (behind p) */
4374 type->next = p->next;
4385 declarator_finished:
4386 /* append inner_types at the end of the list, we don't to set last anymore
4387 * as it's not needed anymore */
4389 assert(first == NULL);
4390 first = inner_types;
4392 last->next = inner_types;
4400 static void parse_declaration_attributes(declaration_t *declaration)
4402 gnu_attribute_t *attributes = NULL;
4403 decl_modifiers_t modifiers = parse_attributes(&attributes);
4405 if (declaration == NULL)
4408 declaration->modifiers |= modifiers;
4409 /* check if we have these stupid mode attributes... */
4410 type_t *old_type = declaration->type;
4411 if (old_type == NULL)
4414 gnu_attribute_t *attribute = attributes;
4415 for ( ; attribute != NULL; attribute = attribute->next) {
4416 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4419 atomic_type_kind_t akind = attribute->u.akind;
4420 if (!is_type_signed(old_type)) {
4422 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4423 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4424 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4425 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4427 panic("invalid akind in mode attribute");
4431 = make_atomic_type(akind, old_type->base.qualifiers);
4435 static type_t *construct_declarator_type(construct_type_t *construct_list,
4438 construct_type_t *iter = construct_list;
4439 for( ; iter != NULL; iter = iter->next) {
4440 switch(iter->kind) {
4441 case CONSTRUCT_INVALID:
4442 internal_errorf(HERE, "invalid type construction found");
4443 case CONSTRUCT_FUNCTION: {
4444 construct_function_type_t *construct_function_type
4445 = (construct_function_type_t*) iter;
4447 type_t *function_type = construct_function_type->function_type;
4449 function_type->function.return_type = type;
4451 type_t *skipped_return_type = skip_typeref(type);
4453 if (is_type_function(skipped_return_type)) {
4454 errorf(HERE, "function returning function is not allowed");
4455 } else if (is_type_array(skipped_return_type)) {
4456 errorf(HERE, "function returning array is not allowed");
4458 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4460 "type qualifiers in return type of function type are meaningless");
4464 type = function_type;
4468 case CONSTRUCT_POINTER: {
4469 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4470 type = make_pointer_type(type, parsed_pointer->type_qualifiers);
4474 case CONSTRUCT_ARRAY: {
4475 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4476 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4478 expression_t *size_expression = parsed_array->size;
4479 if (size_expression != NULL) {
4481 = create_implicit_cast(size_expression, type_size_t);
4484 array_type->base.qualifiers = parsed_array->type_qualifiers;
4485 array_type->array.element_type = type;
4486 array_type->array.is_static = parsed_array->is_static;
4487 array_type->array.is_variable = parsed_array->is_variable;
4488 array_type->array.size_expression = size_expression;
4490 if (size_expression != NULL) {
4491 if (is_constant_expression(size_expression)) {
4492 array_type->array.size_constant = true;
4493 array_type->array.size
4494 = fold_constant(size_expression);
4496 array_type->array.is_vla = true;
4500 type_t *skipped_type = skip_typeref(type);
4502 if (is_type_incomplete(skipped_type)) {
4503 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4504 } else if (is_type_function(skipped_type)) {
4505 errorf(HERE, "array of functions is not allowed");
4512 type_t *hashed_type = typehash_insert(type);
4513 if (hashed_type != type) {
4514 /* the function type was constructed earlier freeing it here will
4515 * destroy other types... */
4516 if (iter->kind != CONSTRUCT_FUNCTION) {
4526 static declaration_t *parse_declarator(
4527 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4529 declaration_t *const declaration = allocate_declaration_zero();
4530 declaration->source_position = specifiers->source_position;
4531 declaration->declared_storage_class = specifiers->declared_storage_class;
4532 declaration->modifiers = specifiers->modifiers;
4533 declaration->deprecated_string = specifiers->deprecated_string;
4534 declaration->get_property_sym = specifiers->get_property_sym;
4535 declaration->put_property_sym = specifiers->put_property_sym;
4536 declaration->is_inline = specifiers->is_inline;
4538 declaration->storage_class = specifiers->declared_storage_class;
4539 if (declaration->storage_class == STORAGE_CLASS_NONE &&
4540 scope != file_scope) {
4541 declaration->storage_class = STORAGE_CLASS_AUTO;
4544 if (specifiers->alignment != 0) {
4545 /* TODO: add checks here */
4546 declaration->alignment = specifiers->alignment;
4549 construct_type_t *construct_type
4550 = parse_inner_declarator(declaration, may_be_abstract);
4551 type_t *const type = specifiers->type;
4552 declaration->type = construct_declarator_type(construct_type, type);
4554 parse_declaration_attributes(declaration);
4556 fix_declaration_type(declaration);
4558 if (construct_type != NULL) {
4559 obstack_free(&temp_obst, construct_type);
4565 static type_t *parse_abstract_declarator(type_t *base_type)
4567 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4569 type_t *result = construct_declarator_type(construct_type, base_type);
4570 if (construct_type != NULL) {
4571 obstack_free(&temp_obst, construct_type);
4577 static declaration_t *append_declaration(declaration_t* const declaration)
4579 if (last_declaration != NULL) {
4580 last_declaration->next = declaration;
4582 scope->declarations = declaration;
4584 last_declaration = declaration;
4589 * Check if the declaration of main is suspicious. main should be a
4590 * function with external linkage, returning int, taking either zero
4591 * arguments, two, or three arguments of appropriate types, ie.
4593 * int main([ int argc, char **argv [, char **env ] ]).
4595 * @param decl the declaration to check
4596 * @param type the function type of the declaration
4598 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4600 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4601 warningf(&decl->source_position,
4602 "'main' is normally a non-static function");
4604 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4605 warningf(&decl->source_position,
4606 "return type of 'main' should be 'int', but is '%T'",
4607 func_type->return_type);
4609 const function_parameter_t *parm = func_type->parameters;
4611 type_t *const first_type = parm->type;
4612 if (!types_compatible(skip_typeref(first_type), type_int)) {
4613 warningf(&decl->source_position,
4614 "first argument of 'main' should be 'int', but is '%T'", first_type);
4618 type_t *const second_type = parm->type;
4619 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4620 warningf(&decl->source_position,
4621 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4625 type_t *const third_type = parm->type;
4626 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4627 warningf(&decl->source_position,
4628 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4632 goto warn_arg_count;
4636 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4642 * Check if a symbol is the equal to "main".
4644 static bool is_sym_main(const symbol_t *const sym)
4646 return strcmp(sym->string, "main") == 0;
4649 static declaration_t *record_declaration(
4650 declaration_t *const declaration,
4651 const bool is_definition)
4653 const symbol_t *const symbol = declaration->symbol;
4654 const namespace_t namespc = (namespace_t)declaration->namespc;
4656 assert(symbol != NULL);
4657 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4659 type_t *const orig_type = declaration->type;
4660 type_t *const type = skip_typeref(orig_type);
4661 if (is_type_function(type) &&
4662 type->function.unspecified_parameters &&
4663 warning.strict_prototypes &&
4664 previous_declaration == NULL) {
4665 warningf(&declaration->source_position,
4666 "function declaration '%#T' is not a prototype",
4670 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4671 check_type_of_main(declaration, &type->function);
4674 if (warning.nested_externs &&
4675 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4676 scope != file_scope) {
4677 warningf(&declaration->source_position,
4678 "nested extern declaration of '%#T'", declaration->type, symbol);
4681 assert(declaration != previous_declaration);
4682 if (previous_declaration != NULL &&
4683 previous_declaration->parent_scope == ¤t_function->scope &&
4684 scope->depth == previous_declaration->parent_scope->depth + 1) {
4685 errorf(&declaration->source_position,
4686 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4687 orig_type, symbol, previous_declaration->type, symbol,
4688 &previous_declaration->source_position);
4691 if (previous_declaration != NULL &&
4692 previous_declaration->parent_scope == scope) {
4693 /* can happen for K&R style declarations */
4694 if (previous_declaration->type == NULL) {
4695 previous_declaration->type = declaration->type;
4698 const type_t *prev_type = skip_typeref(previous_declaration->type);
4699 if (!types_compatible(type, prev_type)) {
4700 errorf(&declaration->source_position,
4701 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4702 orig_type, symbol, previous_declaration->type, symbol,
4703 &previous_declaration->source_position);
4705 unsigned old_storage_class = previous_declaration->storage_class;
4706 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4707 errorf(&declaration->source_position,
4708 "redeclaration of enum entry '%Y' (declared %P)",
4709 symbol, &previous_declaration->source_position);
4710 return previous_declaration;
4713 if (warning.redundant_decls &&
4715 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4716 !(previous_declaration->modifiers & DM_USED) &&
4717 !previous_declaration->used) {
4718 warningf(&previous_declaration->source_position,
4719 "unnecessary static forward declaration for '%#T'",
4720 previous_declaration->type, symbol);
4723 unsigned new_storage_class = declaration->storage_class;
4725 if (is_type_incomplete(prev_type)) {
4726 previous_declaration->type = type;
4730 /* pretend no storage class means extern for function
4731 * declarations (except if the previous declaration is neither
4732 * none nor extern) */
4733 if (is_type_function(type)) {
4734 if (prev_type->function.unspecified_parameters) {
4735 previous_declaration->type = type;
4739 switch (old_storage_class) {
4740 case STORAGE_CLASS_NONE:
4741 old_storage_class = STORAGE_CLASS_EXTERN;
4744 case STORAGE_CLASS_EXTERN:
4745 if (is_definition) {
4746 if (warning.missing_prototypes &&
4747 prev_type->function.unspecified_parameters &&
4748 !is_sym_main(symbol)) {
4749 warningf(&declaration->source_position,
4750 "no previous prototype for '%#T'",
4753 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4754 new_storage_class = STORAGE_CLASS_EXTERN;
4763 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4764 new_storage_class == STORAGE_CLASS_EXTERN) {
4765 warn_redundant_declaration:
4766 if (!is_definition &&
4767 warning.redundant_decls &&
4768 is_type_valid(prev_type) &&
4769 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4770 warningf(&declaration->source_position,
4771 "redundant declaration for '%Y' (declared %P)",
4772 symbol, &previous_declaration->source_position);
4774 } else if (current_function == NULL) {
4775 if (old_storage_class != STORAGE_CLASS_STATIC &&
4776 new_storage_class == STORAGE_CLASS_STATIC) {
4777 errorf(&declaration->source_position,
4778 "static declaration of '%Y' follows non-static declaration (declared %P)",
4779 symbol, &previous_declaration->source_position);
4780 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4781 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4782 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4784 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4786 goto error_redeclaration;
4787 goto warn_redundant_declaration;
4789 } else if (is_type_valid(prev_type)) {
4790 if (old_storage_class == new_storage_class) {
4791 error_redeclaration:
4792 errorf(&declaration->source_position,
4793 "redeclaration of '%Y' (declared %P)",
4794 symbol, &previous_declaration->source_position);
4796 errorf(&declaration->source_position,
4797 "redeclaration of '%Y' with different linkage (declared %P)",
4798 symbol, &previous_declaration->source_position);
4803 previous_declaration->modifiers |= declaration->modifiers;
4804 previous_declaration->is_inline |= declaration->is_inline;
4805 return previous_declaration;
4806 } else if (is_type_function(type)) {
4807 if (is_definition &&
4808 declaration->storage_class != STORAGE_CLASS_STATIC) {
4809 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4810 warningf(&declaration->source_position,
4811 "no previous prototype for '%#T'", orig_type, symbol);
4812 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4813 warningf(&declaration->source_position,
4814 "no previous declaration for '%#T'", orig_type,
4819 if (warning.missing_declarations &&
4820 scope == file_scope && (
4821 declaration->storage_class == STORAGE_CLASS_NONE ||
4822 declaration->storage_class == STORAGE_CLASS_THREAD
4824 warningf(&declaration->source_position,
4825 "no previous declaration for '%#T'", orig_type, symbol);
4829 assert(declaration->parent_scope == NULL);
4830 assert(scope != NULL);
4832 declaration->parent_scope = scope;
4834 environment_push(declaration);
4835 return append_declaration(declaration);
4838 static void parser_error_multiple_definition(declaration_t *declaration,
4839 const source_position_t *source_position)
4841 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4842 declaration->symbol, &declaration->source_position);
4845 static bool is_declaration_specifier(const token_t *token,
4846 bool only_specifiers_qualifiers)
4848 switch (token->type) {
4853 return is_typedef_symbol(token->v.symbol);
4855 case T___extension__:
4857 return !only_specifiers_qualifiers;
4864 static void parse_init_declarator_rest(declaration_t *declaration)
4868 type_t *orig_type = declaration->type;
4869 type_t *type = skip_typeref(orig_type);
4871 if (declaration->init.initializer != NULL) {
4872 parser_error_multiple_definition(declaration, HERE);
4875 bool must_be_constant = false;
4876 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4877 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
4878 declaration->parent_scope == file_scope) {
4879 must_be_constant = true;
4882 if (is_type_function(type)) {
4883 errorf(&declaration->source_position,
4884 "function '%#T' is initialized like a variable",
4885 orig_type, declaration->symbol);
4886 orig_type = type_error_type;
4889 parse_initializer_env_t env;
4890 env.type = orig_type;
4891 env.must_be_constant = must_be_constant;
4892 env.declaration = current_init_decl = declaration;
4894 initializer_t *initializer = parse_initializer(&env);
4895 current_init_decl = NULL;
4897 if (!is_type_function(type)) {
4898 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4899 * the array type size */
4900 declaration->type = env.type;
4901 declaration->init.initializer = initializer;
4905 /* parse rest of a declaration without any declarator */
4906 static void parse_anonymous_declaration_rest(
4907 const declaration_specifiers_t *specifiers)
4911 if (warning.other) {
4912 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4913 warningf(&specifiers->source_position,
4914 "useless storage class in empty declaration");
4917 type_t *type = specifiers->type;
4918 switch (type->kind) {
4919 case TYPE_COMPOUND_STRUCT:
4920 case TYPE_COMPOUND_UNION: {
4921 if (type->compound.declaration->symbol == NULL) {
4922 warningf(&specifiers->source_position,
4923 "unnamed struct/union that defines no instances");
4932 warningf(&specifiers->source_position, "empty declaration");
4937 #ifdef RECORD_EMPTY_DECLARATIONS
4938 declaration_t *const declaration = allocate_declaration_zero();
4939 declaration->type = specifiers->type;
4940 declaration->declared_storage_class = specifiers->declared_storage_class;
4941 declaration->source_position = specifiers->source_position;
4942 declaration->modifiers = specifiers->modifiers;
4943 declaration->storage_class = STORAGE_CLASS_NONE;
4945 append_declaration(declaration);
4949 static void parse_declaration_rest(declaration_t *ndeclaration,
4950 const declaration_specifiers_t *specifiers,
4951 parsed_declaration_func finished_declaration)
4953 add_anchor_token(';');
4954 add_anchor_token(',');
4956 declaration_t *declaration =
4957 finished_declaration(ndeclaration, token.type == '=');
4959 type_t *orig_type = declaration->type;
4960 type_t *type = skip_typeref(orig_type);
4962 if (warning.other &&
4963 type->kind != TYPE_FUNCTION &&
4964 declaration->is_inline &&
4965 is_type_valid(type)) {
4966 warningf(&declaration->source_position,
4967 "variable '%Y' declared 'inline'\n", declaration->symbol);
4970 if (token.type == '=') {
4971 parse_init_declarator_rest(declaration);
4974 if (token.type != ',')
4978 add_anchor_token('=');
4979 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4980 rem_anchor_token('=');
4985 rem_anchor_token(';');
4986 rem_anchor_token(',');
4989 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4991 symbol_t *symbol = declaration->symbol;
4992 if (symbol == NULL) {
4993 errorf(HERE, "anonymous declaration not valid as function parameter");
4996 namespace_t namespc = (namespace_t) declaration->namespc;
4997 if (namespc != NAMESPACE_NORMAL) {
4998 return record_declaration(declaration, false);
5001 declaration_t *previous_declaration = get_declaration(symbol, namespc);
5002 if (previous_declaration == NULL ||
5003 previous_declaration->parent_scope != scope) {
5004 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5009 if (is_definition) {
5010 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
5013 if (previous_declaration->type == NULL) {
5014 previous_declaration->type = declaration->type;
5015 previous_declaration->declared_storage_class = declaration->declared_storage_class;
5016 previous_declaration->storage_class = declaration->storage_class;
5017 previous_declaration->parent_scope = scope;
5018 return previous_declaration;
5020 return record_declaration(declaration, false);
5024 static void parse_declaration(parsed_declaration_func finished_declaration)
5026 declaration_specifiers_t specifiers;
5027 memset(&specifiers, 0, sizeof(specifiers));
5029 add_anchor_token(';');
5030 parse_declaration_specifiers(&specifiers);
5031 rem_anchor_token(';');
5033 if (token.type == ';') {
5034 parse_anonymous_declaration_rest(&specifiers);
5036 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5037 parse_declaration_rest(declaration, &specifiers, finished_declaration);
5041 static type_t *get_default_promoted_type(type_t *orig_type)
5043 type_t *result = orig_type;
5045 type_t *type = skip_typeref(orig_type);
5046 if (is_type_integer(type)) {
5047 result = promote_integer(type);
5048 } else if (type == type_float) {
5049 result = type_double;
5055 static void parse_kr_declaration_list(declaration_t *declaration)
5057 type_t *type = skip_typeref(declaration->type);
5058 if (!is_type_function(type))
5061 if (!type->function.kr_style_parameters)
5064 add_anchor_token('{');
5066 /* push function parameters */
5067 size_t const top = environment_top();
5068 scope_push(&declaration->scope);
5070 declaration_t *parameter = declaration->scope.declarations;
5071 for ( ; parameter != NULL; parameter = parameter->next) {
5072 assert(parameter->parent_scope == NULL);
5073 parameter->parent_scope = scope;
5074 environment_push(parameter);
5077 /* parse declaration list */
5078 while (is_declaration_specifier(&token, false)) {
5079 parse_declaration(finished_kr_declaration);
5082 /* pop function parameters */
5083 assert(scope == &declaration->scope);
5085 environment_pop_to(top);
5087 /* update function type */
5088 type_t *new_type = duplicate_type(type);
5090 function_parameter_t *parameters = NULL;
5091 function_parameter_t *last_parameter = NULL;
5093 declaration_t *parameter_declaration = declaration->scope.declarations;
5094 for( ; parameter_declaration != NULL;
5095 parameter_declaration = parameter_declaration->next) {
5096 type_t *parameter_type = parameter_declaration->type;
5097 if (parameter_type == NULL) {
5099 errorf(HERE, "no type specified for function parameter '%Y'",
5100 parameter_declaration->symbol);
5102 if (warning.implicit_int) {
5103 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5104 parameter_declaration->symbol);
5106 parameter_type = type_int;
5107 parameter_declaration->type = parameter_type;
5111 semantic_parameter(parameter_declaration);
5112 parameter_type = parameter_declaration->type;
5115 * we need the default promoted types for the function type
5117 parameter_type = get_default_promoted_type(parameter_type);
5119 function_parameter_t *function_parameter
5120 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5121 memset(function_parameter, 0, sizeof(function_parameter[0]));
5123 function_parameter->type = parameter_type;
5124 if (last_parameter != NULL) {
5125 last_parameter->next = function_parameter;
5127 parameters = function_parameter;
5129 last_parameter = function_parameter;
5132 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5134 new_type->function.parameters = parameters;
5135 new_type->function.unspecified_parameters = true;
5137 type = typehash_insert(new_type);
5138 if (type != new_type) {
5139 obstack_free(type_obst, new_type);
5142 declaration->type = type;
5144 rem_anchor_token('{');
5147 static bool first_err = true;
5150 * When called with first_err set, prints the name of the current function,
5153 static void print_in_function(void)
5157 diagnosticf("%s: In function '%Y':\n",
5158 current_function->source_position.input_name,
5159 current_function->symbol);
5164 * Check if all labels are defined in the current function.
5165 * Check if all labels are used in the current function.
5167 static void check_labels(void)
5169 for (const goto_statement_t *goto_statement = goto_first;
5170 goto_statement != NULL;
5171 goto_statement = goto_statement->next) {
5172 /* skip computed gotos */
5173 if (goto_statement->expression != NULL)
5176 declaration_t *label = goto_statement->label;
5179 if (label->source_position.input_name == NULL) {
5180 print_in_function();
5181 errorf(&goto_statement->base.source_position,
5182 "label '%Y' used but not defined", label->symbol);
5185 goto_first = goto_last = NULL;
5187 if (warning.unused_label) {
5188 for (const label_statement_t *label_statement = label_first;
5189 label_statement != NULL;
5190 label_statement = label_statement->next) {
5191 const declaration_t *label = label_statement->label;
5193 if (! label->used) {
5194 print_in_function();
5195 warningf(&label_statement->base.source_position,
5196 "label '%Y' defined but not used", label->symbol);
5200 label_first = label_last = NULL;
5203 static void warn_unused_decl(declaration_t *decl, declaration_t *end, char const *const what)
5205 for (; decl != NULL; decl = decl->next) {
5210 print_in_function();
5211 warningf(&decl->source_position, "%s '%Y' is unused", what, decl->symbol);
5212 } else if (!decl->read) {
5213 print_in_function();
5214 warningf(&decl->source_position, "%s '%Y' is never read", what, decl->symbol);
5222 static void check_unused_variables(statement_t *const stmt, void *const env)
5226 switch (stmt->kind) {
5227 case STATEMENT_DECLARATION: {
5228 declaration_statement_t const *const decls = &stmt->declaration;
5229 warn_unused_decl(decls->declarations_begin, decls->declarations_end, "variable");
5234 warn_unused_decl(stmt->fors.scope.declarations, NULL, "variable");
5243 * Check declarations of current_function for unused entities.
5245 static void check_declarations(void)
5247 if (warning.unused_parameter) {
5248 const scope_t *scope = ¤t_function->scope;
5250 /* do not issue unused warnings for main */
5251 if (!is_sym_main(current_function->symbol)) {
5252 warn_unused_decl(scope->declarations, NULL, "parameter");
5255 if (warning.unused_variable) {
5256 walk_statements(current_function->init.statement, check_unused_variables, NULL);
5260 static int determine_truth(expression_t const* const cond)
5263 !is_constant_expression(cond) ? 0 :
5264 fold_constant(cond) != 0 ? 1 :
5268 static bool expression_returns(expression_t const *const expr)
5270 switch (expr->kind) {
5272 expression_t const *const func = expr->call.function;
5273 if (func->kind == EXPR_REFERENCE) {
5274 declaration_t const *const decl = func->reference.declaration;
5275 if (decl != NULL && decl->modifiers & DM_NORETURN)
5279 if (!expression_returns(func))
5282 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5283 if (!expression_returns(arg->expression))
5290 case EXPR_REFERENCE:
5292 case EXPR_CHARACTER_CONSTANT:
5293 case EXPR_WIDE_CHARACTER_CONSTANT:
5294 case EXPR_STRING_LITERAL:
5295 case EXPR_WIDE_STRING_LITERAL:
5296 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5297 case EXPR_LABEL_ADDRESS:
5298 case EXPR_CLASSIFY_TYPE:
5299 case EXPR_SIZEOF: // TODO handle obscure VLA case
5302 case EXPR_BUILTIN_SYMBOL:
5303 case EXPR_BUILTIN_CONSTANT_P:
5304 case EXPR_BUILTIN_PREFETCH:
5306 case EXPR_STATEMENT: // TODO implement
5309 case EXPR_CONDITIONAL:
5310 // TODO handle constant expression
5312 expression_returns(expr->conditional.condition) && (
5313 expression_returns(expr->conditional.true_expression) ||
5314 expression_returns(expr->conditional.false_expression)
5318 return expression_returns(expr->select.compound);
5320 case EXPR_ARRAY_ACCESS:
5322 expression_returns(expr->array_access.array_ref) &&
5323 expression_returns(expr->array_access.index);
5326 return expression_returns(expr->va_starte.ap);
5329 return expression_returns(expr->va_arge.ap);
5331 EXPR_UNARY_CASES_MANDATORY
5332 return expression_returns(expr->unary.value);
5334 case EXPR_UNARY_THROW:
5338 // TODO handle constant lhs of && and ||
5340 expression_returns(expr->binary.left) &&
5341 expression_returns(expr->binary.right);
5348 panic("unhandled expression");
5351 static bool noreturn_candidate;
5353 static void check_reachable(statement_t *const stmt)
5355 if (stmt->base.reachable)
5357 if (stmt->kind != STATEMENT_DO_WHILE)
5358 stmt->base.reachable = true;
5360 statement_t *last = stmt;
5362 switch (stmt->kind) {
5363 case STATEMENT_INVALID:
5364 case STATEMENT_EMPTY:
5365 case STATEMENT_DECLARATION:
5367 next = stmt->base.next;
5370 case STATEMENT_COMPOUND:
5371 next = stmt->compound.statements;
5374 case STATEMENT_RETURN:
5375 noreturn_candidate = false;
5378 case STATEMENT_IF: {
5379 if_statement_t const* const ifs = &stmt->ifs;
5380 int const val = determine_truth(ifs->condition);
5383 check_reachable(ifs->true_statement);
5388 if (ifs->false_statement != NULL) {
5389 check_reachable(ifs->false_statement);
5393 next = stmt->base.next;
5397 case STATEMENT_SWITCH: {
5398 switch_statement_t const *const switchs = &stmt->switchs;
5399 expression_t const *const expr = switchs->expression;
5401 if (is_constant_expression(expr)) {
5402 long const val = fold_constant(expr);
5403 case_label_statement_t * defaults = NULL;
5404 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5405 if (i->expression == NULL) {
5410 if (i->first_case <= val && val <= i->last_case) {
5411 check_reachable((statement_t*)i);
5416 if (defaults != NULL) {
5417 check_reachable((statement_t*)defaults);
5421 bool has_default = false;
5422 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5423 if (i->expression == NULL)
5426 check_reachable((statement_t*)i);
5433 next = stmt->base.next;
5437 case STATEMENT_EXPRESSION: {
5438 /* Check for noreturn function call */
5439 expression_t const *const expr = stmt->expression.expression;
5440 if (!expression_returns(expr))
5443 next = stmt->base.next;
5447 case STATEMENT_CONTINUE: {
5448 statement_t *parent = stmt;
5450 parent = parent->base.parent;
5451 if (parent == NULL) /* continue not within loop */
5455 switch (parent->kind) {
5456 case STATEMENT_WHILE: goto continue_while;
5457 case STATEMENT_DO_WHILE: goto continue_do_while;
5458 case STATEMENT_FOR: goto continue_for;
5465 case STATEMENT_BREAK: {
5466 statement_t *parent = stmt;
5468 parent = parent->base.parent;
5469 if (parent == NULL) /* break not within loop/switch */
5472 switch (parent->kind) {
5473 case STATEMENT_SWITCH:
5474 case STATEMENT_WHILE:
5475 case STATEMENT_DO_WHILE:
5478 next = parent->base.next;
5479 goto found_break_parent;
5488 case STATEMENT_GOTO:
5489 if (stmt->gotos.expression) {
5490 statement_t *parent = stmt->base.parent;
5491 if (parent == NULL) /* top level goto */
5495 next = stmt->gotos.label->init.statement;
5496 if (next == NULL) /* missing label */
5501 case STATEMENT_LABEL:
5502 next = stmt->label.statement;
5505 case STATEMENT_CASE_LABEL:
5506 next = stmt->case_label.statement;
5509 case STATEMENT_WHILE: {
5510 while_statement_t const *const whiles = &stmt->whiles;
5511 int const val = determine_truth(whiles->condition);
5514 check_reachable(whiles->body);
5519 next = stmt->base.next;
5523 case STATEMENT_DO_WHILE:
5524 next = stmt->do_while.body;
5527 case STATEMENT_FOR: {
5528 for_statement_t *const fors = &stmt->fors;
5530 if (fors->condition_reachable)
5532 fors->condition_reachable = true;
5534 expression_t const *const cond = fors->condition;
5536 cond == NULL ? 1 : determine_truth(cond);
5539 check_reachable(fors->body);
5544 next = stmt->base.next;
5548 case STATEMENT_MS_TRY: {
5549 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5550 check_reachable(ms_try->try_statement);
5551 next = ms_try->final_statement;
5555 case STATEMENT_LEAVE: {
5556 statement_t *parent = stmt;
5558 parent = parent->base.parent;
5559 if (parent == NULL) /* __leave not within __try */
5562 if (parent->kind == STATEMENT_MS_TRY) {
5564 next = parent->ms_try.final_statement;
5572 while (next == NULL) {
5573 next = last->base.parent;
5575 noreturn_candidate = false;
5577 type_t *const type = current_function->type;
5578 assert(is_type_function(type));
5579 type_t *const ret = skip_typeref(type->function.return_type);
5580 if (warning.return_type &&
5581 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5582 is_type_valid(ret) &&
5583 !is_sym_main(current_function->symbol)) {
5584 warningf(&stmt->base.source_position,
5585 "control reaches end of non-void function");
5590 switch (next->kind) {
5591 case STATEMENT_INVALID:
5592 case STATEMENT_EMPTY:
5593 case STATEMENT_DECLARATION:
5594 case STATEMENT_EXPRESSION:
5596 case STATEMENT_RETURN:
5597 case STATEMENT_CONTINUE:
5598 case STATEMENT_BREAK:
5599 case STATEMENT_GOTO:
5600 case STATEMENT_LEAVE:
5601 panic("invalid control flow in function");
5603 case STATEMENT_COMPOUND:
5605 case STATEMENT_SWITCH:
5606 case STATEMENT_LABEL:
5607 case STATEMENT_CASE_LABEL:
5609 next = next->base.next;
5612 case STATEMENT_WHILE: {
5614 if (next->base.reachable)
5616 next->base.reachable = true;
5618 while_statement_t const *const whiles = &next->whiles;
5619 int const val = determine_truth(whiles->condition);
5622 check_reachable(whiles->body);
5628 next = next->base.next;
5632 case STATEMENT_DO_WHILE: {
5634 if (next->base.reachable)
5636 next->base.reachable = true;
5638 do_while_statement_t const *const dw = &next->do_while;
5639 int const val = determine_truth(dw->condition);
5642 check_reachable(dw->body);
5648 next = next->base.next;
5652 case STATEMENT_FOR: {
5654 for_statement_t *const fors = &next->fors;
5656 fors->step_reachable = true;
5658 if (fors->condition_reachable)
5660 fors->condition_reachable = true;
5662 expression_t const *const cond = fors->condition;
5664 cond == NULL ? 1 : determine_truth(cond);
5667 check_reachable(fors->body);
5673 next = next->base.next;
5677 case STATEMENT_MS_TRY:
5679 next = next->ms_try.final_statement;
5684 check_reachable(next);
5687 static void check_unreachable(statement_t* const stmt, void *const env)
5691 switch (stmt->kind) {
5692 case STATEMENT_DO_WHILE:
5693 if (!stmt->base.reachable) {
5694 expression_t const *const cond = stmt->do_while.condition;
5695 if (determine_truth(cond) >= 0) {
5696 warningf(&cond->base.source_position,
5697 "condition of do-while-loop is unreachable");
5702 case STATEMENT_FOR: {
5703 for_statement_t const* const fors = &stmt->fors;
5705 // if init and step are unreachable, cond is unreachable, too
5706 if (!stmt->base.reachable && !fors->step_reachable) {
5707 warningf(&stmt->base.source_position, "statement is unreachable");
5709 if (!stmt->base.reachable && fors->initialisation != NULL) {
5710 warningf(&fors->initialisation->base.source_position,
5711 "initialisation of for-statement is unreachable");
5714 if (!fors->condition_reachable && fors->condition != NULL) {
5715 warningf(&fors->condition->base.source_position,
5716 "condition of for-statement is unreachable");
5719 if (!fors->step_reachable && fors->step != NULL) {
5720 warningf(&fors->step->base.source_position,
5721 "step of for-statement is unreachable");
5727 case STATEMENT_COMPOUND:
5728 if (stmt->compound.statements != NULL)
5733 if (!stmt->base.reachable)
5734 warningf(&stmt->base.source_position, "statement is unreachable");
5739 static void parse_external_declaration(void)
5741 /* function-definitions and declarations both start with declaration
5743 declaration_specifiers_t specifiers;
5744 memset(&specifiers, 0, sizeof(specifiers));
5746 add_anchor_token(';');
5747 parse_declaration_specifiers(&specifiers);
5748 rem_anchor_token(';');
5750 /* must be a declaration */
5751 if (token.type == ';') {
5752 parse_anonymous_declaration_rest(&specifiers);
5756 add_anchor_token(',');
5757 add_anchor_token('=');
5758 add_anchor_token(';');
5759 add_anchor_token('{');
5761 /* declarator is common to both function-definitions and declarations */
5762 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5764 rem_anchor_token('{');
5765 rem_anchor_token(';');
5766 rem_anchor_token('=');
5767 rem_anchor_token(',');
5769 /* must be a declaration */
5770 switch (token.type) {
5774 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5778 /* must be a function definition */
5779 parse_kr_declaration_list(ndeclaration);
5781 if (token.type != '{') {
5782 parse_error_expected("while parsing function definition", '{', NULL);
5783 eat_until_matching_token(';');
5787 type_t *type = ndeclaration->type;
5789 /* note that we don't skip typerefs: the standard doesn't allow them here
5790 * (so we can't use is_type_function here) */
5791 if (type->kind != TYPE_FUNCTION) {
5792 if (is_type_valid(type)) {
5793 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5794 type, ndeclaration->symbol);
5800 if (warning.aggregate_return &&
5801 is_type_compound(skip_typeref(type->function.return_type))) {
5802 warningf(HERE, "function '%Y' returns an aggregate",
5803 ndeclaration->symbol);
5805 if (warning.traditional && !type->function.unspecified_parameters) {
5806 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5807 ndeclaration->symbol);
5809 if (warning.old_style_definition && type->function.unspecified_parameters) {
5810 warningf(HERE, "old-style function definition '%Y'",
5811 ndeclaration->symbol);
5814 /* § 6.7.5.3 (14) a function definition with () means no
5815 * parameters (and not unspecified parameters) */
5816 if (type->function.unspecified_parameters
5817 && type->function.parameters == NULL
5818 && !type->function.kr_style_parameters) {
5819 type_t *duplicate = duplicate_type(type);
5820 duplicate->function.unspecified_parameters = false;
5822 type = typehash_insert(duplicate);
5823 if (type != duplicate) {
5824 obstack_free(type_obst, duplicate);
5826 ndeclaration->type = type;
5829 declaration_t *const declaration = record_declaration(ndeclaration, true);
5830 if (ndeclaration != declaration) {
5831 declaration->scope = ndeclaration->scope;
5833 type = skip_typeref(declaration->type);
5835 /* push function parameters and switch scope */
5836 size_t const top = environment_top();
5837 scope_push(&declaration->scope);
5839 declaration_t *parameter = declaration->scope.declarations;
5840 for( ; parameter != NULL; parameter = parameter->next) {
5841 if (parameter->parent_scope == &ndeclaration->scope) {
5842 parameter->parent_scope = scope;
5844 assert(parameter->parent_scope == NULL
5845 || parameter->parent_scope == scope);
5846 parameter->parent_scope = scope;
5847 if (parameter->symbol == NULL) {
5848 errorf(¶meter->source_position, "parameter name omitted");
5851 environment_push(parameter);
5854 if (declaration->init.statement != NULL) {
5855 parser_error_multiple_definition(declaration, HERE);
5858 /* parse function body */
5859 int label_stack_top = label_top();
5860 declaration_t *old_current_function = current_function;
5861 current_function = declaration;
5862 current_parent = NULL;
5864 statement_t *const body = parse_compound_statement(false);
5865 declaration->init.statement = body;
5868 check_declarations();
5869 if (warning.return_type ||
5870 warning.unreachable_code ||
5871 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5872 noreturn_candidate = true;
5873 check_reachable(body);
5874 if (warning.unreachable_code)
5875 walk_statements(body, check_unreachable, NULL);
5876 if (warning.missing_noreturn &&
5877 noreturn_candidate &&
5878 !(declaration->modifiers & DM_NORETURN)) {
5879 warningf(&body->base.source_position,
5880 "function '%#T' is candidate for attribute 'noreturn'",
5881 type, declaration->symbol);
5885 assert(current_parent == NULL);
5886 assert(current_function == declaration);
5887 current_function = old_current_function;
5888 label_pop_to(label_stack_top);
5891 assert(scope == &declaration->scope);
5893 environment_pop_to(top);
5896 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5897 source_position_t *source_position,
5898 const symbol_t *symbol)
5900 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5902 type->bitfield.base_type = base_type;
5903 type->bitfield.size_expression = size;
5906 type_t *skipped_type = skip_typeref(base_type);
5907 if (!is_type_integer(skipped_type)) {
5908 errorf(HERE, "bitfield base type '%T' is not an integer type",
5912 bit_size = skipped_type->base.size * 8;
5915 if (is_constant_expression(size)) {
5916 long v = fold_constant(size);
5919 errorf(source_position, "negative width in bit-field '%Y'",
5921 } else if (v == 0) {
5922 errorf(source_position, "zero width for bit-field '%Y'",
5924 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5925 errorf(source_position, "width of '%Y' exceeds its type",
5928 type->bitfield.bit_size = v;
5935 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5938 declaration_t *iter = compound_declaration->scope.declarations;
5939 for( ; iter != NULL; iter = iter->next) {
5940 if (iter->namespc != NAMESPACE_NORMAL)
5943 if (iter->symbol == NULL) {
5944 type_t *type = skip_typeref(iter->type);
5945 if (is_type_compound(type)) {
5946 declaration_t *result
5947 = find_compound_entry(type->compound.declaration, symbol);
5954 if (iter->symbol == symbol) {
5962 static void parse_compound_declarators(declaration_t *struct_declaration,
5963 const declaration_specifiers_t *specifiers)
5965 declaration_t *last_declaration = struct_declaration->scope.declarations;
5966 if (last_declaration != NULL) {
5967 while (last_declaration->next != NULL) {
5968 last_declaration = last_declaration->next;
5973 declaration_t *declaration;
5975 if (token.type == ':') {
5976 source_position_t source_position = *HERE;
5979 type_t *base_type = specifiers->type;
5980 expression_t *size = parse_constant_expression();
5982 type_t *type = make_bitfield_type(base_type, size,
5983 &source_position, sym_anonymous);
5985 declaration = allocate_declaration_zero();
5986 declaration->namespc = NAMESPACE_NORMAL;
5987 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5988 declaration->storage_class = STORAGE_CLASS_NONE;
5989 declaration->source_position = source_position;
5990 declaration->modifiers = specifiers->modifiers;
5991 declaration->type = type;
5993 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5995 type_t *orig_type = declaration->type;
5996 type_t *type = skip_typeref(orig_type);
5998 if (token.type == ':') {
5999 source_position_t source_position = *HERE;
6001 expression_t *size = parse_constant_expression();
6003 type_t *bitfield_type = make_bitfield_type(orig_type, size,
6004 &source_position, declaration->symbol);
6005 declaration->type = bitfield_type;
6007 /* TODO we ignore arrays for now... what is missing is a check
6008 * that they're at the end of the struct */
6009 if (is_type_incomplete(type) && !is_type_array(type)) {
6011 "compound member '%Y' has incomplete type '%T'",
6012 declaration->symbol, orig_type);
6013 } else if (is_type_function(type)) {
6014 errorf(HERE, "compound member '%Y' must not have function type '%T'",
6015 declaration->symbol, orig_type);
6020 /* make sure we don't define a symbol multiple times */
6021 symbol_t *symbol = declaration->symbol;
6022 if (symbol != NULL) {
6023 declaration_t *prev_decl
6024 = find_compound_entry(struct_declaration, symbol);
6026 if (prev_decl != NULL) {
6027 assert(prev_decl->symbol == symbol);
6028 errorf(&declaration->source_position,
6029 "multiple declarations of symbol '%Y' (declared %P)",
6030 symbol, &prev_decl->source_position);
6034 /* append declaration */
6035 if (last_declaration != NULL) {
6036 last_declaration->next = declaration;
6038 struct_declaration->scope.declarations = declaration;
6040 last_declaration = declaration;
6042 if (token.type != ',')
6052 static void parse_compound_type_entries(declaration_t *compound_declaration)
6055 add_anchor_token('}');
6057 while (token.type != '}') {
6058 if (token.type == T_EOF) {
6059 errorf(HERE, "EOF while parsing struct");
6062 declaration_specifiers_t specifiers;
6063 memset(&specifiers, 0, sizeof(specifiers));
6064 parse_declaration_specifiers(&specifiers);
6066 parse_compound_declarators(compound_declaration, &specifiers);
6068 rem_anchor_token('}');
6072 static type_t *parse_typename(void)
6074 declaration_specifiers_t specifiers;
6075 memset(&specifiers, 0, sizeof(specifiers));
6076 parse_declaration_specifiers(&specifiers);
6077 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
6078 /* TODO: improve error message, user does probably not know what a
6079 * storage class is...
6081 errorf(HERE, "typename may not have a storage class");
6084 type_t *result = parse_abstract_declarator(specifiers.type);
6092 typedef expression_t* (*parse_expression_function)(void);
6093 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6095 typedef struct expression_parser_function_t expression_parser_function_t;
6096 struct expression_parser_function_t {
6097 parse_expression_function parser;
6098 unsigned infix_precedence;
6099 parse_expression_infix_function infix_parser;
6102 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6105 * Prints an error message if an expression was expected but not read
6107 static expression_t *expected_expression_error(void)
6109 /* skip the error message if the error token was read */
6110 if (token.type != T_ERROR) {
6111 errorf(HERE, "expected expression, got token '%K'", &token);
6115 return create_invalid_expression();
6119 * Parse a string constant.
6121 static expression_t *parse_string_const(void)
6124 if (token.type == T_STRING_LITERAL) {
6125 string_t res = token.v.string;
6127 while (token.type == T_STRING_LITERAL) {
6128 res = concat_strings(&res, &token.v.string);
6131 if (token.type != T_WIDE_STRING_LITERAL) {
6132 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6133 /* note: that we use type_char_ptr here, which is already the
6134 * automatic converted type. revert_automatic_type_conversion
6135 * will construct the array type */
6136 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6137 cnst->string.value = res;
6141 wres = concat_string_wide_string(&res, &token.v.wide_string);
6143 wres = token.v.wide_string;
6148 switch (token.type) {
6149 case T_WIDE_STRING_LITERAL:
6150 wres = concat_wide_strings(&wres, &token.v.wide_string);
6153 case T_STRING_LITERAL:
6154 wres = concat_wide_string_string(&wres, &token.v.string);
6158 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6159 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6160 cnst->wide_string.value = wres;
6169 * Parse an integer constant.
6171 static expression_t *parse_int_const(void)
6173 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6174 cnst->base.source_position = *HERE;
6175 cnst->base.type = token.datatype;
6176 cnst->conste.v.int_value = token.v.intvalue;
6184 * Parse a character constant.
6186 static expression_t *parse_character_constant(void)
6188 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6190 cnst->base.source_position = *HERE;
6191 cnst->base.type = token.datatype;
6192 cnst->conste.v.character = token.v.string;
6194 if (cnst->conste.v.character.size != 1) {
6195 if (warning.multichar && GNU_MODE) {
6196 warningf(HERE, "multi-character character constant");
6198 errorf(HERE, "more than 1 characters in character constant");
6207 * Parse a wide character constant.
6209 static expression_t *parse_wide_character_constant(void)
6211 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6213 cnst->base.source_position = *HERE;
6214 cnst->base.type = token.datatype;
6215 cnst->conste.v.wide_character = token.v.wide_string;
6217 if (cnst->conste.v.wide_character.size != 1) {
6218 if (warning.multichar && GNU_MODE) {
6219 warningf(HERE, "multi-character character constant");
6221 errorf(HERE, "more than 1 characters in character constant");
6230 * Parse a float constant.
6232 static expression_t *parse_float_const(void)
6234 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6235 cnst->base.type = token.datatype;
6236 cnst->conste.v.float_value = token.v.floatvalue;
6243 static declaration_t *create_implicit_function(symbol_t *symbol,
6244 const source_position_t *source_position)
6246 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6247 ntype->function.return_type = type_int;
6248 ntype->function.unspecified_parameters = true;
6250 type_t *type = typehash_insert(ntype);
6251 if (type != ntype) {
6255 declaration_t *const declaration = allocate_declaration_zero();
6256 declaration->storage_class = STORAGE_CLASS_EXTERN;
6257 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
6258 declaration->type = type;
6259 declaration->symbol = symbol;
6260 declaration->source_position = *source_position;
6261 declaration->implicit = true;
6263 bool strict_prototypes_old = warning.strict_prototypes;
6264 warning.strict_prototypes = false;
6265 record_declaration(declaration, false);
6266 warning.strict_prototypes = strict_prototypes_old;
6272 * Creates a return_type (func)(argument_type) function type if not
6275 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6276 type_t *argument_type2)
6278 function_parameter_t *parameter2
6279 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6280 memset(parameter2, 0, sizeof(parameter2[0]));
6281 parameter2->type = argument_type2;
6283 function_parameter_t *parameter1
6284 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6285 memset(parameter1, 0, sizeof(parameter1[0]));
6286 parameter1->type = argument_type1;
6287 parameter1->next = parameter2;
6289 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6290 type->function.return_type = return_type;
6291 type->function.parameters = parameter1;
6293 type_t *result = typehash_insert(type);
6294 if (result != type) {
6302 * Creates a return_type (func)(argument_type) function type if not
6305 * @param return_type the return type
6306 * @param argument_type the argument type
6308 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6310 function_parameter_t *parameter
6311 = obstack_alloc(type_obst, sizeof(parameter[0]));
6312 memset(parameter, 0, sizeof(parameter[0]));
6313 parameter->type = argument_type;
6315 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6316 type->function.return_type = return_type;
6317 type->function.parameters = parameter;
6319 type_t *result = typehash_insert(type);
6320 if (result != type) {
6327 static type_t *make_function_0_type(type_t *return_type)
6329 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6330 type->function.return_type = return_type;
6331 type->function.parameters = NULL;
6333 type_t *result = typehash_insert(type);
6334 if (result != type) {
6342 * Creates a function type for some function like builtins.
6344 * @param symbol the symbol describing the builtin
6346 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6348 switch(symbol->ID) {
6349 case T___builtin_alloca:
6350 return make_function_1_type(type_void_ptr, type_size_t);
6351 case T___builtin_huge_val:
6352 return make_function_0_type(type_double);
6353 case T___builtin_inf:
6354 return make_function_0_type(type_double);
6355 case T___builtin_inff:
6356 return make_function_0_type(type_float);
6357 case T___builtin_infl:
6358 return make_function_0_type(type_long_double);
6359 case T___builtin_nan:
6360 return make_function_1_type(type_double, type_char_ptr);
6361 case T___builtin_nanf:
6362 return make_function_1_type(type_float, type_char_ptr);
6363 case T___builtin_nanl:
6364 return make_function_1_type(type_long_double, type_char_ptr);
6365 case T___builtin_va_end:
6366 return make_function_1_type(type_void, type_valist);
6367 case T___builtin_expect:
6368 return make_function_2_type(type_long, type_long, type_long);
6370 internal_errorf(HERE, "not implemented builtin symbol found");
6375 * Performs automatic type cast as described in § 6.3.2.1.
6377 * @param orig_type the original type
6379 static type_t *automatic_type_conversion(type_t *orig_type)
6381 type_t *type = skip_typeref(orig_type);
6382 if (is_type_array(type)) {
6383 array_type_t *array_type = &type->array;
6384 type_t *element_type = array_type->element_type;
6385 unsigned qualifiers = array_type->base.qualifiers;
6387 return make_pointer_type(element_type, qualifiers);
6390 if (is_type_function(type)) {
6391 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6398 * reverts the automatic casts of array to pointer types and function
6399 * to function-pointer types as defined § 6.3.2.1
6401 type_t *revert_automatic_type_conversion(const expression_t *expression)
6403 switch (expression->kind) {
6404 case EXPR_REFERENCE: return expression->reference.declaration->type;
6407 return get_qualified_type(expression->select.compound_entry->type,
6408 expression->base.type->base.qualifiers);
6410 case EXPR_UNARY_DEREFERENCE: {
6411 const expression_t *const value = expression->unary.value;
6412 type_t *const type = skip_typeref(value->base.type);
6413 assert(is_type_pointer(type));
6414 return type->pointer.points_to;
6417 case EXPR_BUILTIN_SYMBOL:
6418 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6420 case EXPR_ARRAY_ACCESS: {
6421 const expression_t *array_ref = expression->array_access.array_ref;
6422 type_t *type_left = skip_typeref(array_ref->base.type);
6423 if (!is_type_valid(type_left))
6425 assert(is_type_pointer(type_left));
6426 return type_left->pointer.points_to;
6429 case EXPR_STRING_LITERAL: {
6430 size_t size = expression->string.value.size;
6431 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6434 case EXPR_WIDE_STRING_LITERAL: {
6435 size_t size = expression->wide_string.value.size;
6436 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6439 case EXPR_COMPOUND_LITERAL:
6440 return expression->compound_literal.type;
6445 return expression->base.type;
6448 static expression_t *parse_reference(void)
6450 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6452 reference_expression_t *ref = &expression->reference;
6453 symbol_t *const symbol = token.v.symbol;
6455 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6457 if (declaration == NULL) {
6458 if (!strict_mode && look_ahead(1)->type == '(') {
6459 /* an implicitly declared function */
6460 if (warning.implicit_function_declaration) {
6461 warningf(HERE, "implicit declaration of function '%Y'",
6465 declaration = create_implicit_function(symbol, HERE);
6467 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6468 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6472 type_t *orig_type = declaration->type;
6474 /* we always do the auto-type conversions; the & and sizeof parser contains
6475 * code to revert this! */
6476 type_t *type = automatic_type_conversion(orig_type);
6478 ref->declaration = declaration;
6479 ref->base.type = type;
6481 /* this declaration is used */
6482 declaration->used = true;
6484 if (declaration->parent_scope != file_scope &&
6485 declaration->parent_scope->depth < current_function->scope.depth &&
6486 is_type_valid(orig_type) && !is_type_function(orig_type)) {
6487 /* access of a variable from an outer function */
6488 declaration->address_taken = true;
6489 current_function->need_closure = true;
6492 /* check for deprecated functions */
6493 if (warning.deprecated_declarations &&
6494 declaration->modifiers & DM_DEPRECATED) {
6495 char const *const prefix = is_type_function(declaration->type) ?
6496 "function" : "variable";
6498 if (declaration->deprecated_string != NULL) {
6499 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6500 prefix, declaration->symbol, &declaration->source_position,
6501 declaration->deprecated_string);
6503 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6504 declaration->symbol, &declaration->source_position);
6507 if (warning.init_self && declaration == current_init_decl && !in_type_prop) {
6508 current_init_decl = NULL;
6509 warningf(HERE, "variable '%#T' is initialized by itself",
6510 declaration->type, declaration->symbol);
6517 static bool semantic_cast(expression_t *cast)
6519 expression_t *expression = cast->unary.value;
6520 type_t *orig_dest_type = cast->base.type;
6521 type_t *orig_type_right = expression->base.type;
6522 type_t const *dst_type = skip_typeref(orig_dest_type);
6523 type_t const *src_type = skip_typeref(orig_type_right);
6524 source_position_t const *pos = &cast->base.source_position;
6526 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6527 if (dst_type == type_void)
6530 /* only integer and pointer can be casted to pointer */
6531 if (is_type_pointer(dst_type) &&
6532 !is_type_pointer(src_type) &&
6533 !is_type_integer(src_type) &&
6534 is_type_valid(src_type)) {
6535 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6539 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6540 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6544 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6545 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6549 if (warning.cast_qual &&
6550 is_type_pointer(src_type) &&
6551 is_type_pointer(dst_type)) {
6552 type_t *src = skip_typeref(src_type->pointer.points_to);
6553 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6554 unsigned missing_qualifiers =
6555 src->base.qualifiers & ~dst->base.qualifiers;
6556 if (missing_qualifiers != 0) {
6558 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6559 missing_qualifiers, orig_type_right);
6565 static expression_t *parse_compound_literal(type_t *type)
6567 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6569 parse_initializer_env_t env;
6571 env.declaration = NULL;
6572 env.must_be_constant = false;
6573 initializer_t *initializer = parse_initializer(&env);
6576 expression->compound_literal.initializer = initializer;
6577 expression->compound_literal.type = type;
6578 expression->base.type = automatic_type_conversion(type);
6584 * Parse a cast expression.
6586 static expression_t *parse_cast(void)
6588 add_anchor_token(')');
6590 source_position_t source_position = token.source_position;
6592 type_t *type = parse_typename();
6594 rem_anchor_token(')');
6597 if (token.type == '{') {
6598 return parse_compound_literal(type);
6601 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6602 cast->base.source_position = source_position;
6604 expression_t *value = parse_sub_expression(PREC_CAST);
6605 cast->base.type = type;
6606 cast->unary.value = value;
6608 if (! semantic_cast(cast)) {
6609 /* TODO: record the error in the AST. else it is impossible to detect it */
6614 return create_invalid_expression();
6618 * Parse a statement expression.
6620 static expression_t *parse_statement_expression(void)
6622 add_anchor_token(')');
6624 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6626 statement_t *statement = parse_compound_statement(true);
6627 expression->statement.statement = statement;
6628 expression->base.source_position = statement->base.source_position;
6630 /* find last statement and use its type */
6631 type_t *type = type_void;
6632 const statement_t *stmt = statement->compound.statements;
6634 while (stmt->base.next != NULL)
6635 stmt = stmt->base.next;
6637 if (stmt->kind == STATEMENT_EXPRESSION) {
6638 type = stmt->expression.expression->base.type;
6640 } else if (warning.other) {
6641 warningf(&expression->base.source_position, "empty statement expression ({})");
6643 expression->base.type = type;
6645 rem_anchor_token(')');
6653 * Parse a parenthesized expression.
6655 static expression_t *parse_parenthesized_expression(void)
6659 switch(token.type) {
6661 /* gcc extension: a statement expression */
6662 return parse_statement_expression();
6666 return parse_cast();
6668 if (is_typedef_symbol(token.v.symbol)) {
6669 return parse_cast();
6673 add_anchor_token(')');
6674 expression_t *result = parse_expression();
6675 rem_anchor_token(')');
6682 static expression_t *parse_function_keyword(void)
6687 if (current_function == NULL) {
6688 errorf(HERE, "'__func__' used outside of a function");
6691 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6692 expression->base.type = type_char_ptr;
6693 expression->funcname.kind = FUNCNAME_FUNCTION;
6698 static expression_t *parse_pretty_function_keyword(void)
6700 eat(T___PRETTY_FUNCTION__);
6702 if (current_function == NULL) {
6703 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6706 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6707 expression->base.type = type_char_ptr;
6708 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6713 static expression_t *parse_funcsig_keyword(void)
6717 if (current_function == NULL) {
6718 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6721 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6722 expression->base.type = type_char_ptr;
6723 expression->funcname.kind = FUNCNAME_FUNCSIG;
6728 static expression_t *parse_funcdname_keyword(void)
6730 eat(T___FUNCDNAME__);
6732 if (current_function == NULL) {
6733 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6736 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6737 expression->base.type = type_char_ptr;
6738 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6743 static designator_t *parse_designator(void)
6745 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6746 result->source_position = *HERE;
6748 if (token.type != T_IDENTIFIER) {
6749 parse_error_expected("while parsing member designator",
6750 T_IDENTIFIER, NULL);
6753 result->symbol = token.v.symbol;
6756 designator_t *last_designator = result;
6758 if (token.type == '.') {
6760 if (token.type != T_IDENTIFIER) {
6761 parse_error_expected("while parsing member designator",
6762 T_IDENTIFIER, NULL);
6765 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6766 designator->source_position = *HERE;
6767 designator->symbol = token.v.symbol;
6770 last_designator->next = designator;
6771 last_designator = designator;
6774 if (token.type == '[') {
6776 add_anchor_token(']');
6777 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6778 designator->source_position = *HERE;
6779 designator->array_index = parse_expression();
6780 rem_anchor_token(']');
6782 if (designator->array_index == NULL) {
6786 last_designator->next = designator;
6787 last_designator = designator;
6799 * Parse the __builtin_offsetof() expression.
6801 static expression_t *parse_offsetof(void)
6803 eat(T___builtin_offsetof);
6805 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6806 expression->base.type = type_size_t;
6809 add_anchor_token(',');
6810 type_t *type = parse_typename();
6811 rem_anchor_token(',');
6813 add_anchor_token(')');
6814 designator_t *designator = parse_designator();
6815 rem_anchor_token(')');
6818 expression->offsetofe.type = type;
6819 expression->offsetofe.designator = designator;
6822 memset(&path, 0, sizeof(path));
6823 path.top_type = type;
6824 path.path = NEW_ARR_F(type_path_entry_t, 0);
6826 descend_into_subtype(&path);
6828 if (!walk_designator(&path, designator, true)) {
6829 return create_invalid_expression();
6832 DEL_ARR_F(path.path);
6836 return create_invalid_expression();
6840 * Parses a _builtin_va_start() expression.
6842 static expression_t *parse_va_start(void)
6844 eat(T___builtin_va_start);
6846 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6849 add_anchor_token(',');
6850 expression->va_starte.ap = parse_assignment_expression();
6851 rem_anchor_token(',');
6853 expression_t *const expr = parse_assignment_expression();
6854 if (expr->kind == EXPR_REFERENCE) {
6855 declaration_t *const decl = expr->reference.declaration;
6856 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6857 errorf(&expr->base.source_position,
6858 "second argument of 'va_start' must be last parameter of the current function");
6860 expression->va_starte.parameter = decl;
6866 return create_invalid_expression();
6870 * Parses a _builtin_va_arg() expression.
6872 static expression_t *parse_va_arg(void)
6874 eat(T___builtin_va_arg);
6876 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6879 expression->va_arge.ap = parse_assignment_expression();
6881 expression->base.type = parse_typename();
6886 return create_invalid_expression();
6889 static expression_t *parse_builtin_symbol(void)
6891 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6893 symbol_t *symbol = token.v.symbol;
6895 expression->builtin_symbol.symbol = symbol;
6898 type_t *type = get_builtin_symbol_type(symbol);
6899 type = automatic_type_conversion(type);
6901 expression->base.type = type;
6906 * Parses a __builtin_constant() expression.
6908 static expression_t *parse_builtin_constant(void)
6910 eat(T___builtin_constant_p);
6912 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6915 add_anchor_token(')');
6916 expression->builtin_constant.value = parse_assignment_expression();
6917 rem_anchor_token(')');
6919 expression->base.type = type_int;
6923 return create_invalid_expression();
6927 * Parses a __builtin_prefetch() expression.
6929 static expression_t *parse_builtin_prefetch(void)
6931 eat(T___builtin_prefetch);
6933 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6936 add_anchor_token(')');
6937 expression->builtin_prefetch.adr = parse_assignment_expression();
6938 if (token.type == ',') {
6940 expression->builtin_prefetch.rw = parse_assignment_expression();
6942 if (token.type == ',') {
6944 expression->builtin_prefetch.locality = parse_assignment_expression();
6946 rem_anchor_token(')');
6948 expression->base.type = type_void;
6952 return create_invalid_expression();
6956 * Parses a __builtin_is_*() compare expression.
6958 static expression_t *parse_compare_builtin(void)
6960 expression_t *expression;
6962 switch(token.type) {
6963 case T___builtin_isgreater:
6964 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6966 case T___builtin_isgreaterequal:
6967 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6969 case T___builtin_isless:
6970 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6972 case T___builtin_islessequal:
6973 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6975 case T___builtin_islessgreater:
6976 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6978 case T___builtin_isunordered:
6979 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6982 internal_errorf(HERE, "invalid compare builtin found");
6984 expression->base.source_position = *HERE;
6988 expression->binary.left = parse_assignment_expression();
6990 expression->binary.right = parse_assignment_expression();
6993 type_t *const orig_type_left = expression->binary.left->base.type;
6994 type_t *const orig_type_right = expression->binary.right->base.type;
6996 type_t *const type_left = skip_typeref(orig_type_left);
6997 type_t *const type_right = skip_typeref(orig_type_right);
6998 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6999 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7000 type_error_incompatible("invalid operands in comparison",
7001 &expression->base.source_position, orig_type_left, orig_type_right);
7004 semantic_comparison(&expression->binary);
7009 return create_invalid_expression();
7014 * Parses a __builtin_expect() expression.
7016 static expression_t *parse_builtin_expect(void)
7018 eat(T___builtin_expect);
7020 expression_t *expression
7021 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7024 expression->binary.left = parse_assignment_expression();
7026 expression->binary.right = parse_constant_expression();
7029 expression->base.type = expression->binary.left->base.type;
7033 return create_invalid_expression();
7038 * Parses a MS assume() expression.
7040 static expression_t *parse_assume(void)
7044 expression_t *expression
7045 = allocate_expression_zero(EXPR_UNARY_ASSUME);
7048 add_anchor_token(')');
7049 expression->unary.value = parse_assignment_expression();
7050 rem_anchor_token(')');
7053 expression->base.type = type_void;
7056 return create_invalid_expression();
7060 * Return the declaration for a given label symbol or create a new one.
7062 * @param symbol the symbol of the label
7064 static declaration_t *get_label(symbol_t *symbol)
7066 declaration_t *candidate;
7067 assert(current_function != NULL);
7069 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
7070 /* if we found a local label, we already created the declaration */
7071 if (candidate != NULL) {
7072 if (candidate->parent_scope != scope) {
7073 assert(candidate->parent_scope->depth < scope->depth);
7074 current_function->goto_to_outer = true;
7079 candidate = get_declaration(symbol, NAMESPACE_LABEL);
7080 /* if we found a label in the same function, then we already created the
7082 if (candidate != NULL
7083 && candidate->parent_scope == ¤t_function->scope) {
7087 /* otherwise we need to create a new one */
7088 declaration_t *const declaration = allocate_declaration_zero();
7089 declaration->namespc = NAMESPACE_LABEL;
7090 declaration->symbol = symbol;
7092 label_push(declaration);
7098 * Parses a GNU && label address expression.
7100 static expression_t *parse_label_address(void)
7102 source_position_t source_position = token.source_position;
7104 if (token.type != T_IDENTIFIER) {
7105 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7108 symbol_t *symbol = token.v.symbol;
7111 declaration_t *label = get_label(symbol);
7114 label->address_taken = true;
7116 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7117 expression->base.source_position = source_position;
7119 /* label address is threaten as a void pointer */
7120 expression->base.type = type_void_ptr;
7121 expression->label_address.declaration = label;
7124 return create_invalid_expression();
7128 * Parse a microsoft __noop expression.
7130 static expression_t *parse_noop_expression(void)
7132 source_position_t source_position = *HERE;
7135 if (token.type == '(') {
7136 /* parse arguments */
7138 add_anchor_token(')');
7139 add_anchor_token(',');
7141 if (token.type != ')') {
7143 (void)parse_assignment_expression();
7144 if (token.type != ',')
7150 rem_anchor_token(',');
7151 rem_anchor_token(')');
7154 /* the result is a (int)0 */
7155 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7156 cnst->base.source_position = source_position;
7157 cnst->base.type = type_int;
7158 cnst->conste.v.int_value = 0;
7159 cnst->conste.is_ms_noop = true;
7164 return create_invalid_expression();
7168 * Parses a primary expression.
7170 static expression_t *parse_primary_expression(void)
7172 switch (token.type) {
7173 case T_INTEGER: return parse_int_const();
7174 case T_CHARACTER_CONSTANT: return parse_character_constant();
7175 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7176 case T_FLOATINGPOINT: return parse_float_const();
7177 case T_STRING_LITERAL:
7178 case T_WIDE_STRING_LITERAL: return parse_string_const();
7179 case T_IDENTIFIER: return parse_reference();
7180 case T___FUNCTION__:
7181 case T___func__: return parse_function_keyword();
7182 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7183 case T___FUNCSIG__: return parse_funcsig_keyword();
7184 case T___FUNCDNAME__: return parse_funcdname_keyword();
7185 case T___builtin_offsetof: return parse_offsetof();
7186 case T___builtin_va_start: return parse_va_start();
7187 case T___builtin_va_arg: return parse_va_arg();
7188 case T___builtin_expect:
7189 case T___builtin_alloca:
7190 case T___builtin_inf:
7191 case T___builtin_inff:
7192 case T___builtin_infl:
7193 case T___builtin_nan:
7194 case T___builtin_nanf:
7195 case T___builtin_nanl:
7196 case T___builtin_huge_val:
7197 case T___builtin_va_end: return parse_builtin_symbol();
7198 case T___builtin_isgreater:
7199 case T___builtin_isgreaterequal:
7200 case T___builtin_isless:
7201 case T___builtin_islessequal:
7202 case T___builtin_islessgreater:
7203 case T___builtin_isunordered: return parse_compare_builtin();
7204 case T___builtin_constant_p: return parse_builtin_constant();
7205 case T___builtin_prefetch: return parse_builtin_prefetch();
7206 case T__assume: return parse_assume();
7209 return parse_label_address();
7212 case '(': return parse_parenthesized_expression();
7213 case T___noop: return parse_noop_expression();
7216 errorf(HERE, "unexpected token %K, expected an expression", &token);
7217 return create_invalid_expression();
7221 * Check if the expression has the character type and issue a warning then.
7223 static void check_for_char_index_type(const expression_t *expression)
7225 type_t *const type = expression->base.type;
7226 const type_t *const base_type = skip_typeref(type);
7228 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7229 warning.char_subscripts) {
7230 warningf(&expression->base.source_position,
7231 "array subscript has type '%T'", type);
7235 static expression_t *parse_array_expression(expression_t *left)
7238 add_anchor_token(']');
7240 expression_t *inside = parse_expression();
7242 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7244 array_access_expression_t *array_access = &expression->array_access;
7246 type_t *const orig_type_left = left->base.type;
7247 type_t *const orig_type_inside = inside->base.type;
7249 type_t *const type_left = skip_typeref(orig_type_left);
7250 type_t *const type_inside = skip_typeref(orig_type_inside);
7252 type_t *return_type;
7253 if (is_type_pointer(type_left)) {
7254 return_type = type_left->pointer.points_to;
7255 array_access->array_ref = left;
7256 array_access->index = inside;
7257 check_for_char_index_type(inside);
7258 } else if (is_type_pointer(type_inside)) {
7259 return_type = type_inside->pointer.points_to;
7260 array_access->array_ref = inside;
7261 array_access->index = left;
7262 array_access->flipped = true;
7263 check_for_char_index_type(left);
7265 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7267 "array access on object with non-pointer types '%T', '%T'",
7268 orig_type_left, orig_type_inside);
7270 return_type = type_error_type;
7271 array_access->array_ref = left;
7272 array_access->index = inside;
7275 expression->base.type = automatic_type_conversion(return_type);
7277 rem_anchor_token(']');
7278 if (token.type == ']') {
7281 parse_error_expected("Problem while parsing array access", ']', NULL);
7286 static expression_t *parse_typeprop(expression_kind_t const kind,
7287 source_position_t const pos)
7289 expression_t *tp_expression = allocate_expression_zero(kind);
7290 tp_expression->base.type = type_size_t;
7291 tp_expression->base.source_position = pos;
7293 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7295 /* we only refer to a type property, mark this case */
7296 bool old = in_type_prop;
7297 in_type_prop = true;
7300 expression_t *expression;
7301 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7303 add_anchor_token(')');
7304 orig_type = parse_typename();
7305 rem_anchor_token(')');
7308 if (token.type == '{') {
7309 /* It was not sizeof(type) after all. It is sizeof of an expression
7310 * starting with a compound literal */
7311 expression = parse_compound_literal(orig_type);
7312 goto typeprop_expression;
7315 expression = parse_sub_expression(PREC_UNARY);
7317 typeprop_expression:
7318 tp_expression->typeprop.tp_expression = expression;
7320 orig_type = revert_automatic_type_conversion(expression);
7321 expression->base.type = orig_type;
7324 tp_expression->typeprop.type = orig_type;
7325 type_t const* const type = skip_typeref(orig_type);
7326 char const* const wrong_type =
7327 is_type_incomplete(type) ? "incomplete" :
7328 type->kind == TYPE_FUNCTION ? "function designator" :
7329 type->kind == TYPE_BITFIELD ? "bitfield" :
7331 if (wrong_type != NULL) {
7332 errorf(&pos, "operand of %s expression must not be of %s type '%T'",
7333 what, wrong_type, orig_type);
7338 return tp_expression;
7341 static expression_t *parse_sizeof(void)
7343 source_position_t pos = *HERE;
7345 return parse_typeprop(EXPR_SIZEOF, pos);
7348 static expression_t *parse_alignof(void)
7350 source_position_t pos = *HERE;
7352 return parse_typeprop(EXPR_ALIGNOF, pos);
7355 static expression_t *parse_select_expression(expression_t *compound)
7357 assert(token.type == '.' || token.type == T_MINUSGREATER);
7359 bool is_pointer = (token.type == T_MINUSGREATER);
7362 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7363 select->select.compound = compound;
7365 if (token.type != T_IDENTIFIER) {
7366 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7369 symbol_t *symbol = token.v.symbol;
7372 type_t *const orig_type = compound->base.type;
7373 type_t *const type = skip_typeref(orig_type);
7376 bool saw_error = false;
7377 if (is_type_pointer(type)) {
7380 "request for member '%Y' in something not a struct or union, but '%T'",
7384 type_left = skip_typeref(type->pointer.points_to);
7386 if (is_pointer && is_type_valid(type)) {
7387 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7393 declaration_t *entry;
7394 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7395 type_left->kind == TYPE_COMPOUND_UNION) {
7396 declaration_t *const declaration = type_left->compound.declaration;
7398 if (!declaration->init.complete) {
7399 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7401 goto create_error_entry;
7404 entry = find_compound_entry(declaration, symbol);
7405 if (entry == NULL) {
7406 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7407 goto create_error_entry;
7410 if (is_type_valid(type_left) && !saw_error) {
7412 "request for member '%Y' in something not a struct or union, but '%T'",
7416 entry = allocate_declaration_zero();
7417 entry->symbol = symbol;
7420 select->select.compound_entry = entry;
7422 type_t *const res_type =
7423 get_qualified_type(entry->type, type_left->base.qualifiers);
7425 /* we always do the auto-type conversions; the & and sizeof parser contains
7426 * code to revert this! */
7427 select->base.type = automatic_type_conversion(res_type);
7429 type_t *skipped = skip_typeref(res_type);
7430 if (skipped->kind == TYPE_BITFIELD) {
7431 select->base.type = skipped->bitfield.base_type;
7437 static void check_call_argument(const function_parameter_t *parameter,
7438 call_argument_t *argument, unsigned pos)
7440 type_t *expected_type = parameter->type;
7441 type_t *expected_type_skip = skip_typeref(expected_type);
7442 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7443 expression_t *arg_expr = argument->expression;
7444 type_t *arg_type = skip_typeref(arg_expr->base.type);
7446 /* handle transparent union gnu extension */
7447 if (is_type_union(expected_type_skip)
7448 && (expected_type_skip->base.modifiers
7449 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7450 declaration_t *union_decl = expected_type_skip->compound.declaration;
7452 declaration_t *declaration = union_decl->scope.declarations;
7453 type_t *best_type = NULL;
7454 for ( ; declaration != NULL; declaration = declaration->next) {
7455 type_t *decl_type = declaration->type;
7456 error = semantic_assign(decl_type, arg_expr);
7457 if (error == ASSIGN_ERROR_INCOMPATIBLE
7458 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7461 if (error == ASSIGN_SUCCESS) {
7462 best_type = decl_type;
7463 } else if (best_type == NULL) {
7464 best_type = decl_type;
7468 if (best_type != NULL) {
7469 expected_type = best_type;
7473 error = semantic_assign(expected_type, arg_expr);
7474 argument->expression = create_implicit_cast(argument->expression,
7477 if (error != ASSIGN_SUCCESS) {
7478 /* report exact scope in error messages (like "in argument 3") */
7480 snprintf(buf, sizeof(buf), "call argument %u", pos);
7481 report_assign_error(error, expected_type, arg_expr, buf,
7482 &arg_expr->base.source_position);
7483 } else if (warning.traditional || warning.conversion) {
7484 type_t *const promoted_type = get_default_promoted_type(arg_type);
7485 if (!types_compatible(expected_type_skip, promoted_type) &&
7486 !types_compatible(expected_type_skip, type_void_ptr) &&
7487 !types_compatible(type_void_ptr, promoted_type)) {
7488 /* Deliberately show the skipped types in this warning */
7489 warningf(&arg_expr->base.source_position,
7490 "passing call argument %u as '%T' rather than '%T' due to prototype",
7491 pos, expected_type_skip, promoted_type);
7497 * Parse a call expression, ie. expression '( ... )'.
7499 * @param expression the function address
7501 static expression_t *parse_call_expression(expression_t *expression)
7503 expression_t *result = allocate_expression_zero(EXPR_CALL);
7504 result->base.source_position = expression->base.source_position;
7506 call_expression_t *call = &result->call;
7507 call->function = expression;
7509 type_t *const orig_type = expression->base.type;
7510 type_t *const type = skip_typeref(orig_type);
7512 function_type_t *function_type = NULL;
7513 if (is_type_pointer(type)) {
7514 type_t *const to_type = skip_typeref(type->pointer.points_to);
7516 if (is_type_function(to_type)) {
7517 function_type = &to_type->function;
7518 call->base.type = function_type->return_type;
7522 if (function_type == NULL && is_type_valid(type)) {
7523 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7526 /* parse arguments */
7528 add_anchor_token(')');
7529 add_anchor_token(',');
7531 if (token.type != ')') {
7532 call_argument_t *last_argument = NULL;
7535 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7537 argument->expression = parse_assignment_expression();
7538 if (last_argument == NULL) {
7539 call->arguments = argument;
7541 last_argument->next = argument;
7543 last_argument = argument;
7545 if (token.type != ',')
7550 rem_anchor_token(',');
7551 rem_anchor_token(')');
7554 if (function_type == NULL)
7557 function_parameter_t *parameter = function_type->parameters;
7558 call_argument_t *argument = call->arguments;
7559 if (!function_type->unspecified_parameters) {
7560 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7561 parameter = parameter->next, argument = argument->next) {
7562 check_call_argument(parameter, argument, ++pos);
7565 if (parameter != NULL) {
7566 errorf(HERE, "too few arguments to function '%E'", expression);
7567 } else if (argument != NULL && !function_type->variadic) {
7568 errorf(HERE, "too many arguments to function '%E'", expression);
7572 /* do default promotion */
7573 for( ; argument != NULL; argument = argument->next) {
7574 type_t *type = argument->expression->base.type;
7576 type = get_default_promoted_type(type);
7578 argument->expression
7579 = create_implicit_cast(argument->expression, type);
7582 check_format(&result->call);
7584 if (warning.aggregate_return &&
7585 is_type_compound(skip_typeref(function_type->return_type))) {
7586 warningf(&result->base.source_position,
7587 "function call has aggregate value");
7594 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7596 static bool same_compound_type(const type_t *type1, const type_t *type2)
7599 is_type_compound(type1) &&
7600 type1->kind == type2->kind &&
7601 type1->compound.declaration == type2->compound.declaration;
7605 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7607 * @param expression the conditional expression
7609 static expression_t *parse_conditional_expression(expression_t *expression)
7611 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7613 conditional_expression_t *conditional = &result->conditional;
7614 conditional->base.source_position = *HERE;
7615 conditional->condition = expression;
7618 add_anchor_token(':');
7621 type_t *const condition_type_orig = expression->base.type;
7622 type_t *const condition_type = skip_typeref(condition_type_orig);
7623 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7624 type_error("expected a scalar type in conditional condition",
7625 &expression->base.source_position, condition_type_orig);
7628 expression_t *true_expression = expression;
7629 bool gnu_cond = false;
7630 if (GNU_MODE && token.type == ':') {
7633 true_expression = parse_expression();
7634 rem_anchor_token(':');
7636 expression_t *false_expression =
7637 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7639 type_t *const orig_true_type = true_expression->base.type;
7640 type_t *const orig_false_type = false_expression->base.type;
7641 type_t *const true_type = skip_typeref(orig_true_type);
7642 type_t *const false_type = skip_typeref(orig_false_type);
7645 type_t *result_type;
7646 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7647 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7648 /* ISO/IEC 14882:1998(E) §5.16:2 */
7649 if (true_expression->kind == EXPR_UNARY_THROW) {
7650 result_type = false_type;
7651 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7652 result_type = true_type;
7654 if (warning.other && (
7655 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7656 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7658 warningf(&conditional->base.source_position,
7659 "ISO C forbids conditional expression with only one void side");
7661 result_type = type_void;
7663 } else if (is_type_arithmetic(true_type)
7664 && is_type_arithmetic(false_type)) {
7665 result_type = semantic_arithmetic(true_type, false_type);
7667 true_expression = create_implicit_cast(true_expression, result_type);
7668 false_expression = create_implicit_cast(false_expression, result_type);
7670 conditional->true_expression = true_expression;
7671 conditional->false_expression = false_expression;
7672 conditional->base.type = result_type;
7673 } else if (same_compound_type(true_type, false_type)) {
7674 /* just take 1 of the 2 types */
7675 result_type = true_type;
7676 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7677 type_t *pointer_type;
7679 expression_t *other_expression;
7680 if (is_type_pointer(true_type) &&
7681 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7682 pointer_type = true_type;
7683 other_type = false_type;
7684 other_expression = false_expression;
7686 pointer_type = false_type;
7687 other_type = true_type;
7688 other_expression = true_expression;
7691 if (is_null_pointer_constant(other_expression)) {
7692 result_type = pointer_type;
7693 } else if (is_type_pointer(other_type)) {
7694 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7695 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7698 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7699 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7701 } else if (types_compatible(get_unqualified_type(to1),
7702 get_unqualified_type(to2))) {
7705 if (warning.other) {
7706 warningf(&conditional->base.source_position,
7707 "pointer types '%T' and '%T' in conditional expression are incompatible",
7708 true_type, false_type);
7713 type_t *const type =
7714 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7715 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7716 } else if (is_type_integer(other_type)) {
7717 if (warning.other) {
7718 warningf(&conditional->base.source_position,
7719 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7721 result_type = pointer_type;
7723 if (is_type_valid(other_type)) {
7724 type_error_incompatible("while parsing conditional",
7725 &expression->base.source_position, true_type, false_type);
7727 result_type = type_error_type;
7730 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7731 type_error_incompatible("while parsing conditional",
7732 &conditional->base.source_position, true_type,
7735 result_type = type_error_type;
7738 conditional->true_expression
7739 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7740 conditional->false_expression
7741 = create_implicit_cast(false_expression, result_type);
7742 conditional->base.type = result_type;
7745 return create_invalid_expression();
7749 * Parse an extension expression.
7751 static expression_t *parse_extension(void)
7753 eat(T___extension__);
7755 bool old_gcc_extension = in_gcc_extension;
7756 in_gcc_extension = true;
7757 expression_t *expression = parse_sub_expression(PREC_UNARY);
7758 in_gcc_extension = old_gcc_extension;
7763 * Parse a __builtin_classify_type() expression.
7765 static expression_t *parse_builtin_classify_type(void)
7767 eat(T___builtin_classify_type);
7769 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7770 result->base.type = type_int;
7773 add_anchor_token(')');
7774 expression_t *expression = parse_expression();
7775 rem_anchor_token(')');
7777 result->classify_type.type_expression = expression;
7781 return create_invalid_expression();
7785 * Parse a delete expression
7786 * ISO/IEC 14882:1998(E) §5.3.5
7788 static expression_t *parse_delete(void)
7790 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7791 result->base.source_position = *HERE;
7792 result->base.type = type_void;
7796 if (token.type == '[') {
7798 result->kind = EXPR_UNARY_DELETE_ARRAY;
7803 expression_t *const value = parse_sub_expression(PREC_CAST);
7804 result->unary.value = value;
7806 type_t *const type = skip_typeref(value->base.type);
7807 if (!is_type_pointer(type)) {
7808 errorf(&value->base.source_position,
7809 "operand of delete must have pointer type");
7810 } else if (warning.other &&
7811 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7812 warningf(&value->base.source_position,
7813 "deleting 'void*' is undefined");
7820 * Parse a throw expression
7821 * ISO/IEC 14882:1998(E) §15:1
7823 static expression_t *parse_throw(void)
7825 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7826 result->base.source_position = *HERE;
7827 result->base.type = type_void;
7831 expression_t *value = NULL;
7832 switch (token.type) {
7834 value = parse_assignment_expression();
7835 /* ISO/IEC 14882:1998(E) §15.1:3 */
7836 type_t *const orig_type = value->base.type;
7837 type_t *const type = skip_typeref(orig_type);
7838 if (is_type_incomplete(type)) {
7839 errorf(&value->base.source_position,
7840 "cannot throw object of incomplete type '%T'", orig_type);
7841 } else if (is_type_pointer(type)) {
7842 type_t *const points_to = skip_typeref(type->pointer.points_to);
7843 if (is_type_incomplete(points_to) &&
7844 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7845 errorf(&value->base.source_position,
7846 "cannot throw pointer to incomplete type '%T'", orig_type);
7854 result->unary.value = value;
7859 static bool check_pointer_arithmetic(const source_position_t *source_position,
7860 type_t *pointer_type,
7861 type_t *orig_pointer_type)
7863 type_t *points_to = pointer_type->pointer.points_to;
7864 points_to = skip_typeref(points_to);
7866 if (is_type_incomplete(points_to)) {
7867 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7868 errorf(source_position,
7869 "arithmetic with pointer to incomplete type '%T' not allowed",
7872 } else if (warning.pointer_arith) {
7873 warningf(source_position,
7874 "pointer of type '%T' used in arithmetic",
7877 } else if (is_type_function(points_to)) {
7879 errorf(source_position,
7880 "arithmetic with pointer to function type '%T' not allowed",
7883 } else if (warning.pointer_arith) {
7884 warningf(source_position,
7885 "pointer to a function '%T' used in arithmetic",
7892 static bool is_lvalue(const expression_t *expression)
7894 switch (expression->kind) {
7895 case EXPR_REFERENCE:
7896 case EXPR_ARRAY_ACCESS:
7898 case EXPR_UNARY_DEREFERENCE:
7902 /* Claim it is an lvalue, if the type is invalid. There was a parse
7903 * error before, which maybe prevented properly recognizing it as
7905 return !is_type_valid(skip_typeref(expression->base.type));
7909 static void semantic_incdec(unary_expression_t *expression)
7911 type_t *const orig_type = expression->value->base.type;
7912 type_t *const type = skip_typeref(orig_type);
7913 if (is_type_pointer(type)) {
7914 if (!check_pointer_arithmetic(&expression->base.source_position,
7918 } else if (!is_type_real(type) && is_type_valid(type)) {
7919 /* TODO: improve error message */
7920 errorf(&expression->base.source_position,
7921 "operation needs an arithmetic or pointer type");
7924 if (!is_lvalue(expression->value)) {
7925 /* TODO: improve error message */
7926 errorf(&expression->base.source_position, "lvalue required as operand");
7928 expression->base.type = orig_type;
7931 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7933 type_t *const orig_type = expression->value->base.type;
7934 type_t *const type = skip_typeref(orig_type);
7935 if (!is_type_arithmetic(type)) {
7936 if (is_type_valid(type)) {
7937 /* TODO: improve error message */
7938 errorf(&expression->base.source_position,
7939 "operation needs an arithmetic type");
7944 expression->base.type = orig_type;
7947 static void semantic_unexpr_plus(unary_expression_t *expression)
7949 semantic_unexpr_arithmetic(expression);
7950 if (warning.traditional)
7951 warningf(&expression->base.source_position,
7952 "traditional C rejects the unary plus operator");
7955 static expression_t const *get_reference_address(expression_t const *expr)
7957 bool regular_take_address = true;
7959 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7960 expr = expr->unary.value;
7962 regular_take_address = false;
7965 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7968 expr = expr->unary.value;
7971 if (expr->kind != EXPR_REFERENCE)
7974 if (!regular_take_address &&
7975 !is_type_function(skip_typeref(expr->reference.declaration->type))) {
7982 static void warn_function_address_as_bool(expression_t const* expr)
7984 if (!warning.address)
7987 expr = get_reference_address(expr);
7989 warningf(&expr->base.source_position,
7990 "the address of '%Y' will always evaluate as 'true'",
7991 expr->reference.declaration->symbol);
7995 static void semantic_not(unary_expression_t *expression)
7997 type_t *const orig_type = expression->value->base.type;
7998 type_t *const type = skip_typeref(orig_type);
7999 if (!is_type_scalar(type) && is_type_valid(type)) {
8000 errorf(&expression->base.source_position,
8001 "operand of ! must be of scalar type");
8004 warn_function_address_as_bool(expression->value);
8006 expression->base.type = type_int;
8009 static void semantic_unexpr_integer(unary_expression_t *expression)
8011 type_t *const orig_type = expression->value->base.type;
8012 type_t *const type = skip_typeref(orig_type);
8013 if (!is_type_integer(type)) {
8014 if (is_type_valid(type)) {
8015 errorf(&expression->base.source_position,
8016 "operand of ~ must be of integer type");
8021 expression->base.type = orig_type;
8024 static void semantic_dereference(unary_expression_t *expression)
8026 type_t *const orig_type = expression->value->base.type;
8027 type_t *const type = skip_typeref(orig_type);
8028 if (!is_type_pointer(type)) {
8029 if (is_type_valid(type)) {
8030 errorf(&expression->base.source_position,
8031 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8036 type_t *result_type = type->pointer.points_to;
8037 result_type = automatic_type_conversion(result_type);
8038 expression->base.type = result_type;
8042 * Record that an address is taken (expression represents an lvalue).
8044 * @param expression the expression
8045 * @param may_be_register if true, the expression might be an register
8047 static void set_address_taken(expression_t *expression, bool may_be_register)
8049 if (expression->kind != EXPR_REFERENCE)
8052 declaration_t *const declaration = expression->reference.declaration;
8053 /* happens for parse errors */
8054 if (declaration == NULL)
8057 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
8058 errorf(&expression->base.source_position,
8059 "address of register variable '%Y' requested",
8060 declaration->symbol);
8062 declaration->address_taken = 1;
8067 * Check the semantic of the address taken expression.
8069 static void semantic_take_addr(unary_expression_t *expression)
8071 expression_t *value = expression->value;
8072 value->base.type = revert_automatic_type_conversion(value);
8074 type_t *orig_type = value->base.type;
8075 if (!is_type_valid(skip_typeref(orig_type)))
8078 set_address_taken(value, false);
8080 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8083 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8084 static expression_t *parse_##unexpression_type(void) \
8086 expression_t *unary_expression \
8087 = allocate_expression_zero(unexpression_type); \
8088 unary_expression->base.source_position = *HERE; \
8090 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8092 sfunc(&unary_expression->unary); \
8094 return unary_expression; \
8097 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8098 semantic_unexpr_arithmetic)
8099 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8100 semantic_unexpr_plus)
8101 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8103 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8104 semantic_dereference)
8105 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8107 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8108 semantic_unexpr_integer)
8109 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8111 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8114 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8116 static expression_t *parse_##unexpression_type(expression_t *left) \
8118 expression_t *unary_expression \
8119 = allocate_expression_zero(unexpression_type); \
8120 unary_expression->base.source_position = *HERE; \
8122 unary_expression->unary.value = left; \
8124 sfunc(&unary_expression->unary); \
8126 return unary_expression; \
8129 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8130 EXPR_UNARY_POSTFIX_INCREMENT,
8132 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8133 EXPR_UNARY_POSTFIX_DECREMENT,
8136 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8138 /* TODO: handle complex + imaginary types */
8140 type_left = get_unqualified_type(type_left);
8141 type_right = get_unqualified_type(type_right);
8143 /* § 6.3.1.8 Usual arithmetic conversions */
8144 if (type_left == type_long_double || type_right == type_long_double) {
8145 return type_long_double;
8146 } else if (type_left == type_double || type_right == type_double) {
8148 } else if (type_left == type_float || type_right == type_float) {
8152 type_left = promote_integer(type_left);
8153 type_right = promote_integer(type_right);
8155 if (type_left == type_right)
8158 bool const signed_left = is_type_signed(type_left);
8159 bool const signed_right = is_type_signed(type_right);
8160 int const rank_left = get_rank(type_left);
8161 int const rank_right = get_rank(type_right);
8163 if (signed_left == signed_right)
8164 return rank_left >= rank_right ? type_left : type_right;
8173 u_rank = rank_right;
8174 u_type = type_right;
8176 s_rank = rank_right;
8177 s_type = type_right;
8182 if (u_rank >= s_rank)
8185 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8187 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8188 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8192 case ATOMIC_TYPE_INT: return type_unsigned_int;
8193 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8194 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8196 default: panic("invalid atomic type");
8201 * Check the semantic restrictions for a binary expression.
8203 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8205 expression_t *const left = expression->left;
8206 expression_t *const right = expression->right;
8207 type_t *const orig_type_left = left->base.type;
8208 type_t *const orig_type_right = right->base.type;
8209 type_t *const type_left = skip_typeref(orig_type_left);
8210 type_t *const type_right = skip_typeref(orig_type_right);
8212 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8213 /* TODO: improve error message */
8214 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8215 errorf(&expression->base.source_position,
8216 "operation needs arithmetic types");
8221 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8222 expression->left = create_implicit_cast(left, arithmetic_type);
8223 expression->right = create_implicit_cast(right, arithmetic_type);
8224 expression->base.type = arithmetic_type;
8227 static void warn_div_by_zero(binary_expression_t const *const expression)
8229 if (!warning.div_by_zero ||
8230 !is_type_integer(expression->base.type))
8233 expression_t const *const right = expression->right;
8234 /* The type of the right operand can be different for /= */
8235 if (is_type_integer(right->base.type) &&
8236 is_constant_expression(right) &&
8237 fold_constant(right) == 0) {
8238 warningf(&expression->base.source_position, "division by zero");
8243 * Check the semantic restrictions for a div/mod expression.
8245 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8246 semantic_binexpr_arithmetic(expression);
8247 warn_div_by_zero(expression);
8250 static void semantic_shift_op(binary_expression_t *expression)
8252 expression_t *const left = expression->left;
8253 expression_t *const right = expression->right;
8254 type_t *const orig_type_left = left->base.type;
8255 type_t *const orig_type_right = right->base.type;
8256 type_t * type_left = skip_typeref(orig_type_left);
8257 type_t * type_right = skip_typeref(orig_type_right);
8259 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8260 /* TODO: improve error message */
8261 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8262 errorf(&expression->base.source_position,
8263 "operands of shift operation must have integer types");
8268 type_left = promote_integer(type_left);
8269 type_right = promote_integer(type_right);
8271 expression->left = create_implicit_cast(left, type_left);
8272 expression->right = create_implicit_cast(right, type_right);
8273 expression->base.type = type_left;
8276 static void semantic_add(binary_expression_t *expression)
8278 expression_t *const left = expression->left;
8279 expression_t *const right = expression->right;
8280 type_t *const orig_type_left = left->base.type;
8281 type_t *const orig_type_right = right->base.type;
8282 type_t *const type_left = skip_typeref(orig_type_left);
8283 type_t *const type_right = skip_typeref(orig_type_right);
8286 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8287 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8288 expression->left = create_implicit_cast(left, arithmetic_type);
8289 expression->right = create_implicit_cast(right, arithmetic_type);
8290 expression->base.type = arithmetic_type;
8292 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8293 check_pointer_arithmetic(&expression->base.source_position,
8294 type_left, orig_type_left);
8295 expression->base.type = type_left;
8296 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8297 check_pointer_arithmetic(&expression->base.source_position,
8298 type_right, orig_type_right);
8299 expression->base.type = type_right;
8300 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8301 errorf(&expression->base.source_position,
8302 "invalid operands to binary + ('%T', '%T')",
8303 orig_type_left, orig_type_right);
8307 static void semantic_sub(binary_expression_t *expression)
8309 expression_t *const left = expression->left;
8310 expression_t *const right = expression->right;
8311 type_t *const orig_type_left = left->base.type;
8312 type_t *const orig_type_right = right->base.type;
8313 type_t *const type_left = skip_typeref(orig_type_left);
8314 type_t *const type_right = skip_typeref(orig_type_right);
8315 source_position_t const *const pos = &expression->base.source_position;
8318 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8319 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8320 expression->left = create_implicit_cast(left, arithmetic_type);
8321 expression->right = create_implicit_cast(right, arithmetic_type);
8322 expression->base.type = arithmetic_type;
8324 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8325 check_pointer_arithmetic(&expression->base.source_position,
8326 type_left, orig_type_left);
8327 expression->base.type = type_left;
8328 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8329 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8330 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8331 if (!types_compatible(unqual_left, unqual_right)) {
8333 "subtracting pointers to incompatible types '%T' and '%T'",
8334 orig_type_left, orig_type_right);
8335 } else if (!is_type_object(unqual_left)) {
8336 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8337 errorf(pos, "subtracting pointers to non-object types '%T'",
8339 } else if (warning.other) {
8340 warningf(pos, "subtracting pointers to void");
8343 expression->base.type = type_ptrdiff_t;
8344 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8345 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8346 orig_type_left, orig_type_right);
8350 static void warn_string_literal_address(expression_t const* expr)
8352 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8353 expr = expr->unary.value;
8354 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8356 expr = expr->unary.value;
8359 if (expr->kind == EXPR_STRING_LITERAL ||
8360 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8361 warningf(&expr->base.source_position,
8362 "comparison with string literal results in unspecified behaviour");
8367 * Check the semantics of comparison expressions.
8369 * @param expression The expression to check.
8371 static void semantic_comparison(binary_expression_t *expression)
8373 expression_t *left = expression->left;
8374 expression_t *right = expression->right;
8376 if (warning.address) {
8377 warn_string_literal_address(left);
8378 warn_string_literal_address(right);
8380 expression_t const* const func_left = get_reference_address(left);
8381 if (func_left != NULL && is_null_pointer_constant(right)) {
8382 warningf(&expression->base.source_position,
8383 "the address of '%Y' will never be NULL",
8384 func_left->reference.declaration->symbol);
8387 expression_t const* const func_right = get_reference_address(right);
8388 if (func_right != NULL && is_null_pointer_constant(right)) {
8389 warningf(&expression->base.source_position,
8390 "the address of '%Y' will never be NULL",
8391 func_right->reference.declaration->symbol);
8395 type_t *orig_type_left = left->base.type;
8396 type_t *orig_type_right = right->base.type;
8397 type_t *type_left = skip_typeref(orig_type_left);
8398 type_t *type_right = skip_typeref(orig_type_right);
8400 /* TODO non-arithmetic types */
8401 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8402 /* test for signed vs unsigned compares */
8403 if (warning.sign_compare &&
8404 (expression->base.kind != EXPR_BINARY_EQUAL &&
8405 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8406 (is_type_signed(type_left) != is_type_signed(type_right))) {
8408 /* check if 1 of the operands is a constant, in this case we just
8409 * check wether we can safely represent the resulting constant in
8410 * the type of the other operand. */
8411 expression_t *const_expr = NULL;
8412 expression_t *other_expr = NULL;
8414 if (is_constant_expression(left)) {
8417 } else if (is_constant_expression(right)) {
8422 if (const_expr != NULL) {
8423 type_t *other_type = skip_typeref(other_expr->base.type);
8424 long val = fold_constant(const_expr);
8425 /* TODO: check if val can be represented by other_type */
8429 warningf(&expression->base.source_position,
8430 "comparison between signed and unsigned");
8432 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8433 expression->left = create_implicit_cast(left, arithmetic_type);
8434 expression->right = create_implicit_cast(right, arithmetic_type);
8435 expression->base.type = arithmetic_type;
8436 if (warning.float_equal &&
8437 (expression->base.kind == EXPR_BINARY_EQUAL ||
8438 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8439 is_type_float(arithmetic_type)) {
8440 warningf(&expression->base.source_position,
8441 "comparing floating point with == or != is unsafe");
8443 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8444 /* TODO check compatibility */
8445 } else if (is_type_pointer(type_left)) {
8446 expression->right = create_implicit_cast(right, type_left);
8447 } else if (is_type_pointer(type_right)) {
8448 expression->left = create_implicit_cast(left, type_right);
8449 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8450 type_error_incompatible("invalid operands in comparison",
8451 &expression->base.source_position,
8452 type_left, type_right);
8454 expression->base.type = type_int;
8458 * Checks if a compound type has constant fields.
8460 static bool has_const_fields(const compound_type_t *type)
8462 const scope_t *scope = &type->declaration->scope;
8463 const declaration_t *declaration = scope->declarations;
8465 for (; declaration != NULL; declaration = declaration->next) {
8466 if (declaration->namespc != NAMESPACE_NORMAL)
8469 const type_t *decl_type = skip_typeref(declaration->type);
8470 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8477 static bool is_valid_assignment_lhs(expression_t const* const left)
8479 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8480 type_t *const type_left = skip_typeref(orig_type_left);
8482 if (!is_lvalue(left)) {
8483 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8488 if (is_type_array(type_left)) {
8489 errorf(HERE, "cannot assign to arrays ('%E')", left);
8492 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8493 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8497 if (is_type_incomplete(type_left)) {
8498 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8499 left, orig_type_left);
8502 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8503 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8504 left, orig_type_left);
8511 static void semantic_arithmetic_assign(binary_expression_t *expression)
8513 expression_t *left = expression->left;
8514 expression_t *right = expression->right;
8515 type_t *orig_type_left = left->base.type;
8516 type_t *orig_type_right = right->base.type;
8518 if (!is_valid_assignment_lhs(left))
8521 type_t *type_left = skip_typeref(orig_type_left);
8522 type_t *type_right = skip_typeref(orig_type_right);
8524 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8525 /* TODO: improve error message */
8526 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8527 errorf(&expression->base.source_position,
8528 "operation needs arithmetic types");
8533 /* combined instructions are tricky. We can't create an implicit cast on
8534 * the left side, because we need the uncasted form for the store.
8535 * The ast2firm pass has to know that left_type must be right_type
8536 * for the arithmetic operation and create a cast by itself */
8537 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8538 expression->right = create_implicit_cast(right, arithmetic_type);
8539 expression->base.type = type_left;
8542 static void semantic_divmod_assign(binary_expression_t *expression)
8544 semantic_arithmetic_assign(expression);
8545 warn_div_by_zero(expression);
8548 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8550 expression_t *const left = expression->left;
8551 expression_t *const right = expression->right;
8552 type_t *const orig_type_left = left->base.type;
8553 type_t *const orig_type_right = right->base.type;
8554 type_t *const type_left = skip_typeref(orig_type_left);
8555 type_t *const type_right = skip_typeref(orig_type_right);
8557 if (!is_valid_assignment_lhs(left))
8560 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8561 /* combined instructions are tricky. We can't create an implicit cast on
8562 * the left side, because we need the uncasted form for the store.
8563 * The ast2firm pass has to know that left_type must be right_type
8564 * for the arithmetic operation and create a cast by itself */
8565 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8566 expression->right = create_implicit_cast(right, arithmetic_type);
8567 expression->base.type = type_left;
8568 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8569 check_pointer_arithmetic(&expression->base.source_position,
8570 type_left, orig_type_left);
8571 expression->base.type = type_left;
8572 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8573 errorf(&expression->base.source_position,
8574 "incompatible types '%T' and '%T' in assignment",
8575 orig_type_left, orig_type_right);
8580 * Check the semantic restrictions of a logical expression.
8582 static void semantic_logical_op(binary_expression_t *expression)
8584 expression_t *const left = expression->left;
8585 expression_t *const right = expression->right;
8586 type_t *const orig_type_left = left->base.type;
8587 type_t *const orig_type_right = right->base.type;
8588 type_t *const type_left = skip_typeref(orig_type_left);
8589 type_t *const type_right = skip_typeref(orig_type_right);
8591 warn_function_address_as_bool(left);
8592 warn_function_address_as_bool(right);
8594 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8595 /* TODO: improve error message */
8596 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8597 errorf(&expression->base.source_position,
8598 "operation needs scalar types");
8603 expression->base.type = type_int;
8607 * Check the semantic restrictions of a binary assign expression.
8609 static void semantic_binexpr_assign(binary_expression_t *expression)
8611 expression_t *left = expression->left;
8612 type_t *orig_type_left = left->base.type;
8614 if (!is_valid_assignment_lhs(left))
8617 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8618 report_assign_error(error, orig_type_left, expression->right,
8619 "assignment", &left->base.source_position);
8620 expression->right = create_implicit_cast(expression->right, orig_type_left);
8621 expression->base.type = orig_type_left;
8625 * Determine if the outermost operation (or parts thereof) of the given
8626 * expression has no effect in order to generate a warning about this fact.
8627 * Therefore in some cases this only examines some of the operands of the
8628 * expression (see comments in the function and examples below).
8630 * f() + 23; // warning, because + has no effect
8631 * x || f(); // no warning, because x controls execution of f()
8632 * x ? y : f(); // warning, because y has no effect
8633 * (void)x; // no warning to be able to suppress the warning
8634 * This function can NOT be used for an "expression has definitely no effect"-
8636 static bool expression_has_effect(const expression_t *const expr)
8638 switch (expr->kind) {
8639 case EXPR_UNKNOWN: break;
8640 case EXPR_INVALID: return true; /* do NOT warn */
8641 case EXPR_REFERENCE: return false;
8642 /* suppress the warning for microsoft __noop operations */
8643 case EXPR_CONST: return expr->conste.is_ms_noop;
8644 case EXPR_CHARACTER_CONSTANT: return false;
8645 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8646 case EXPR_STRING_LITERAL: return false;
8647 case EXPR_WIDE_STRING_LITERAL: return false;
8648 case EXPR_LABEL_ADDRESS: return false;
8651 const call_expression_t *const call = &expr->call;
8652 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8655 switch (call->function->builtin_symbol.symbol->ID) {
8656 case T___builtin_va_end: return true;
8657 default: return false;
8661 /* Generate the warning if either the left or right hand side of a
8662 * conditional expression has no effect */
8663 case EXPR_CONDITIONAL: {
8664 const conditional_expression_t *const cond = &expr->conditional;
8666 expression_has_effect(cond->true_expression) &&
8667 expression_has_effect(cond->false_expression);
8670 case EXPR_SELECT: return false;
8671 case EXPR_ARRAY_ACCESS: return false;
8672 case EXPR_SIZEOF: return false;
8673 case EXPR_CLASSIFY_TYPE: return false;
8674 case EXPR_ALIGNOF: return false;
8676 case EXPR_FUNCNAME: return false;
8677 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8678 case EXPR_BUILTIN_CONSTANT_P: return false;
8679 case EXPR_BUILTIN_PREFETCH: return true;
8680 case EXPR_OFFSETOF: return false;
8681 case EXPR_VA_START: return true;
8682 case EXPR_VA_ARG: return true;
8683 case EXPR_STATEMENT: return true; // TODO
8684 case EXPR_COMPOUND_LITERAL: return false;
8686 case EXPR_UNARY_NEGATE: return false;
8687 case EXPR_UNARY_PLUS: return false;
8688 case EXPR_UNARY_BITWISE_NEGATE: return false;
8689 case EXPR_UNARY_NOT: return false;
8690 case EXPR_UNARY_DEREFERENCE: return false;
8691 case EXPR_UNARY_TAKE_ADDRESS: return false;
8692 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8693 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8694 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8695 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8697 /* Treat void casts as if they have an effect in order to being able to
8698 * suppress the warning */
8699 case EXPR_UNARY_CAST: {
8700 type_t *const type = skip_typeref(expr->base.type);
8701 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8704 case EXPR_UNARY_CAST_IMPLICIT: return true;
8705 case EXPR_UNARY_ASSUME: return true;
8706 case EXPR_UNARY_DELETE: return true;
8707 case EXPR_UNARY_DELETE_ARRAY: return true;
8708 case EXPR_UNARY_THROW: return true;
8710 case EXPR_BINARY_ADD: return false;
8711 case EXPR_BINARY_SUB: return false;
8712 case EXPR_BINARY_MUL: return false;
8713 case EXPR_BINARY_DIV: return false;
8714 case EXPR_BINARY_MOD: return false;
8715 case EXPR_BINARY_EQUAL: return false;
8716 case EXPR_BINARY_NOTEQUAL: return false;
8717 case EXPR_BINARY_LESS: return false;
8718 case EXPR_BINARY_LESSEQUAL: return false;
8719 case EXPR_BINARY_GREATER: return false;
8720 case EXPR_BINARY_GREATEREQUAL: return false;
8721 case EXPR_BINARY_BITWISE_AND: return false;
8722 case EXPR_BINARY_BITWISE_OR: return false;
8723 case EXPR_BINARY_BITWISE_XOR: return false;
8724 case EXPR_BINARY_SHIFTLEFT: return false;
8725 case EXPR_BINARY_SHIFTRIGHT: return false;
8726 case EXPR_BINARY_ASSIGN: return true;
8727 case EXPR_BINARY_MUL_ASSIGN: return true;
8728 case EXPR_BINARY_DIV_ASSIGN: return true;
8729 case EXPR_BINARY_MOD_ASSIGN: return true;
8730 case EXPR_BINARY_ADD_ASSIGN: return true;
8731 case EXPR_BINARY_SUB_ASSIGN: return true;
8732 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8733 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8734 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8735 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8736 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8738 /* Only examine the right hand side of && and ||, because the left hand
8739 * side already has the effect of controlling the execution of the right
8741 case EXPR_BINARY_LOGICAL_AND:
8742 case EXPR_BINARY_LOGICAL_OR:
8743 /* Only examine the right hand side of a comma expression, because the left
8744 * hand side has a separate warning */
8745 case EXPR_BINARY_COMMA:
8746 return expression_has_effect(expr->binary.right);
8748 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8749 case EXPR_BINARY_ISGREATER: return false;
8750 case EXPR_BINARY_ISGREATEREQUAL: return false;
8751 case EXPR_BINARY_ISLESS: return false;
8752 case EXPR_BINARY_ISLESSEQUAL: return false;
8753 case EXPR_BINARY_ISLESSGREATER: return false;
8754 case EXPR_BINARY_ISUNORDERED: return false;
8757 internal_errorf(HERE, "unexpected expression");
8760 static void semantic_comma(binary_expression_t *expression)
8762 if (warning.unused_value) {
8763 const expression_t *const left = expression->left;
8764 if (!expression_has_effect(left)) {
8765 warningf(&left->base.source_position,
8766 "left-hand operand of comma expression has no effect");
8769 expression->base.type = expression->right->base.type;
8773 * @param prec_r precedence of the right operand
8775 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8776 static expression_t *parse_##binexpression_type(expression_t *left) \
8778 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8779 binexpr->base.source_position = *HERE; \
8780 binexpr->binary.left = left; \
8783 expression_t *right = parse_sub_expression(prec_r); \
8785 binexpr->binary.right = right; \
8786 sfunc(&binexpr->binary); \
8791 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8792 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8793 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8794 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8795 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8796 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8797 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8798 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8799 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8800 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8801 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8802 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8803 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8804 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8805 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8806 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8807 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8808 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8809 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8810 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8811 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8812 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8813 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8814 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8815 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8816 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8817 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8818 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8819 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8820 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8823 static expression_t *parse_sub_expression(precedence_t precedence)
8825 if (token.type < 0) {
8826 return expected_expression_error();
8829 expression_parser_function_t *parser
8830 = &expression_parsers[token.type];
8831 source_position_t source_position = token.source_position;
8834 if (parser->parser != NULL) {
8835 left = parser->parser();
8837 left = parse_primary_expression();
8839 assert(left != NULL);
8840 left->base.source_position = source_position;
8843 if (token.type < 0) {
8844 return expected_expression_error();
8847 parser = &expression_parsers[token.type];
8848 if (parser->infix_parser == NULL)
8850 if (parser->infix_precedence < precedence)
8853 left = parser->infix_parser(left);
8855 assert(left != NULL);
8856 assert(left->kind != EXPR_UNKNOWN);
8857 left->base.source_position = source_position;
8864 * Parse an expression.
8866 static expression_t *parse_expression(void)
8868 return parse_sub_expression(PREC_EXPRESSION);
8872 * Register a parser for a prefix-like operator.
8874 * @param parser the parser function
8875 * @param token_type the token type of the prefix token
8877 static void register_expression_parser(parse_expression_function parser,
8880 expression_parser_function_t *entry = &expression_parsers[token_type];
8882 if (entry->parser != NULL) {
8883 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8884 panic("trying to register multiple expression parsers for a token");
8886 entry->parser = parser;
8890 * Register a parser for an infix operator with given precedence.
8892 * @param parser the parser function
8893 * @param token_type the token type of the infix operator
8894 * @param precedence the precedence of the operator
8896 static void register_infix_parser(parse_expression_infix_function parser,
8897 int token_type, unsigned precedence)
8899 expression_parser_function_t *entry = &expression_parsers[token_type];
8901 if (entry->infix_parser != NULL) {
8902 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8903 panic("trying to register multiple infix expression parsers for a "
8906 entry->infix_parser = parser;
8907 entry->infix_precedence = precedence;
8911 * Initialize the expression parsers.
8913 static void init_expression_parsers(void)
8915 memset(&expression_parsers, 0, sizeof(expression_parsers));
8917 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8918 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8919 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8920 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8921 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8922 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8923 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8924 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8925 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8926 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8927 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8928 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8929 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8930 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8931 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8932 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8933 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8934 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8935 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8936 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8937 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8938 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8939 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8940 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8941 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8942 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8943 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8944 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8945 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8946 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8947 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8948 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8949 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8950 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8951 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8952 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8953 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8955 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8956 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8957 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8958 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8959 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8960 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8961 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8962 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8963 register_expression_parser(parse_sizeof, T_sizeof);
8964 register_expression_parser(parse_alignof, T___alignof__);
8965 register_expression_parser(parse_extension, T___extension__);
8966 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8967 register_expression_parser(parse_delete, T_delete);
8968 register_expression_parser(parse_throw, T_throw);
8972 * Parse a asm statement arguments specification.
8974 static asm_argument_t *parse_asm_arguments(bool is_out)
8976 asm_argument_t *result = NULL;
8977 asm_argument_t *last = NULL;
8979 while (token.type == T_STRING_LITERAL || token.type == '[') {
8980 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8981 memset(argument, 0, sizeof(argument[0]));
8983 if (token.type == '[') {
8985 if (token.type != T_IDENTIFIER) {
8986 parse_error_expected("while parsing asm argument",
8987 T_IDENTIFIER, NULL);
8990 argument->symbol = token.v.symbol;
8995 argument->constraints = parse_string_literals();
8997 add_anchor_token(')');
8998 expression_t *expression = parse_expression();
8999 rem_anchor_token(')');
9001 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9002 * change size or type representation (e.g. int -> long is ok, but
9003 * int -> float is not) */
9004 if (expression->kind == EXPR_UNARY_CAST) {
9005 type_t *const type = expression->base.type;
9006 type_kind_t const kind = type->kind;
9007 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9010 if (kind == TYPE_ATOMIC) {
9011 atomic_type_kind_t const akind = type->atomic.akind;
9012 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9013 size = get_atomic_type_size(akind);
9015 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9016 size = get_atomic_type_size(get_intptr_kind());
9020 expression_t *const value = expression->unary.value;
9021 type_t *const value_type = value->base.type;
9022 type_kind_t const value_kind = value_type->kind;
9024 unsigned value_flags;
9025 unsigned value_size;
9026 if (value_kind == TYPE_ATOMIC) {
9027 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9028 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9029 value_size = get_atomic_type_size(value_akind);
9030 } else if (value_kind == TYPE_POINTER) {
9031 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9032 value_size = get_atomic_type_size(get_intptr_kind());
9037 if (value_flags != flags || value_size != size)
9041 } while (expression->kind == EXPR_UNARY_CAST);
9045 if (!is_lvalue(expression)) {
9046 errorf(&expression->base.source_position,
9047 "asm output argument is not an lvalue");
9050 if (argument->constraints.begin[0] == '+')
9051 mark_decls_read(expression, NULL);
9053 mark_decls_read(expression, NULL);
9055 argument->expression = expression;
9058 set_address_taken(expression, true);
9061 last->next = argument;
9067 if (token.type != ',')
9078 * Parse a asm statement clobber specification.
9080 static asm_clobber_t *parse_asm_clobbers(void)
9082 asm_clobber_t *result = NULL;
9083 asm_clobber_t *last = NULL;
9085 while(token.type == T_STRING_LITERAL) {
9086 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9087 clobber->clobber = parse_string_literals();
9090 last->next = clobber;
9096 if (token.type != ',')
9105 * Parse an asm statement.
9107 static statement_t *parse_asm_statement(void)
9109 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9110 asm_statement_t *asm_statement = &statement->asms;
9114 if (token.type == T_volatile) {
9116 asm_statement->is_volatile = true;
9120 add_anchor_token(')');
9121 add_anchor_token(':');
9122 asm_statement->asm_text = parse_string_literals();
9124 if (token.type != ':') {
9125 rem_anchor_token(':');
9130 asm_statement->outputs = parse_asm_arguments(true);
9131 if (token.type != ':') {
9132 rem_anchor_token(':');
9137 asm_statement->inputs = parse_asm_arguments(false);
9138 if (token.type != ':') {
9139 rem_anchor_token(':');
9142 rem_anchor_token(':');
9145 asm_statement->clobbers = parse_asm_clobbers();
9148 rem_anchor_token(')');
9152 if (asm_statement->outputs == NULL) {
9153 /* GCC: An 'asm' instruction without any output operands will be treated
9154 * identically to a volatile 'asm' instruction. */
9155 asm_statement->is_volatile = true;
9160 return create_invalid_statement();
9164 * Parse a case statement.
9166 static statement_t *parse_case_statement(void)
9168 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9169 source_position_t *const pos = &statement->base.source_position;
9173 expression_t *const expression = parse_expression();
9174 statement->case_label.expression = expression;
9175 if (!is_constant_expression(expression)) {
9176 /* This check does not prevent the error message in all cases of an
9177 * prior error while parsing the expression. At least it catches the
9178 * common case of a mistyped enum entry. */
9179 if (is_type_valid(skip_typeref(expression->base.type))) {
9180 errorf(pos, "case label does not reduce to an integer constant");
9182 statement->case_label.is_bad = true;
9184 long const val = fold_constant(expression);
9185 statement->case_label.first_case = val;
9186 statement->case_label.last_case = val;
9190 if (token.type == T_DOTDOTDOT) {
9192 expression_t *const end_range = parse_expression();
9193 statement->case_label.end_range = end_range;
9194 if (!is_constant_expression(end_range)) {
9195 /* This check does not prevent the error message in all cases of an
9196 * prior error while parsing the expression. At least it catches the
9197 * common case of a mistyped enum entry. */
9198 if (is_type_valid(skip_typeref(end_range->base.type))) {
9199 errorf(pos, "case range does not reduce to an integer constant");
9201 statement->case_label.is_bad = true;
9203 long const val = fold_constant(end_range);
9204 statement->case_label.last_case = val;
9206 if (warning.other && val < statement->case_label.first_case) {
9207 statement->case_label.is_empty_range = true;
9208 warningf(pos, "empty range specified");
9214 PUSH_PARENT(statement);
9218 if (current_switch != NULL) {
9219 if (! statement->case_label.is_bad) {
9220 /* Check for duplicate case values */
9221 case_label_statement_t *c = &statement->case_label;
9222 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9223 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9226 if (c->last_case < l->first_case || c->first_case > l->last_case)
9229 errorf(pos, "duplicate case value (previously used %P)",
9230 &l->base.source_position);
9234 /* link all cases into the switch statement */
9235 if (current_switch->last_case == NULL) {
9236 current_switch->first_case = &statement->case_label;
9238 current_switch->last_case->next = &statement->case_label;
9240 current_switch->last_case = &statement->case_label;
9242 errorf(pos, "case label not within a switch statement");
9245 statement_t *const inner_stmt = parse_statement();
9246 statement->case_label.statement = inner_stmt;
9247 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9248 errorf(&inner_stmt->base.source_position, "declaration after case label");
9255 return create_invalid_statement();
9259 * Parse a default statement.
9261 static statement_t *parse_default_statement(void)
9263 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9267 PUSH_PARENT(statement);
9270 if (current_switch != NULL) {
9271 const case_label_statement_t *def_label = current_switch->default_label;
9272 if (def_label != NULL) {
9273 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9274 &def_label->base.source_position);
9276 current_switch->default_label = &statement->case_label;
9278 /* link all cases into the switch statement */
9279 if (current_switch->last_case == NULL) {
9280 current_switch->first_case = &statement->case_label;
9282 current_switch->last_case->next = &statement->case_label;
9284 current_switch->last_case = &statement->case_label;
9287 errorf(&statement->base.source_position,
9288 "'default' label not within a switch statement");
9291 statement_t *const inner_stmt = parse_statement();
9292 statement->case_label.statement = inner_stmt;
9293 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9294 errorf(&inner_stmt->base.source_position, "declaration after default label");
9301 return create_invalid_statement();
9305 * Parse a label statement.
9307 static statement_t *parse_label_statement(void)
9309 assert(token.type == T_IDENTIFIER);
9310 symbol_t *symbol = token.v.symbol;
9311 declaration_t *label = get_label(symbol);
9313 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9314 statement->label.label = label;
9318 PUSH_PARENT(statement);
9320 /* if statement is already set then the label is defined twice,
9321 * otherwise it was just mentioned in a goto/local label declaration so far */
9322 if (label->init.statement != NULL) {
9323 errorf(HERE, "duplicate label '%Y' (declared %P)",
9324 symbol, &label->source_position);
9326 label->source_position = token.source_position;
9327 label->init.statement = statement;
9332 if (token.type == '}') {
9333 /* TODO only warn? */
9334 if (warning.other && false) {
9335 warningf(HERE, "label at end of compound statement");
9336 statement->label.statement = create_empty_statement();
9338 errorf(HERE, "label at end of compound statement");
9339 statement->label.statement = create_invalid_statement();
9341 } else if (token.type == ';') {
9342 /* Eat an empty statement here, to avoid the warning about an empty
9343 * statement after a label. label:; is commonly used to have a label
9344 * before a closing brace. */
9345 statement->label.statement = create_empty_statement();
9348 statement_t *const inner_stmt = parse_statement();
9349 statement->label.statement = inner_stmt;
9350 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9351 errorf(&inner_stmt->base.source_position, "declaration after label");
9355 /* remember the labels in a list for later checking */
9356 if (label_last == NULL) {
9357 label_first = &statement->label;
9359 label_last->next = &statement->label;
9361 label_last = &statement->label;
9368 * Parse an if statement.
9370 static statement_t *parse_if(void)
9372 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9376 PUSH_PARENT(statement);
9378 add_anchor_token('{');
9381 add_anchor_token(')');
9382 expression_t *const expr = parse_expression();
9383 statement->ifs.condition = expr;
9384 mark_decls_read(expr, NULL);
9385 rem_anchor_token(')');
9389 rem_anchor_token('{');
9391 add_anchor_token(T_else);
9392 statement->ifs.true_statement = parse_statement();
9393 rem_anchor_token(T_else);
9395 if (token.type == T_else) {
9397 statement->ifs.false_statement = parse_statement();
9405 * Check that all enums are handled in a switch.
9407 * @param statement the switch statement to check
9409 static void check_enum_cases(const switch_statement_t *statement) {
9410 const type_t *type = skip_typeref(statement->expression->base.type);
9411 if (! is_type_enum(type))
9413 const enum_type_t *enumt = &type->enumt;
9415 /* if we have a default, no warnings */
9416 if (statement->default_label != NULL)
9419 /* FIXME: calculation of value should be done while parsing */
9420 const declaration_t *declaration;
9421 long last_value = -1;
9422 for (declaration = enumt->declaration->next;
9423 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
9424 declaration = declaration->next) {
9425 const expression_t *expression = declaration->init.enum_value;
9426 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9428 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9429 if (l->expression == NULL)
9431 if (l->first_case <= value && value <= l->last_case) {
9437 warningf(&statement->base.source_position,
9438 "enumeration value '%Y' not handled in switch", declaration->symbol);
9445 * Parse a switch statement.
9447 static statement_t *parse_switch(void)
9449 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9453 PUSH_PARENT(statement);
9456 add_anchor_token(')');
9457 expression_t *const expr = parse_expression();
9458 mark_decls_read(expr, NULL);
9459 type_t * type = skip_typeref(expr->base.type);
9460 if (is_type_integer(type)) {
9461 type = promote_integer(type);
9462 if (warning.traditional) {
9463 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9464 warningf(&expr->base.source_position,
9465 "'%T' switch expression not converted to '%T' in ISO C",
9469 } else if (is_type_valid(type)) {
9470 errorf(&expr->base.source_position,
9471 "switch quantity is not an integer, but '%T'", type);
9472 type = type_error_type;
9474 statement->switchs.expression = create_implicit_cast(expr, type);
9476 rem_anchor_token(')');
9478 switch_statement_t *rem = current_switch;
9479 current_switch = &statement->switchs;
9480 statement->switchs.body = parse_statement();
9481 current_switch = rem;
9483 if (warning.switch_default &&
9484 statement->switchs.default_label == NULL) {
9485 warningf(&statement->base.source_position, "switch has no default case");
9487 if (warning.switch_enum)
9488 check_enum_cases(&statement->switchs);
9494 return create_invalid_statement();
9497 static statement_t *parse_loop_body(statement_t *const loop)
9499 statement_t *const rem = current_loop;
9500 current_loop = loop;
9502 statement_t *const body = parse_statement();
9509 * Parse a while statement.
9511 static statement_t *parse_while(void)
9513 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9517 PUSH_PARENT(statement);
9520 add_anchor_token(')');
9521 expression_t *const cond = parse_expression();
9522 statement->whiles.condition = cond;
9523 mark_decls_read(cond, NULL);
9524 rem_anchor_token(')');
9527 statement->whiles.body = parse_loop_body(statement);
9533 return create_invalid_statement();
9537 * Parse a do statement.
9539 static statement_t *parse_do(void)
9541 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9545 PUSH_PARENT(statement);
9547 add_anchor_token(T_while);
9548 statement->do_while.body = parse_loop_body(statement);
9549 rem_anchor_token(T_while);
9553 add_anchor_token(')');
9554 expression_t *const cond = parse_expression();
9555 statement->do_while.condition = cond;
9556 mark_decls_read(cond, NULL);
9557 rem_anchor_token(')');
9565 return create_invalid_statement();
9569 * Parse a for statement.
9571 static statement_t *parse_for(void)
9573 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9577 PUSH_PARENT(statement);
9579 size_t const top = environment_top();
9580 scope_push(&statement->fors.scope);
9583 add_anchor_token(')');
9585 if (token.type != ';') {
9586 if (is_declaration_specifier(&token, false)) {
9587 parse_declaration(record_declaration);
9589 add_anchor_token(';');
9590 expression_t *const init = parse_expression();
9591 statement->fors.initialisation = init;
9592 mark_decls_read(init, DECL_ANY);
9593 if (warning.unused_value && !expression_has_effect(init)) {
9594 warningf(&init->base.source_position,
9595 "initialisation of 'for'-statement has no effect");
9597 rem_anchor_token(';');
9604 if (token.type != ';') {
9605 add_anchor_token(';');
9606 expression_t *const cond = parse_expression();
9607 statement->fors.condition = cond;
9608 mark_decls_read(cond, NULL);
9609 rem_anchor_token(';');
9612 if (token.type != ')') {
9613 expression_t *const step = parse_expression();
9614 statement->fors.step = step;
9615 mark_decls_read(step, DECL_ANY);
9616 if (warning.unused_value && !expression_has_effect(step)) {
9617 warningf(&step->base.source_position,
9618 "step of 'for'-statement has no effect");
9622 rem_anchor_token(')');
9623 statement->fors.body = parse_loop_body(statement);
9625 assert(scope == &statement->fors.scope);
9627 environment_pop_to(top);
9634 rem_anchor_token(')');
9635 assert(scope == &statement->fors.scope);
9637 environment_pop_to(top);
9639 return create_invalid_statement();
9643 * Parse a goto statement.
9645 static statement_t *parse_goto(void)
9647 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9650 if (GNU_MODE && token.type == '*') {
9652 expression_t *expression = parse_expression();
9653 mark_decls_read(expression, NULL);
9655 /* Argh: although documentation say the expression must be of type void *,
9656 * gcc excepts anything that can be casted into void * without error */
9657 type_t *type = expression->base.type;
9659 if (type != type_error_type) {
9660 if (!is_type_pointer(type) && !is_type_integer(type)) {
9661 errorf(&expression->base.source_position,
9662 "cannot convert to a pointer type");
9663 } else if (warning.other && type != type_void_ptr) {
9664 warningf(&expression->base.source_position,
9665 "type of computed goto expression should be 'void*' not '%T'", type);
9667 expression = create_implicit_cast(expression, type_void_ptr);
9670 statement->gotos.expression = expression;
9672 if (token.type != T_IDENTIFIER) {
9674 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9676 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9680 symbol_t *symbol = token.v.symbol;
9683 statement->gotos.label = get_label(symbol);
9686 /* remember the goto's in a list for later checking */
9687 if (goto_last == NULL) {
9688 goto_first = &statement->gotos;
9690 goto_last->next = &statement->gotos;
9692 goto_last = &statement->gotos;
9698 return create_invalid_statement();
9702 * Parse a continue statement.
9704 static statement_t *parse_continue(void)
9706 if (current_loop == NULL) {
9707 errorf(HERE, "continue statement not within loop");
9710 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9720 * Parse a break statement.
9722 static statement_t *parse_break(void)
9724 if (current_switch == NULL && current_loop == NULL) {
9725 errorf(HERE, "break statement not within loop or switch");
9728 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9738 * Parse a __leave statement.
9740 static statement_t *parse_leave_statement(void)
9742 if (current_try == NULL) {
9743 errorf(HERE, "__leave statement not within __try");
9746 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9756 * Check if a given declaration represents a local variable.
9758 static bool is_local_var_declaration(const declaration_t *declaration)
9760 switch ((storage_class_tag_t) declaration->storage_class) {
9761 case STORAGE_CLASS_AUTO:
9762 case STORAGE_CLASS_REGISTER: {
9763 const type_t *type = skip_typeref(declaration->type);
9764 if (is_type_function(type)) {
9776 * Check if a given declaration represents a variable.
9778 static bool is_var_declaration(const declaration_t *declaration)
9780 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9783 const type_t *type = skip_typeref(declaration->type);
9784 return !is_type_function(type);
9788 * Check if a given expression represents a local variable.
9790 static bool is_local_variable(const expression_t *expression)
9792 if (expression->base.kind != EXPR_REFERENCE) {
9795 const declaration_t *declaration = expression->reference.declaration;
9796 return is_local_var_declaration(declaration);
9800 * Check if a given expression represents a local variable and
9801 * return its declaration then, else return NULL.
9803 declaration_t *expr_is_variable(const expression_t *expression)
9805 if (expression->base.kind != EXPR_REFERENCE) {
9808 declaration_t *declaration = expression->reference.declaration;
9809 if (is_var_declaration(declaration))
9815 * Parse a return statement.
9817 static statement_t *parse_return(void)
9821 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9823 expression_t *return_value = NULL;
9824 if (token.type != ';') {
9825 return_value = parse_expression();
9826 mark_decls_read(return_value, NULL);
9829 const type_t *const func_type = current_function->type;
9830 assert(is_type_function(func_type));
9831 type_t *const return_type = skip_typeref(func_type->function.return_type);
9833 if (return_value != NULL) {
9834 type_t *return_value_type = skip_typeref(return_value->base.type);
9836 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
9837 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9838 if (warning.other) {
9839 warningf(&statement->base.source_position,
9840 "'return' with a value, in function returning void");
9842 return_value = NULL;
9844 assign_error_t error = semantic_assign(return_type, return_value);
9845 report_assign_error(error, return_type, return_value, "'return'",
9846 &statement->base.source_position);
9847 return_value = create_implicit_cast(return_value, return_type);
9849 /* check for returning address of a local var */
9850 if (warning.other &&
9851 return_value != NULL &&
9852 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9853 const expression_t *expression = return_value->unary.value;
9854 if (is_local_variable(expression)) {
9855 warningf(&statement->base.source_position,
9856 "function returns address of local variable");
9859 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9860 warningf(&statement->base.source_position,
9861 "'return' without value, in function returning non-void");
9863 statement->returns.value = return_value;
9872 * Parse a declaration statement.
9874 static statement_t *parse_declaration_statement(void)
9876 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9878 declaration_t *before = last_declaration;
9880 parse_external_declaration();
9882 parse_declaration(record_declaration);
9884 if (before == NULL) {
9885 statement->declaration.declarations_begin = scope->declarations;
9887 statement->declaration.declarations_begin = before->next;
9889 statement->declaration.declarations_end = last_declaration;
9895 * Parse an expression statement, ie. expr ';'.
9897 static statement_t *parse_expression_statement(void)
9899 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9901 expression_t *const expr = parse_expression();
9902 statement->expression.expression = expr;
9903 mark_decls_read(expr, DECL_ANY);
9912 * Parse a microsoft __try { } __finally { } or
9913 * __try{ } __except() { }
9915 static statement_t *parse_ms_try_statment(void)
9917 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9920 PUSH_PARENT(statement);
9922 ms_try_statement_t *rem = current_try;
9923 current_try = &statement->ms_try;
9924 statement->ms_try.try_statement = parse_compound_statement(false);
9929 if (token.type == T___except) {
9932 add_anchor_token(')');
9933 expression_t *const expr = parse_expression();
9934 mark_decls_read(expr, NULL);
9935 type_t * type = skip_typeref(expr->base.type);
9936 if (is_type_integer(type)) {
9937 type = promote_integer(type);
9938 } else if (is_type_valid(type)) {
9939 errorf(&expr->base.source_position,
9940 "__expect expression is not an integer, but '%T'", type);
9941 type = type_error_type;
9943 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9944 rem_anchor_token(')');
9946 statement->ms_try.final_statement = parse_compound_statement(false);
9947 } else if (token.type == T__finally) {
9949 statement->ms_try.final_statement = parse_compound_statement(false);
9951 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9952 return create_invalid_statement();
9956 return create_invalid_statement();
9959 static statement_t *parse_empty_statement(void)
9961 if (warning.empty_statement) {
9962 warningf(HERE, "statement is empty");
9964 statement_t *const statement = create_empty_statement();
9969 static statement_t *parse_local_label_declaration(void) {
9970 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9974 declaration_t *begin = NULL, *end = NULL;
9977 if (token.type != T_IDENTIFIER) {
9978 parse_error_expected("while parsing local label declaration",
9979 T_IDENTIFIER, NULL);
9982 symbol_t *symbol = token.v.symbol;
9983 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9984 if (declaration != NULL) {
9985 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9986 symbol, &declaration->source_position);
9988 declaration = allocate_declaration_zero();
9989 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9990 declaration->source_position = token.source_position;
9991 declaration->symbol = symbol;
9992 declaration->parent_scope = scope;
9993 declaration->init.statement = NULL;
9996 end->next = declaration;
9999 begin = declaration;
10001 local_label_push(declaration);
10005 if (token.type != ',')
10011 statement->declaration.declarations_begin = begin;
10012 statement->declaration.declarations_end = end;
10017 * Parse a statement.
10018 * There's also parse_statement() which additionally checks for
10019 * "statement has no effect" warnings
10021 static statement_t *intern_parse_statement(void)
10023 statement_t *statement = NULL;
10025 /* declaration or statement */
10026 add_anchor_token(';');
10027 switch (token.type) {
10028 case T_IDENTIFIER: {
10029 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10030 if (la1_type == ':') {
10031 statement = parse_label_statement();
10032 } else if (is_typedef_symbol(token.v.symbol)) {
10033 statement = parse_declaration_statement();
10034 } else switch (la1_type) {
10036 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10037 goto expression_statment;
10042 statement = parse_declaration_statement();
10046 expression_statment:
10047 statement = parse_expression_statement();
10053 case T___extension__:
10054 /* This can be a prefix to a declaration or an expression statement.
10055 * We simply eat it now and parse the rest with tail recursion. */
10058 } while (token.type == T___extension__);
10059 bool old_gcc_extension = in_gcc_extension;
10060 in_gcc_extension = true;
10061 statement = parse_statement();
10062 in_gcc_extension = old_gcc_extension;
10066 statement = parse_declaration_statement();
10070 statement = parse_local_label_declaration();
10073 case ';': statement = parse_empty_statement(); break;
10074 case '{': statement = parse_compound_statement(false); break;
10075 case T___leave: statement = parse_leave_statement(); break;
10076 case T___try: statement = parse_ms_try_statment(); break;
10077 case T_asm: statement = parse_asm_statement(); break;
10078 case T_break: statement = parse_break(); break;
10079 case T_case: statement = parse_case_statement(); break;
10080 case T_continue: statement = parse_continue(); break;
10081 case T_default: statement = parse_default_statement(); break;
10082 case T_do: statement = parse_do(); break;
10083 case T_for: statement = parse_for(); break;
10084 case T_goto: statement = parse_goto(); break;
10085 case T_if: statement = parse_if(); break;
10086 case T_return: statement = parse_return(); break;
10087 case T_switch: statement = parse_switch(); break;
10088 case T_while: statement = parse_while(); break;
10091 statement = parse_expression_statement();
10095 errorf(HERE, "unexpected token %K while parsing statement", &token);
10096 statement = create_invalid_statement();
10101 rem_anchor_token(';');
10103 assert(statement != NULL
10104 && statement->base.source_position.input_name != NULL);
10110 * parse a statement and emits "statement has no effect" warning if needed
10111 * (This is really a wrapper around intern_parse_statement with check for 1
10112 * single warning. It is needed, because for statement expressions we have
10113 * to avoid the warning on the last statement)
10115 static statement_t *parse_statement(void)
10117 statement_t *statement = intern_parse_statement();
10119 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10120 expression_t *expression = statement->expression.expression;
10121 if (!expression_has_effect(expression)) {
10122 warningf(&expression->base.source_position,
10123 "statement has no effect");
10131 * Parse a compound statement.
10133 static statement_t *parse_compound_statement(bool inside_expression_statement)
10135 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10137 PUSH_PARENT(statement);
10140 add_anchor_token('}');
10142 size_t const top = environment_top();
10143 size_t const top_local = local_label_top();
10144 scope_push(&statement->compound.scope);
10146 statement_t **anchor = &statement->compound.statements;
10147 bool only_decls_so_far = true;
10148 while (token.type != '}') {
10149 if (token.type == T_EOF) {
10150 errorf(&statement->base.source_position,
10151 "EOF while parsing compound statement");
10154 statement_t *sub_statement = intern_parse_statement();
10155 if (is_invalid_statement(sub_statement)) {
10156 /* an error occurred. if we are at an anchor, return */
10162 if (warning.declaration_after_statement) {
10163 if (sub_statement->kind != STATEMENT_DECLARATION) {
10164 only_decls_so_far = false;
10165 } else if (!only_decls_so_far) {
10166 warningf(&sub_statement->base.source_position,
10167 "ISO C90 forbids mixed declarations and code");
10171 *anchor = sub_statement;
10173 while (sub_statement->base.next != NULL)
10174 sub_statement = sub_statement->base.next;
10176 anchor = &sub_statement->base.next;
10180 /* look over all statements again to produce no effect warnings */
10181 if (warning.unused_value) {
10182 statement_t *sub_statement = statement->compound.statements;
10183 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10184 if (sub_statement->kind != STATEMENT_EXPRESSION)
10186 /* don't emit a warning for the last expression in an expression
10187 * statement as it has always an effect */
10188 if (inside_expression_statement && sub_statement->base.next == NULL)
10191 expression_t *expression = sub_statement->expression.expression;
10192 if (!expression_has_effect(expression)) {
10193 warningf(&expression->base.source_position,
10194 "statement has no effect");
10200 rem_anchor_token('}');
10201 assert(scope == &statement->compound.scope);
10203 environment_pop_to(top);
10204 local_label_pop_to(top_local);
10211 * Initialize builtin types.
10213 static void initialize_builtin_types(void)
10215 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
10216 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
10217 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
10218 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
10219 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
10220 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
10221 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
10222 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
10224 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
10225 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
10226 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
10227 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
10229 /* const version of wchar_t */
10230 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF);
10231 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
10232 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
10234 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
10238 * Check for unused global static functions and variables
10240 static void check_unused_globals(void)
10242 if (!warning.unused_function && !warning.unused_variable)
10245 for (const declaration_t *decl = file_scope->declarations; decl != NULL; decl = decl->next) {
10247 decl->modifiers & DM_UNUSED ||
10248 decl->modifiers & DM_USED ||
10249 decl->storage_class != STORAGE_CLASS_STATIC)
10252 type_t *const type = decl->type;
10254 if (is_type_function(skip_typeref(type))) {
10255 if (!warning.unused_function || decl->is_inline)
10258 s = (decl->init.statement != NULL ? "defined" : "declared");
10260 if (!warning.unused_variable)
10266 warningf(&decl->source_position, "'%#T' %s but not used",
10267 type, decl->symbol, s);
10271 static void parse_global_asm(void)
10273 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10278 statement->asms.asm_text = parse_string_literals();
10279 statement->base.next = unit->global_asm;
10280 unit->global_asm = statement;
10289 * Parse a translation unit.
10291 static void parse_translation_unit(void)
10293 add_anchor_token(T_EOF);
10296 unsigned char token_anchor_copy[T_LAST_TOKEN];
10297 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10301 bool anchor_leak = false;
10302 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10303 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10305 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10306 anchor_leak = true;
10309 if (in_gcc_extension) {
10310 errorf(HERE, "Leaked __extension__");
10311 anchor_leak = true;
10318 switch (token.type) {
10321 case T___extension__:
10322 parse_external_declaration();
10326 parse_global_asm();
10330 rem_anchor_token(T_EOF);
10334 if (!strict_mode) {
10336 warningf(HERE, "stray ';' outside of function");
10343 errorf(HERE, "stray %K outside of function", &token);
10344 if (token.type == '(' || token.type == '{' || token.type == '[')
10345 eat_until_matching_token(token.type);
10355 * @return the translation unit or NULL if errors occurred.
10357 void start_parsing(void)
10359 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10360 label_stack = NEW_ARR_F(stack_entry_t, 0);
10361 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10362 diagnostic_count = 0;
10366 type_set_output(stderr);
10367 ast_set_output(stderr);
10369 assert(unit == NULL);
10370 unit = allocate_ast_zero(sizeof(unit[0]));
10372 assert(file_scope == NULL);
10373 file_scope = &unit->scope;
10375 assert(scope == NULL);
10376 scope_push(&unit->scope);
10378 initialize_builtin_types();
10381 translation_unit_t *finish_parsing(void)
10383 /* do NOT use scope_pop() here, this will crash, will it by hand */
10384 assert(scope == &unit->scope);
10386 last_declaration = NULL;
10388 assert(file_scope == &unit->scope);
10389 check_unused_globals();
10392 DEL_ARR_F(environment_stack);
10393 DEL_ARR_F(label_stack);
10394 DEL_ARR_F(local_label_stack);
10396 translation_unit_t *result = unit;
10403 lookahead_bufpos = 0;
10404 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10407 parse_translation_unit();
10411 * Initialize the parser.
10413 void init_parser(void)
10415 sym_anonymous = symbol_table_insert("<anonymous>");
10417 if (c_mode & _MS) {
10418 /* add predefined symbols for extended-decl-modifier */
10419 sym_align = symbol_table_insert("align");
10420 sym_allocate = symbol_table_insert("allocate");
10421 sym_dllimport = symbol_table_insert("dllimport");
10422 sym_dllexport = symbol_table_insert("dllexport");
10423 sym_naked = symbol_table_insert("naked");
10424 sym_noinline = symbol_table_insert("noinline");
10425 sym_noreturn = symbol_table_insert("noreturn");
10426 sym_nothrow = symbol_table_insert("nothrow");
10427 sym_novtable = symbol_table_insert("novtable");
10428 sym_property = symbol_table_insert("property");
10429 sym_get = symbol_table_insert("get");
10430 sym_put = symbol_table_insert("put");
10431 sym_selectany = symbol_table_insert("selectany");
10432 sym_thread = symbol_table_insert("thread");
10433 sym_uuid = symbol_table_insert("uuid");
10434 sym_deprecated = symbol_table_insert("deprecated");
10435 sym_restrict = symbol_table_insert("restrict");
10436 sym_noalias = symbol_table_insert("noalias");
10438 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10440 init_expression_parsers();
10441 obstack_init(&temp_obst);
10443 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10444 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10448 * Terminate the parser.
10450 void exit_parser(void)
10452 obstack_free(&temp_obst, NULL);