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"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 /** if wchar_t is equal to unsigned short. */
45 bool opt_short_wchar_t =
52 //#define PRINT_TOKENS
53 #define MAX_LOOKAHEAD 2
61 typedef struct argument_list_t argument_list_t;
62 struct argument_list_t {
64 argument_list_t *next;
67 typedef struct gnu_attribute_t gnu_attribute_t;
68 struct gnu_attribute_t {
69 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
70 gnu_attribute_t *next;
71 bool invalid; /**< Set if this attribute had argument errors, */
72 bool have_arguments; /**< True, if this attribute has arguments. */
76 atomic_type_kind_t akind;
77 long argument; /**< Single argument. */
78 argument_list_t *arguments; /**< List of argument expressions. */
82 typedef struct declaration_specifiers_t declaration_specifiers_t;
83 struct declaration_specifiers_t {
84 source_position_t source_position;
85 storage_class_t storage_class;
86 unsigned char alignment; /**< Alignment, 0 if not set. */
89 decl_modifiers_t modifiers; /**< declaration modifiers */
90 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
91 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
92 symbol_t *get_property_sym; /**< the name of the get property if set. */
93 symbol_t *put_property_sym; /**< the name of the put property if set. */
98 * An environment for parsing initializers (and compound literals).
100 typedef struct parse_initializer_env_t {
101 type_t *type; /**< the type of the initializer. In case of an
102 array type with unspecified size this gets
103 adjusted to the actual size. */
104 entity_t *entity; /**< the variable that is initialized if any */
105 bool must_be_constant;
106 } parse_initializer_env_t;
108 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
110 /** The current token. */
111 static token_t token;
112 /** The lookahead ring-buffer. */
113 static token_t lookahead_buffer[MAX_LOOKAHEAD];
114 /** Position of the next token in the lookahead buffer. */
115 static int lookahead_bufpos;
116 static stack_entry_t *environment_stack = NULL;
117 static stack_entry_t *label_stack = NULL;
118 static stack_entry_t *local_label_stack = NULL;
119 /** The global file scope. */
120 static scope_t *file_scope = NULL;
121 /** The current scope. */
122 static scope_t *scope = NULL;
123 /** Point to the current function declaration if inside a function. */
124 static function_t *current_function = NULL;
125 static entity_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(compound_t *compound_declaration);
190 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
191 bool may_be_abstract,
192 bool create_compound_member);
193 static entity_t *record_entity(entity_t *entity, bool is_definition);
195 static void semantic_comparison(binary_expression_t *expression);
197 #define STORAGE_CLASSES \
205 #define TYPE_QUALIFIERS \
210 case T__forceinline: \
211 case T___attribute__:
213 #ifdef PROVIDE_COMPLEX
214 #define COMPLEX_SPECIFIERS \
216 #define IMAGINARY_SPECIFIERS \
219 #define COMPLEX_SPECIFIERS
220 #define IMAGINARY_SPECIFIERS
223 #define TYPE_SPECIFIERS \
238 case T___builtin_va_list: \
243 #define DECLARATION_START \
248 #define TYPENAME_START \
252 #define EXPRESSION_START \
261 case T_CHARACTER_CONSTANT: \
262 case T_FLOATINGPOINT: \
266 case T_STRING_LITERAL: \
267 case T_WIDE_CHARACTER_CONSTANT: \
268 case T_WIDE_STRING_LITERAL: \
269 case T___FUNCDNAME__: \
270 case T___FUNCSIG__: \
271 case T___FUNCTION__: \
272 case T___PRETTY_FUNCTION__: \
273 case T___alignof__: \
274 case T___builtin_alloca: \
275 case T___builtin_classify_type: \
276 case T___builtin_constant_p: \
277 case T___builtin_expect: \
278 case T___builtin_huge_val: \
279 case T___builtin_inf: \
280 case T___builtin_inff: \
281 case T___builtin_infl: \
282 case T___builtin_isgreater: \
283 case T___builtin_isgreaterequal: \
284 case T___builtin_isless: \
285 case T___builtin_islessequal: \
286 case T___builtin_islessgreater: \
287 case T___builtin_isunordered: \
288 case T___builtin_nan: \
289 case T___builtin_nanf: \
290 case T___builtin_nanl: \
291 case T___builtin_offsetof: \
292 case T___builtin_prefetch: \
293 case T___builtin_va_arg: \
294 case T___builtin_va_end: \
295 case T___builtin_va_start: \
304 * Allocate an AST node with given size and
305 * initialize all fields with zero.
307 static void *allocate_ast_zero(size_t size)
309 void *res = allocate_ast(size);
310 memset(res, 0, size);
314 static size_t get_entity_struct_size(entity_kind_t kind)
316 static const size_t sizes[] = {
317 [ENTITY_VARIABLE] = sizeof(variable_t),
318 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
319 [ENTITY_FUNCTION] = sizeof(function_t),
320 [ENTITY_TYPEDEF] = sizeof(typedef_t),
321 [ENTITY_STRUCT] = sizeof(compound_t),
322 [ENTITY_UNION] = sizeof(compound_t),
323 [ENTITY_ENUM] = sizeof(enum_t),
324 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
325 [ENTITY_LABEL] = sizeof(label_t),
326 [ENTITY_LOCAL_LABEL] = sizeof(label_t)
328 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
329 assert(sizes[kind] != 0);
333 static entity_t *allocate_entity_zero(entity_kind_t kind)
335 size_t size = get_entity_struct_size(kind);
336 entity_t *entity = allocate_ast_zero(size);
342 * Returns the size of a statement node.
344 * @param kind the statement kind
346 static size_t get_statement_struct_size(statement_kind_t kind)
348 static const size_t sizes[] = {
349 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
350 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
351 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
352 [STATEMENT_RETURN] = sizeof(return_statement_t),
353 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
354 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
355 [STATEMENT_IF] = sizeof(if_statement_t),
356 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
357 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
358 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
359 [STATEMENT_BREAK] = sizeof(statement_base_t),
360 [STATEMENT_GOTO] = sizeof(goto_statement_t),
361 [STATEMENT_LABEL] = sizeof(label_statement_t),
362 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
363 [STATEMENT_WHILE] = sizeof(while_statement_t),
364 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
365 [STATEMENT_FOR] = sizeof(for_statement_t),
366 [STATEMENT_ASM] = sizeof(asm_statement_t),
367 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
368 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
370 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
371 assert(sizes[kind] != 0);
376 * Returns the size of an expression node.
378 * @param kind the expression kind
380 static size_t get_expression_struct_size(expression_kind_t kind)
382 static const size_t sizes[] = {
383 [EXPR_INVALID] = sizeof(expression_base_t),
384 [EXPR_REFERENCE] = sizeof(reference_expression_t),
385 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
386 [EXPR_CONST] = sizeof(const_expression_t),
387 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
388 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
389 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
390 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
391 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
392 [EXPR_CALL] = sizeof(call_expression_t),
393 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
394 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
395 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
396 [EXPR_SELECT] = sizeof(select_expression_t),
397 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
398 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
399 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
400 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
401 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
402 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
403 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
404 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
405 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
406 [EXPR_VA_START] = sizeof(va_start_expression_t),
407 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
408 [EXPR_STATEMENT] = sizeof(statement_expression_t),
409 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
411 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
412 return sizes[EXPR_UNARY_FIRST];
414 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
415 return sizes[EXPR_BINARY_FIRST];
417 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
418 assert(sizes[kind] != 0);
423 * Allocate a statement node of given kind and initialize all
426 static statement_t *allocate_statement_zero(statement_kind_t kind)
428 size_t size = get_statement_struct_size(kind);
429 statement_t *res = allocate_ast_zero(size);
431 res->base.kind = kind;
432 res->base.parent = current_parent;
433 res->base.source_position = token.source_position;
438 * Allocate an expression node of given kind and initialize all
441 static expression_t *allocate_expression_zero(expression_kind_t kind)
443 size_t size = get_expression_struct_size(kind);
444 expression_t *res = allocate_ast_zero(size);
446 res->base.kind = kind;
447 res->base.type = type_error_type;
452 * Creates a new invalid expression.
454 static expression_t *create_invalid_expression(void)
456 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
457 expression->base.source_position = token.source_position;
462 * Creates a new invalid statement.
464 static statement_t *create_invalid_statement(void)
466 return allocate_statement_zero(STATEMENT_INVALID);
470 * Allocate a new empty statement.
472 static statement_t *create_empty_statement(void)
474 return allocate_statement_zero(STATEMENT_EMPTY);
478 * Returns the size of a type node.
480 * @param kind the type kind
482 static size_t get_type_struct_size(type_kind_t kind)
484 static const size_t sizes[] = {
485 [TYPE_ATOMIC] = sizeof(atomic_type_t),
486 [TYPE_COMPLEX] = sizeof(complex_type_t),
487 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
488 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
489 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
490 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
491 [TYPE_ENUM] = sizeof(enum_type_t),
492 [TYPE_FUNCTION] = sizeof(function_type_t),
493 [TYPE_POINTER] = sizeof(pointer_type_t),
494 [TYPE_ARRAY] = sizeof(array_type_t),
495 [TYPE_BUILTIN] = sizeof(builtin_type_t),
496 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
497 [TYPE_TYPEOF] = sizeof(typeof_type_t),
499 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
500 assert(kind <= TYPE_TYPEOF);
501 assert(sizes[kind] != 0);
506 * Allocate a type node of given kind and initialize all
509 * @param kind type kind to allocate
511 static type_t *allocate_type_zero(type_kind_t kind)
513 size_t size = get_type_struct_size(kind);
514 type_t *res = obstack_alloc(type_obst, size);
515 memset(res, 0, size);
516 res->base.kind = kind;
522 * Returns the size of an initializer node.
524 * @param kind the initializer kind
526 static size_t get_initializer_size(initializer_kind_t kind)
528 static const size_t sizes[] = {
529 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
530 [INITIALIZER_STRING] = sizeof(initializer_string_t),
531 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
532 [INITIALIZER_LIST] = sizeof(initializer_list_t),
533 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
535 assert(kind < sizeof(sizes) / sizeof(*sizes));
536 assert(sizes[kind] != 0);
541 * Allocate an initializer node of given kind and initialize all
544 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
546 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
553 * Free a type from the type obstack.
555 static void free_type(void *type)
557 obstack_free(type_obst, type);
561 * Returns the index of the top element of the environment stack.
563 static size_t environment_top(void)
565 return ARR_LEN(environment_stack);
569 * Returns the index of the top element of the global label stack.
571 static size_t label_top(void)
573 return ARR_LEN(label_stack);
577 * Returns the index of the top element of the local label stack.
579 static size_t local_label_top(void)
581 return ARR_LEN(local_label_stack);
585 * Return the next token.
587 static inline void next_token(void)
589 token = lookahead_buffer[lookahead_bufpos];
590 lookahead_buffer[lookahead_bufpos] = lexer_token;
593 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
596 print_token(stderr, &token);
597 fprintf(stderr, "\n");
602 * Return the next token with a given lookahead.
604 static inline const token_t *look_ahead(int num)
606 assert(num > 0 && num <= MAX_LOOKAHEAD);
607 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
608 return &lookahead_buffer[pos];
612 * Adds a token to the token anchor set (a multi-set).
614 static void add_anchor_token(int token_type)
616 assert(0 <= token_type && token_type < T_LAST_TOKEN);
617 ++token_anchor_set[token_type];
620 static int save_and_reset_anchor_state(int token_type)
622 assert(0 <= token_type && token_type < T_LAST_TOKEN);
623 int count = token_anchor_set[token_type];
624 token_anchor_set[token_type] = 0;
628 static void restore_anchor_state(int token_type, int count)
630 assert(0 <= token_type && token_type < T_LAST_TOKEN);
631 token_anchor_set[token_type] = count;
635 * Remove a token from the token anchor set (a multi-set).
637 static void rem_anchor_token(int token_type)
639 assert(0 <= token_type && token_type < T_LAST_TOKEN);
640 assert(token_anchor_set[token_type] != 0);
641 --token_anchor_set[token_type];
644 static bool at_anchor(void)
648 return token_anchor_set[token.type];
652 * Eat tokens until a matching token is found.
654 static void eat_until_matching_token(int type)
658 case '(': end_token = ')'; break;
659 case '{': end_token = '}'; break;
660 case '[': end_token = ']'; break;
661 default: end_token = type; break;
664 unsigned parenthesis_count = 0;
665 unsigned brace_count = 0;
666 unsigned bracket_count = 0;
667 while (token.type != end_token ||
668 parenthesis_count != 0 ||
670 bracket_count != 0) {
671 switch (token.type) {
673 case '(': ++parenthesis_count; break;
674 case '{': ++brace_count; break;
675 case '[': ++bracket_count; break;
678 if (parenthesis_count > 0)
688 if (bracket_count > 0)
691 if (token.type == end_token &&
692 parenthesis_count == 0 &&
706 * Eat input tokens until an anchor is found.
708 static void eat_until_anchor(void)
710 while (token_anchor_set[token.type] == 0) {
711 if (token.type == '(' || token.type == '{' || token.type == '[')
712 eat_until_matching_token(token.type);
717 static void eat_block(void)
719 eat_until_matching_token('{');
720 if (token.type == '}')
724 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
727 * Report a parse error because an expected token was not found.
730 #if defined __GNUC__ && __GNUC__ >= 4
731 __attribute__((sentinel))
733 void parse_error_expected(const char *message, ...)
735 if (message != NULL) {
736 errorf(HERE, "%s", message);
739 va_start(ap, message);
740 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
745 * Report a type error.
747 static void type_error(const char *msg, const source_position_t *source_position,
750 errorf(source_position, "%s, but found type '%T'", msg, type);
754 * Report an incompatible type.
756 static void type_error_incompatible(const char *msg,
757 const source_position_t *source_position, type_t *type1, type_t *type2)
759 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
764 * Expect the the current token is the expected token.
765 * If not, generate an error, eat the current statement,
766 * and goto the end_error label.
768 #define expect(expected) \
770 if (UNLIKELY(token.type != (expected))) { \
771 parse_error_expected(NULL, (expected), NULL); \
772 add_anchor_token(expected); \
773 eat_until_anchor(); \
774 if (token.type == expected) \
776 rem_anchor_token(expected); \
782 static void scope_push(scope_t *new_scope)
785 new_scope->depth = scope->depth + 1;
787 new_scope->parent = scope;
791 static void scope_pop(void)
793 scope = scope->parent;
797 * Search an entity by its symbol in a given namespace.
799 static entity_t *get_entity(const symbol_t *const symbol, namespace_t namespc)
801 entity_t *entity = symbol->entity;
802 for( ; entity != NULL; entity = entity->base.symbol_next) {
803 if (entity->base.namespc == namespc)
811 * pushs an entity on the environment stack and links the corresponding symbol
814 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
816 symbol_t *symbol = entity->base.symbol;
817 namespace_t namespc = entity->base.namespc;
818 assert(namespc != NAMESPACE_INVALID);
820 /* replace/add entity into entity list of the symbol */
823 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
828 /* replace an entry? */
829 if (iter->base.namespc == namespc) {
830 entity->base.symbol_next = iter->base.symbol_next;
836 /* remember old declaration */
838 entry.symbol = symbol;
839 entry.old_entity = iter;
840 entry.namespc = namespc;
841 ARR_APP1(stack_entry_t, *stack_ptr, entry);
845 * Push an entity on the environment stack.
847 static void environment_push(entity_t *entity)
849 assert(entity->base.source_position.input_name != NULL);
850 assert(entity->base.parent_scope != NULL);
851 stack_push(&environment_stack, entity);
855 * Push a declaration on the global label stack.
857 * @param declaration the declaration
859 static void label_push(entity_t *label)
861 /* we abuse the parameters scope as parent for the labels */
862 label->base.parent_scope = ¤t_function->parameters;
863 stack_push(&label_stack, label);
867 * Push a declaration of the local label stack.
869 * @param declaration the declaration
871 static void local_label_push(entity_t *label)
873 assert(label->base.parent_scope != NULL);
874 label->base.parent_scope = scope;
875 stack_push(&local_label_stack, label);
879 * pops symbols from the environment stack until @p new_top is the top element
881 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
883 stack_entry_t *stack = *stack_ptr;
884 size_t top = ARR_LEN(stack);
887 assert(new_top <= top);
891 for(i = top; i > new_top; --i) {
892 stack_entry_t *entry = &stack[i - 1];
894 entity_t *old_entity = entry->old_entity;
895 symbol_t *symbol = entry->symbol;
896 namespace_t namespc = entry->namespc;
898 /* replace with old_entity/remove */
901 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
903 assert(iter != NULL);
904 /* replace an entry? */
905 if (iter->base.namespc == namespc)
909 /* restore definition from outer scopes (if there was one) */
910 if (old_entity != NULL) {
911 old_entity->base.symbol_next = iter->base.symbol_next;
912 *anchor = old_entity;
914 /* remove entry from list */
915 *anchor = iter->base.symbol_next;
919 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
923 * Pop all entries from the environment stack until the new_top
926 * @param new_top the new stack top
928 static void environment_pop_to(size_t new_top)
930 stack_pop_to(&environment_stack, new_top);
934 * Pop all entries from the global label stack until the new_top
937 * @param new_top the new stack top
939 static void label_pop_to(size_t new_top)
941 stack_pop_to(&label_stack, new_top);
945 * Pop all entries from the local label stack until the new_top
948 * @param new_top the new stack top
950 static void local_label_pop_to(size_t new_top)
952 stack_pop_to(&local_label_stack, new_top);
956 static int get_akind_rank(atomic_type_kind_t akind)
961 static int get_rank(const type_t *type)
963 assert(!is_typeref(type));
964 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
965 * and esp. footnote 108). However we can't fold constants (yet), so we
966 * can't decide whether unsigned int is possible, while int always works.
967 * (unsigned int would be preferable when possible... for stuff like
968 * struct { enum { ... } bla : 4; } ) */
969 if (type->kind == TYPE_ENUM)
970 return get_akind_rank(ATOMIC_TYPE_INT);
972 assert(type->kind == TYPE_ATOMIC);
973 return get_akind_rank(type->atomic.akind);
976 static type_t *promote_integer(type_t *type)
978 if (type->kind == TYPE_BITFIELD)
979 type = type->bitfield.base_type;
981 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
988 * Create a cast expression.
990 * @param expression the expression to cast
991 * @param dest_type the destination type
993 static expression_t *create_cast_expression(expression_t *expression,
996 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
998 cast->unary.value = expression;
999 cast->base.type = dest_type;
1005 * Check if a given expression represents the 0 pointer constant.
1007 static bool is_null_pointer_constant(const expression_t *expression)
1009 /* skip void* cast */
1010 if (expression->kind == EXPR_UNARY_CAST
1011 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1012 expression = expression->unary.value;
1015 /* TODO: not correct yet, should be any constant integer expression
1016 * which evaluates to 0 */
1017 if (expression->kind != EXPR_CONST)
1020 type_t *const type = skip_typeref(expression->base.type);
1021 if (!is_type_integer(type))
1024 return expression->conste.v.int_value == 0;
1028 * Create an implicit cast expression.
1030 * @param expression the expression to cast
1031 * @param dest_type the destination type
1033 static expression_t *create_implicit_cast(expression_t *expression,
1036 type_t *const source_type = expression->base.type;
1038 if (source_type == dest_type)
1041 return create_cast_expression(expression, dest_type);
1044 typedef enum assign_error_t {
1046 ASSIGN_ERROR_INCOMPATIBLE,
1047 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1048 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1049 ASSIGN_WARNING_POINTER_FROM_INT,
1050 ASSIGN_WARNING_INT_FROM_POINTER
1053 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1054 const expression_t *const right,
1055 const char *context,
1056 const source_position_t *source_position)
1058 type_t *const orig_type_right = right->base.type;
1059 type_t *const type_left = skip_typeref(orig_type_left);
1060 type_t *const type_right = skip_typeref(orig_type_right);
1063 case ASSIGN_SUCCESS:
1065 case ASSIGN_ERROR_INCOMPATIBLE:
1066 errorf(source_position,
1067 "destination type '%T' in %s is incompatible with type '%T'",
1068 orig_type_left, context, orig_type_right);
1071 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1072 if (warning.other) {
1073 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1074 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1076 /* the left type has all qualifiers from the right type */
1077 unsigned missing_qualifiers
1078 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1079 warningf(source_position,
1080 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1081 orig_type_left, context, orig_type_right, missing_qualifiers);
1086 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1087 if (warning.other) {
1088 warningf(source_position,
1089 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1090 orig_type_left, context, right, orig_type_right);
1094 case ASSIGN_WARNING_POINTER_FROM_INT:
1095 if (warning.other) {
1096 warningf(source_position,
1097 "%s makes pointer '%T' from integer '%T' without a cast",
1098 context, orig_type_left, orig_type_right);
1102 case ASSIGN_WARNING_INT_FROM_POINTER:
1103 if (warning.other) {
1104 warningf(source_position,
1105 "%s makes integer '%T' from pointer '%T' without a cast",
1106 context, orig_type_left, orig_type_right);
1111 panic("invalid error value");
1115 /** Implements the rules from § 6.5.16.1 */
1116 static assign_error_t semantic_assign(type_t *orig_type_left,
1117 const expression_t *const right)
1119 type_t *const orig_type_right = right->base.type;
1120 type_t *const type_left = skip_typeref(orig_type_left);
1121 type_t *const type_right = skip_typeref(orig_type_right);
1123 if (is_type_pointer(type_left)) {
1124 if (is_null_pointer_constant(right)) {
1125 return ASSIGN_SUCCESS;
1126 } else if (is_type_pointer(type_right)) {
1127 type_t *points_to_left
1128 = skip_typeref(type_left->pointer.points_to);
1129 type_t *points_to_right
1130 = skip_typeref(type_right->pointer.points_to);
1131 assign_error_t res = ASSIGN_SUCCESS;
1133 /* the left type has all qualifiers from the right type */
1134 unsigned missing_qualifiers
1135 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1136 if (missing_qualifiers != 0) {
1137 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1140 points_to_left = get_unqualified_type(points_to_left);
1141 points_to_right = get_unqualified_type(points_to_right);
1143 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1146 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1147 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1148 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1151 if (!types_compatible(points_to_left, points_to_right)) {
1152 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1156 } else if (is_type_integer(type_right)) {
1157 return ASSIGN_WARNING_POINTER_FROM_INT;
1159 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1160 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1161 && is_type_pointer(type_right))) {
1162 return ASSIGN_SUCCESS;
1163 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1164 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1165 type_t *const unqual_type_left = get_unqualified_type(type_left);
1166 type_t *const unqual_type_right = get_unqualified_type(type_right);
1167 if (types_compatible(unqual_type_left, unqual_type_right)) {
1168 return ASSIGN_SUCCESS;
1170 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1171 return ASSIGN_WARNING_INT_FROM_POINTER;
1174 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1175 return ASSIGN_SUCCESS;
1177 return ASSIGN_ERROR_INCOMPATIBLE;
1180 static expression_t *parse_constant_expression(void)
1182 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1184 if (!is_constant_expression(result)) {
1185 errorf(&result->base.source_position,
1186 "expression '%E' is not constant\n", result);
1192 static expression_t *parse_assignment_expression(void)
1194 return parse_sub_expression(PREC_ASSIGNMENT);
1197 static type_t *make_global_typedef(const char *name, type_t *type)
1199 symbol_t *const symbol = symbol_table_insert(name);
1201 entity_t *const entity = allocate_entity_zero(ENTITY_TYPEDEF);
1202 entity->base.symbol = symbol;
1203 entity->base.source_position = builtin_source_position;
1204 entity->base.namespc = NAMESPACE_NORMAL;
1205 entity->typedefe.type = type;
1206 entity->typedefe.builtin = true;
1208 record_entity(entity, false);
1210 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF);
1211 typedef_type->typedeft.typedefe = &entity->typedefe;
1213 return typedef_type;
1216 static string_t parse_string_literals(void)
1218 assert(token.type == T_STRING_LITERAL);
1219 string_t result = token.v.string;
1223 while (token.type == T_STRING_LITERAL) {
1224 result = concat_strings(&result, &token.v.string);
1231 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1232 [GNU_AK_CONST] = "const",
1233 [GNU_AK_VOLATILE] = "volatile",
1234 [GNU_AK_CDECL] = "cdecl",
1235 [GNU_AK_STDCALL] = "stdcall",
1236 [GNU_AK_FASTCALL] = "fastcall",
1237 [GNU_AK_DEPRECATED] = "deprecated",
1238 [GNU_AK_NOINLINE] = "noinline",
1239 [GNU_AK_NORETURN] = "noreturn",
1240 [GNU_AK_NAKED] = "naked",
1241 [GNU_AK_PURE] = "pure",
1242 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1243 [GNU_AK_MALLOC] = "malloc",
1244 [GNU_AK_WEAK] = "weak",
1245 [GNU_AK_CONSTRUCTOR] = "constructor",
1246 [GNU_AK_DESTRUCTOR] = "destructor",
1247 [GNU_AK_NOTHROW] = "nothrow",
1248 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1249 [GNU_AK_COMMON] = "common",
1250 [GNU_AK_NOCOMMON] = "nocommon",
1251 [GNU_AK_PACKED] = "packed",
1252 [GNU_AK_SHARED] = "shared",
1253 [GNU_AK_NOTSHARED] = "notshared",
1254 [GNU_AK_USED] = "used",
1255 [GNU_AK_UNUSED] = "unused",
1256 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1257 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1258 [GNU_AK_LONGCALL] = "longcall",
1259 [GNU_AK_SHORTCALL] = "shortcall",
1260 [GNU_AK_LONG_CALL] = "long_call",
1261 [GNU_AK_SHORT_CALL] = "short_call",
1262 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1263 [GNU_AK_INTERRUPT] = "interrupt",
1264 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1265 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1266 [GNU_AK_NESTING] = "nesting",
1267 [GNU_AK_NEAR] = "near",
1268 [GNU_AK_FAR] = "far",
1269 [GNU_AK_SIGNAL] = "signal",
1270 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1271 [GNU_AK_TINY_DATA] = "tiny_data",
1272 [GNU_AK_SAVEALL] = "saveall",
1273 [GNU_AK_FLATTEN] = "flatten",
1274 [GNU_AK_SSEREGPARM] = "sseregparm",
1275 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1276 [GNU_AK_RETURN_TWICE] = "return_twice",
1277 [GNU_AK_MAY_ALIAS] = "may_alias",
1278 [GNU_AK_MS_STRUCT] = "ms_struct",
1279 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1280 [GNU_AK_DLLIMPORT] = "dllimport",
1281 [GNU_AK_DLLEXPORT] = "dllexport",
1282 [GNU_AK_ALIGNED] = "aligned",
1283 [GNU_AK_ALIAS] = "alias",
1284 [GNU_AK_SECTION] = "section",
1285 [GNU_AK_FORMAT] = "format",
1286 [GNU_AK_FORMAT_ARG] = "format_arg",
1287 [GNU_AK_WEAKREF] = "weakref",
1288 [GNU_AK_NONNULL] = "nonnull",
1289 [GNU_AK_TLS_MODEL] = "tls_model",
1290 [GNU_AK_VISIBILITY] = "visibility",
1291 [GNU_AK_REGPARM] = "regparm",
1292 [GNU_AK_MODE] = "mode",
1293 [GNU_AK_MODEL] = "model",
1294 [GNU_AK_TRAP_EXIT] = "trap_exit",
1295 [GNU_AK_SP_SWITCH] = "sp_switch",
1296 [GNU_AK_SENTINEL] = "sentinel"
1300 * compare two string, ignoring double underscores on the second.
1302 static int strcmp_underscore(const char *s1, const char *s2)
1304 if (s2[0] == '_' && s2[1] == '_') {
1305 size_t len2 = strlen(s2);
1306 size_t len1 = strlen(s1);
1307 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1308 return strncmp(s1, s2+2, len2-4);
1312 return strcmp(s1, s2);
1316 * Allocate a new gnu temporal attribute.
1318 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1320 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1321 attribute->kind = kind;
1322 attribute->next = NULL;
1323 attribute->invalid = false;
1324 attribute->have_arguments = false;
1330 * parse one constant expression argument.
1332 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1334 expression_t *expression;
1335 add_anchor_token(')');
1336 expression = parse_constant_expression();
1337 rem_anchor_token(')');
1339 attribute->u.argument = fold_constant(expression);
1342 attribute->invalid = true;
1346 * parse a list of constant expressions arguments.
1348 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1350 argument_list_t **list = &attribute->u.arguments;
1351 argument_list_t *entry;
1352 expression_t *expression;
1353 add_anchor_token(')');
1354 add_anchor_token(',');
1356 expression = parse_constant_expression();
1357 entry = obstack_alloc(&temp_obst, sizeof(entry));
1358 entry->argument = fold_constant(expression);
1361 list = &entry->next;
1362 if (token.type != ',')
1366 rem_anchor_token(',');
1367 rem_anchor_token(')');
1371 attribute->invalid = true;
1375 * parse one string literal argument.
1377 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1380 add_anchor_token('(');
1381 if (token.type != T_STRING_LITERAL) {
1382 parse_error_expected("while parsing attribute directive",
1383 T_STRING_LITERAL, NULL);
1386 *string = parse_string_literals();
1387 rem_anchor_token('(');
1391 attribute->invalid = true;
1395 * parse one tls model.
1397 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1399 static const char *const tls_models[] = {
1405 string_t string = { NULL, 0 };
1406 parse_gnu_attribute_string_arg(attribute, &string);
1407 if (string.begin != NULL) {
1408 for(size_t i = 0; i < 4; ++i) {
1409 if (strcmp(tls_models[i], string.begin) == 0) {
1410 attribute->u.value = i;
1414 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1416 attribute->invalid = true;
1420 * parse one tls model.
1422 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1424 static const char *const visibilities[] = {
1430 string_t string = { NULL, 0 };
1431 parse_gnu_attribute_string_arg(attribute, &string);
1432 if (string.begin != NULL) {
1433 for(size_t i = 0; i < 4; ++i) {
1434 if (strcmp(visibilities[i], string.begin) == 0) {
1435 attribute->u.value = i;
1439 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1441 attribute->invalid = true;
1445 * parse one (code) model.
1447 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1449 static const char *const visibilities[] = {
1454 string_t string = { NULL, 0 };
1455 parse_gnu_attribute_string_arg(attribute, &string);
1456 if (string.begin != NULL) {
1457 for(int i = 0; i < 3; ++i) {
1458 if (strcmp(visibilities[i], string.begin) == 0) {
1459 attribute->u.value = i;
1463 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1465 attribute->invalid = true;
1468 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1470 /* TODO: find out what is allowed here... */
1472 /* at least: byte, word, pointer, list of machine modes
1473 * __XXX___ is interpreted as XXX */
1474 add_anchor_token(')');
1476 if (token.type != T_IDENTIFIER) {
1477 expect(T_IDENTIFIER);
1480 /* This isn't really correct, the backend should provide a list of machine
1481 * specific modes (according to gcc philosophy that is...) */
1482 const char *symbol_str = token.v.symbol->string;
1483 if (strcmp_underscore("QI", symbol_str) == 0 ||
1484 strcmp_underscore("byte", symbol_str) == 0) {
1485 attribute->u.akind = ATOMIC_TYPE_CHAR;
1486 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1487 attribute->u.akind = ATOMIC_TYPE_SHORT;
1488 } else if (strcmp_underscore("SI", symbol_str) == 0
1489 || strcmp_underscore("word", symbol_str) == 0
1490 || strcmp_underscore("pointer", symbol_str) == 0) {
1491 attribute->u.akind = ATOMIC_TYPE_INT;
1492 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1493 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1496 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1497 attribute->invalid = true;
1501 rem_anchor_token(')');
1505 attribute->invalid = true;
1509 * parse one interrupt argument.
1511 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1513 static const char *const interrupts[] = {
1520 string_t string = { NULL, 0 };
1521 parse_gnu_attribute_string_arg(attribute, &string);
1522 if (string.begin != NULL) {
1523 for(size_t i = 0; i < 5; ++i) {
1524 if (strcmp(interrupts[i], string.begin) == 0) {
1525 attribute->u.value = i;
1529 errorf(HERE, "'%s' is not an interrupt", string.begin);
1531 attribute->invalid = true;
1535 * parse ( identifier, const expression, const expression )
1537 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1539 static const char *const format_names[] = {
1547 if (token.type != T_IDENTIFIER) {
1548 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1551 const char *name = token.v.symbol->string;
1552 for(i = 0; i < 4; ++i) {
1553 if (strcmp_underscore(format_names[i], name) == 0)
1557 if (warning.attribute)
1558 warningf(HERE, "'%s' is an unrecognized format function type", name);
1563 add_anchor_token(')');
1564 add_anchor_token(',');
1565 parse_constant_expression();
1566 rem_anchor_token(',');
1567 rem_anchor_token(')');
1570 add_anchor_token(')');
1571 parse_constant_expression();
1572 rem_anchor_token(')');
1576 attribute->u.value = true;
1579 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1581 if (!attribute->have_arguments)
1584 /* should have no arguments */
1585 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1586 eat_until_matching_token('(');
1587 /* we have already consumed '(', so we stop before ')', eat it */
1589 attribute->invalid = true;
1593 * Parse one GNU attribute.
1595 * Note that attribute names can be specified WITH or WITHOUT
1596 * double underscores, ie const or __const__.
1598 * The following attributes are parsed without arguments
1623 * no_instrument_function
1624 * warn_unused_result
1641 * externally_visible
1649 * The following attributes are parsed with arguments
1650 * aligned( const expression )
1651 * alias( string literal )
1652 * section( string literal )
1653 * format( identifier, const expression, const expression )
1654 * format_arg( const expression )
1655 * tls_model( string literal )
1656 * visibility( string literal )
1657 * regparm( const expression )
1658 * model( string leteral )
1659 * trap_exit( const expression )
1660 * sp_switch( string literal )
1662 * The following attributes might have arguments
1663 * weak_ref( string literal )
1664 * non_null( const expression // ',' )
1665 * interrupt( string literal )
1666 * sentinel( constant expression )
1668 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1670 gnu_attribute_t *head = *attributes;
1671 gnu_attribute_t *last = *attributes;
1672 decl_modifiers_t modifiers = 0;
1673 gnu_attribute_t *attribute;
1675 eat(T___attribute__);
1679 if (token.type != ')') {
1680 /* find the end of the list */
1682 while (last->next != NULL)
1686 /* non-empty attribute list */
1689 if (token.type == T_const) {
1691 } else if (token.type == T_volatile) {
1693 } else if (token.type == T_cdecl) {
1694 /* __attribute__((cdecl)), WITH ms mode */
1696 } else if (token.type == T_IDENTIFIER) {
1697 const symbol_t *sym = token.v.symbol;
1700 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1707 for(i = 0; i < GNU_AK_LAST; ++i) {
1708 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1711 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1714 if (kind == GNU_AK_LAST) {
1715 if (warning.attribute)
1716 warningf(HERE, "'%s' attribute directive ignored", name);
1718 /* skip possible arguments */
1719 if (token.type == '(') {
1720 eat_until_matching_token(')');
1723 /* check for arguments */
1724 attribute = allocate_gnu_attribute(kind);
1725 if (token.type == '(') {
1727 if (token.type == ')') {
1728 /* empty args are allowed */
1731 attribute->have_arguments = true;
1735 case GNU_AK_VOLATILE:
1740 case GNU_AK_NOCOMMON:
1742 case GNU_AK_NOTSHARED:
1743 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1744 case GNU_AK_WARN_UNUSED_RESULT:
1745 case GNU_AK_LONGCALL:
1746 case GNU_AK_SHORTCALL:
1747 case GNU_AK_LONG_CALL:
1748 case GNU_AK_SHORT_CALL:
1749 case GNU_AK_FUNCTION_VECTOR:
1750 case GNU_AK_INTERRUPT_HANDLER:
1751 case GNU_AK_NMI_HANDLER:
1752 case GNU_AK_NESTING:
1756 case GNU_AK_EIGTHBIT_DATA:
1757 case GNU_AK_TINY_DATA:
1758 case GNU_AK_SAVEALL:
1759 case GNU_AK_FLATTEN:
1760 case GNU_AK_SSEREGPARM:
1761 case GNU_AK_EXTERNALLY_VISIBLE:
1762 case GNU_AK_RETURN_TWICE:
1763 case GNU_AK_MAY_ALIAS:
1764 case GNU_AK_MS_STRUCT:
1765 case GNU_AK_GCC_STRUCT:
1768 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1769 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1770 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1771 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1772 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1773 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1774 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1775 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1776 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1777 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1778 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1779 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1780 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1781 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1782 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1783 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1784 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1785 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1787 case GNU_AK_ALIGNED:
1788 /* __align__ may be used without an argument */
1789 if (attribute->have_arguments) {
1790 parse_gnu_attribute_const_arg(attribute);
1794 case GNU_AK_FORMAT_ARG:
1795 case GNU_AK_REGPARM:
1796 case GNU_AK_TRAP_EXIT:
1797 if (!attribute->have_arguments) {
1798 /* should have arguments */
1799 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1800 attribute->invalid = true;
1802 parse_gnu_attribute_const_arg(attribute);
1805 case GNU_AK_SECTION:
1806 case GNU_AK_SP_SWITCH:
1807 if (!attribute->have_arguments) {
1808 /* should have arguments */
1809 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1810 attribute->invalid = true;
1812 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1815 if (!attribute->have_arguments) {
1816 /* should have arguments */
1817 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1818 attribute->invalid = true;
1820 parse_gnu_attribute_format_args(attribute);
1822 case GNU_AK_WEAKREF:
1823 /* may have one string argument */
1824 if (attribute->have_arguments)
1825 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1827 case GNU_AK_NONNULL:
1828 if (attribute->have_arguments)
1829 parse_gnu_attribute_const_arg_list(attribute);
1831 case GNU_AK_TLS_MODEL:
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_tls_model_arg(attribute);
1838 case GNU_AK_VISIBILITY:
1839 if (!attribute->have_arguments) {
1840 /* should have arguments */
1841 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1843 parse_gnu_attribute_visibility_arg(attribute);
1846 if (!attribute->have_arguments) {
1847 /* should have arguments */
1848 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1850 parse_gnu_attribute_model_arg(attribute);
1854 if (!attribute->have_arguments) {
1855 /* should have arguments */
1856 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1858 parse_gnu_attribute_mode_arg(attribute);
1861 case GNU_AK_INTERRUPT:
1862 /* may have one string argument */
1863 if (attribute->have_arguments)
1864 parse_gnu_attribute_interrupt_arg(attribute);
1866 case GNU_AK_SENTINEL:
1867 /* may have one string argument */
1868 if (attribute->have_arguments)
1869 parse_gnu_attribute_const_arg(attribute);
1872 /* already handled */
1876 check_no_argument(attribute, name);
1879 if (attribute != NULL) {
1881 last->next = attribute;
1884 head = last = attribute;
1888 if (token.type != ',')
1902 * Parse GNU attributes.
1904 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1906 decl_modifiers_t modifiers = 0;
1909 switch (token.type) {
1910 case T___attribute__:
1911 modifiers |= parse_gnu_attribute(attributes);
1917 if (token.type != T_STRING_LITERAL) {
1918 parse_error_expected("while parsing assembler attribute",
1919 T_STRING_LITERAL, NULL);
1920 eat_until_matching_token('(');
1923 parse_string_literals();
1928 case T_cdecl: modifiers |= DM_CDECL; break;
1929 case T__fastcall: modifiers |= DM_FASTCALL; break;
1930 case T__stdcall: modifiers |= DM_STDCALL; break;
1933 /* TODO record modifier */
1935 warningf(HERE, "Ignoring declaration modifier %K", &token);
1939 default: return modifiers;
1946 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1948 static variable_t *determine_lhs_var(expression_t *const expr,
1949 variable_t *lhs_var)
1951 switch (expr->kind) {
1952 case EXPR_REFERENCE: {
1953 entity_t *const entity = expr->reference.entity;
1954 /* we should only find variables as lavlues... */
1955 if (entity->base.kind != ENTITY_VARIABLE)
1958 return &entity->variable;
1961 case EXPR_ARRAY_ACCESS: {
1962 expression_t *const ref = expr->array_access.array_ref;
1963 variable_t * var = NULL;
1964 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1965 var = determine_lhs_var(ref, lhs_var);
1968 mark_vars_read(expr->select.compound, lhs_var);
1970 mark_vars_read(expr->array_access.index, lhs_var);
1975 if (is_type_compound(skip_typeref(expr->base.type))) {
1976 return determine_lhs_var(expr->select.compound, lhs_var);
1978 mark_vars_read(expr->select.compound, lhs_var);
1983 case EXPR_UNARY_DEREFERENCE: {
1984 expression_t *const val = expr->unary.value;
1985 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1987 return determine_lhs_var(val->unary.value, lhs_var);
1989 mark_vars_read(val, NULL);
1995 mark_vars_read(expr, NULL);
2000 #define VAR_ANY ((variable_t*)-1)
2003 * Mark declarations, which are read. This is used to deted variables, which
2007 * x is not marked as "read", because it is only read to calculate its own new
2011 * x and y are not detected as "not read", because multiple variables are
2014 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
2016 switch (expr->kind) {
2017 case EXPR_REFERENCE: {
2018 entity_t *const entity = expr->reference.entity;
2019 if (entity->kind != ENTITY_VARIABLE)
2022 variable_t *variable = &entity->variable;
2023 if (lhs_var != variable && lhs_var != VAR_ANY) {
2024 variable->read = true;
2030 // TODO respect pure/const
2031 mark_vars_read(expr->call.function, NULL);
2032 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2033 mark_vars_read(arg->expression, NULL);
2037 case EXPR_CONDITIONAL:
2038 // TODO lhs_decl should depend on whether true/false have an effect
2039 mark_vars_read(expr->conditional.condition, NULL);
2040 if (expr->conditional.true_expression != NULL)
2041 mark_vars_read(expr->conditional.true_expression, lhs_var);
2042 mark_vars_read(expr->conditional.false_expression, lhs_var);
2046 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2048 mark_vars_read(expr->select.compound, lhs_var);
2051 case EXPR_ARRAY_ACCESS: {
2052 expression_t *const ref = expr->array_access.array_ref;
2053 mark_vars_read(ref, lhs_var);
2054 lhs_var = determine_lhs_var(ref, lhs_var);
2055 mark_vars_read(expr->array_access.index, lhs_var);
2060 mark_vars_read(expr->va_arge.ap, lhs_var);
2063 case EXPR_UNARY_CAST:
2064 /* Special case: Use void cast to mark a variable as "read" */
2065 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2070 case EXPR_UNARY_THROW:
2071 if (expr->unary.value == NULL)
2074 case EXPR_UNARY_DEREFERENCE:
2075 case EXPR_UNARY_DELETE:
2076 case EXPR_UNARY_DELETE_ARRAY:
2077 if (lhs_var == VAR_ANY)
2081 case EXPR_UNARY_NEGATE:
2082 case EXPR_UNARY_PLUS:
2083 case EXPR_UNARY_BITWISE_NEGATE:
2084 case EXPR_UNARY_NOT:
2085 case EXPR_UNARY_TAKE_ADDRESS:
2086 case EXPR_UNARY_POSTFIX_INCREMENT:
2087 case EXPR_UNARY_POSTFIX_DECREMENT:
2088 case EXPR_UNARY_PREFIX_INCREMENT:
2089 case EXPR_UNARY_PREFIX_DECREMENT:
2090 case EXPR_UNARY_CAST_IMPLICIT:
2091 case EXPR_UNARY_ASSUME:
2093 mark_vars_read(expr->unary.value, lhs_var);
2096 case EXPR_BINARY_ADD:
2097 case EXPR_BINARY_SUB:
2098 case EXPR_BINARY_MUL:
2099 case EXPR_BINARY_DIV:
2100 case EXPR_BINARY_MOD:
2101 case EXPR_BINARY_EQUAL:
2102 case EXPR_BINARY_NOTEQUAL:
2103 case EXPR_BINARY_LESS:
2104 case EXPR_BINARY_LESSEQUAL:
2105 case EXPR_BINARY_GREATER:
2106 case EXPR_BINARY_GREATEREQUAL:
2107 case EXPR_BINARY_BITWISE_AND:
2108 case EXPR_BINARY_BITWISE_OR:
2109 case EXPR_BINARY_BITWISE_XOR:
2110 case EXPR_BINARY_LOGICAL_AND:
2111 case EXPR_BINARY_LOGICAL_OR:
2112 case EXPR_BINARY_SHIFTLEFT:
2113 case EXPR_BINARY_SHIFTRIGHT:
2114 case EXPR_BINARY_COMMA:
2115 case EXPR_BINARY_ISGREATER:
2116 case EXPR_BINARY_ISGREATEREQUAL:
2117 case EXPR_BINARY_ISLESS:
2118 case EXPR_BINARY_ISLESSEQUAL:
2119 case EXPR_BINARY_ISLESSGREATER:
2120 case EXPR_BINARY_ISUNORDERED:
2121 mark_vars_read(expr->binary.left, lhs_var);
2122 mark_vars_read(expr->binary.right, lhs_var);
2125 case EXPR_BINARY_ASSIGN:
2126 case EXPR_BINARY_MUL_ASSIGN:
2127 case EXPR_BINARY_DIV_ASSIGN:
2128 case EXPR_BINARY_MOD_ASSIGN:
2129 case EXPR_BINARY_ADD_ASSIGN:
2130 case EXPR_BINARY_SUB_ASSIGN:
2131 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2132 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2133 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2134 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2135 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2136 if (lhs_var == VAR_ANY)
2138 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2139 mark_vars_read(expr->binary.right, lhs_var);
2144 determine_lhs_var(expr->va_starte.ap, lhs_var);
2150 case EXPR_CHARACTER_CONSTANT:
2151 case EXPR_WIDE_CHARACTER_CONSTANT:
2152 case EXPR_STRING_LITERAL:
2153 case EXPR_WIDE_STRING_LITERAL:
2154 case EXPR_COMPOUND_LITERAL: // TODO init?
2156 case EXPR_CLASSIFY_TYPE:
2159 case EXPR_BUILTIN_SYMBOL:
2160 case EXPR_BUILTIN_CONSTANT_P:
2161 case EXPR_BUILTIN_PREFETCH:
2163 case EXPR_STATEMENT: // TODO
2164 case EXPR_LABEL_ADDRESS:
2165 case EXPR_BINARY_BUILTIN_EXPECT:
2166 case EXPR_REFERENCE_ENUM_VALUE:
2170 panic("unhandled expression");
2173 static designator_t *parse_designation(void)
2175 designator_t *result = NULL;
2176 designator_t *last = NULL;
2179 designator_t *designator;
2180 switch (token.type) {
2182 designator = allocate_ast_zero(sizeof(designator[0]));
2183 designator->source_position = token.source_position;
2185 add_anchor_token(']');
2186 designator->array_index = parse_constant_expression();
2187 rem_anchor_token(']');
2191 designator = allocate_ast_zero(sizeof(designator[0]));
2192 designator->source_position = token.source_position;
2194 if (token.type != T_IDENTIFIER) {
2195 parse_error_expected("while parsing designator",
2196 T_IDENTIFIER, NULL);
2199 designator->symbol = token.v.symbol;
2207 assert(designator != NULL);
2209 last->next = designator;
2211 result = designator;
2219 static initializer_t *initializer_from_string(array_type_t *type,
2220 const string_t *const string)
2222 /* TODO: check len vs. size of array type */
2225 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2226 initializer->string.string = *string;
2231 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2232 wide_string_t *const string)
2234 /* TODO: check len vs. size of array type */
2237 initializer_t *const initializer =
2238 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2239 initializer->wide_string.string = *string;
2245 * Build an initializer from a given expression.
2247 static initializer_t *initializer_from_expression(type_t *orig_type,
2248 expression_t *expression)
2250 /* TODO check that expression is a constant expression */
2252 /* § 6.7.8.14/15 char array may be initialized by string literals */
2253 type_t *type = skip_typeref(orig_type);
2254 type_t *expr_type_orig = expression->base.type;
2255 type_t *expr_type = skip_typeref(expr_type_orig);
2256 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2257 array_type_t *const array_type = &type->array;
2258 type_t *const element_type = skip_typeref(array_type->element_type);
2260 if (element_type->kind == TYPE_ATOMIC) {
2261 atomic_type_kind_t akind = element_type->atomic.akind;
2262 switch (expression->kind) {
2263 case EXPR_STRING_LITERAL:
2264 if (akind == ATOMIC_TYPE_CHAR
2265 || akind == ATOMIC_TYPE_SCHAR
2266 || akind == ATOMIC_TYPE_UCHAR) {
2267 return initializer_from_string(array_type,
2268 &expression->string.value);
2271 case EXPR_WIDE_STRING_LITERAL: {
2272 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2273 if (get_unqualified_type(element_type) == bare_wchar_type) {
2274 return initializer_from_wide_string(array_type,
2275 &expression->wide_string.value);
2285 assign_error_t error = semantic_assign(type, expression);
2286 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2288 report_assign_error(error, type, expression, "initializer",
2289 &expression->base.source_position);
2291 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2293 if (type->kind == TYPE_BITFIELD) {
2294 type = type->bitfield.base_type;
2297 result->value.value = create_implicit_cast(expression, type);
2303 * Checks if a given expression can be used as an constant initializer.
2305 static bool is_initializer_constant(const expression_t *expression)
2307 return is_constant_expression(expression)
2308 || is_address_constant(expression);
2312 * Parses an scalar initializer.
2314 * § 6.7.8.11; eat {} without warning
2316 static initializer_t *parse_scalar_initializer(type_t *type,
2317 bool must_be_constant)
2319 /* there might be extra {} hierarchies */
2321 if (token.type == '{') {
2323 warningf(HERE, "extra curly braces around scalar initializer");
2327 } while (token.type == '{');
2330 expression_t *expression = parse_assignment_expression();
2331 mark_vars_read(expression, NULL);
2332 if (must_be_constant && !is_initializer_constant(expression)) {
2333 errorf(&expression->base.source_position,
2334 "Initialisation expression '%E' is not constant\n",
2338 initializer_t *initializer = initializer_from_expression(type, expression);
2340 if (initializer == NULL) {
2341 errorf(&expression->base.source_position,
2342 "expression '%E' (type '%T') doesn't match expected type '%T'",
2343 expression, expression->base.type, type);
2348 bool additional_warning_displayed = false;
2349 while (braces > 0) {
2350 if (token.type == ',') {
2353 if (token.type != '}') {
2354 if (!additional_warning_displayed && warning.other) {
2355 warningf(HERE, "additional elements in scalar initializer");
2356 additional_warning_displayed = true;
2367 * An entry in the type path.
2369 typedef struct type_path_entry_t type_path_entry_t;
2370 struct type_path_entry_t {
2371 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2373 size_t index; /**< For array types: the current index. */
2374 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2379 * A type path expression a position inside compound or array types.
2381 typedef struct type_path_t type_path_t;
2382 struct type_path_t {
2383 type_path_entry_t *path; /**< An flexible array containing the current path. */
2384 type_t *top_type; /**< type of the element the path points */
2385 size_t max_index; /**< largest index in outermost array */
2389 * Prints a type path for debugging.
2391 static __attribute__((unused)) void debug_print_type_path(
2392 const type_path_t *path)
2394 size_t len = ARR_LEN(path->path);
2396 for(size_t i = 0; i < len; ++i) {
2397 const type_path_entry_t *entry = & path->path[i];
2399 type_t *type = skip_typeref(entry->type);
2400 if (is_type_compound(type)) {
2401 /* in gcc mode structs can have no members */
2402 if (entry->v.compound_entry == NULL) {
2406 fprintf(stderr, ".%s",
2407 entry->v.compound_entry->base.symbol->string);
2408 } else if (is_type_array(type)) {
2409 fprintf(stderr, "[%zu]", entry->v.index);
2411 fprintf(stderr, "-INVALID-");
2414 if (path->top_type != NULL) {
2415 fprintf(stderr, " (");
2416 print_type(path->top_type);
2417 fprintf(stderr, ")");
2422 * Return the top type path entry, ie. in a path
2423 * (type).a.b returns the b.
2425 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2427 size_t len = ARR_LEN(path->path);
2429 return &path->path[len-1];
2433 * Enlarge the type path by an (empty) element.
2435 static type_path_entry_t *append_to_type_path(type_path_t *path)
2437 size_t len = ARR_LEN(path->path);
2438 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2440 type_path_entry_t *result = & path->path[len];
2441 memset(result, 0, sizeof(result[0]));
2446 * Descending into a sub-type. Enter the scope of the current top_type.
2448 static void descend_into_subtype(type_path_t *path)
2450 type_t *orig_top_type = path->top_type;
2451 type_t *top_type = skip_typeref(orig_top_type);
2453 type_path_entry_t *top = append_to_type_path(path);
2454 top->type = top_type;
2456 if (is_type_compound(top_type)) {
2457 compound_t *compound = top_type->compound.compound;
2458 entity_t *entry = compound->members.entities;
2460 if (entry != NULL) {
2461 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2462 top->v.compound_entry = &entry->declaration;
2463 path->top_type = entry->declaration.type;
2465 path->top_type = NULL;
2467 } else if (is_type_array(top_type)) {
2469 path->top_type = top_type->array.element_type;
2471 assert(!is_type_valid(top_type));
2476 * Pop an entry from the given type path, ie. returning from
2477 * (type).a.b to (type).a
2479 static void ascend_from_subtype(type_path_t *path)
2481 type_path_entry_t *top = get_type_path_top(path);
2483 path->top_type = top->type;
2485 size_t len = ARR_LEN(path->path);
2486 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2490 * Pop entries from the given type path until the given
2491 * path level is reached.
2493 static void ascend_to(type_path_t *path, size_t top_path_level)
2495 size_t len = ARR_LEN(path->path);
2497 while (len > top_path_level) {
2498 ascend_from_subtype(path);
2499 len = ARR_LEN(path->path);
2503 static bool walk_designator(type_path_t *path, const designator_t *designator,
2504 bool used_in_offsetof)
2506 for( ; designator != NULL; designator = designator->next) {
2507 type_path_entry_t *top = get_type_path_top(path);
2508 type_t *orig_type = top->type;
2510 type_t *type = skip_typeref(orig_type);
2512 if (designator->symbol != NULL) {
2513 symbol_t *symbol = designator->symbol;
2514 if (!is_type_compound(type)) {
2515 if (is_type_valid(type)) {
2516 errorf(&designator->source_position,
2517 "'.%Y' designator used for non-compound type '%T'",
2521 top->type = type_error_type;
2522 top->v.compound_entry = NULL;
2523 orig_type = type_error_type;
2525 compound_t *compound = type->compound.compound;
2526 entity_t *iter = compound->members.entities;
2527 for( ; iter != NULL; iter = iter->base.next) {
2528 if (iter->base.symbol == symbol) {
2533 errorf(&designator->source_position,
2534 "'%T' has no member named '%Y'", orig_type, symbol);
2537 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2538 if (used_in_offsetof) {
2539 type_t *real_type = skip_typeref(iter->declaration.type);
2540 if (real_type->kind == TYPE_BITFIELD) {
2541 errorf(&designator->source_position,
2542 "offsetof designator '%Y' may not specify bitfield",
2548 top->type = orig_type;
2549 top->v.compound_entry = &iter->declaration;
2550 orig_type = iter->declaration.type;
2553 expression_t *array_index = designator->array_index;
2554 assert(designator->array_index != NULL);
2556 if (!is_type_array(type)) {
2557 if (is_type_valid(type)) {
2558 errorf(&designator->source_position,
2559 "[%E] designator used for non-array type '%T'",
2560 array_index, orig_type);
2565 long index = fold_constant(array_index);
2566 if (!used_in_offsetof) {
2568 errorf(&designator->source_position,
2569 "array index [%E] must be positive", array_index);
2570 } else if (type->array.size_constant) {
2571 long array_size = type->array.size;
2572 if (index >= array_size) {
2573 errorf(&designator->source_position,
2574 "designator [%E] (%d) exceeds array size %d",
2575 array_index, index, array_size);
2580 top->type = orig_type;
2581 top->v.index = (size_t) index;
2582 orig_type = type->array.element_type;
2584 path->top_type = orig_type;
2586 if (designator->next != NULL) {
2587 descend_into_subtype(path);
2596 static void advance_current_object(type_path_t *path, size_t top_path_level)
2598 type_path_entry_t *top = get_type_path_top(path);
2600 type_t *type = skip_typeref(top->type);
2601 if (is_type_union(type)) {
2602 /* in unions only the first element is initialized */
2603 top->v.compound_entry = NULL;
2604 } else if (is_type_struct(type)) {
2605 declaration_t *entry = top->v.compound_entry;
2607 entity_t *next_entity = entry->base.next;
2608 if (next_entity != NULL) {
2609 assert(is_declaration(next_entity));
2610 entry = &next_entity->declaration;
2615 top->v.compound_entry = entry;
2616 if (entry != NULL) {
2617 path->top_type = entry->type;
2620 } else if (is_type_array(type)) {
2621 assert(is_type_array(type));
2625 if (!type->array.size_constant || top->v.index < type->array.size) {
2629 assert(!is_type_valid(type));
2633 /* we're past the last member of the current sub-aggregate, try if we
2634 * can ascend in the type hierarchy and continue with another subobject */
2635 size_t len = ARR_LEN(path->path);
2637 if (len > top_path_level) {
2638 ascend_from_subtype(path);
2639 advance_current_object(path, top_path_level);
2641 path->top_type = NULL;
2646 * skip until token is found.
2648 static void skip_until(int type)
2650 while (token.type != type) {
2651 if (token.type == T_EOF)
2658 * skip any {...} blocks until a closing bracket is reached.
2660 static void skip_initializers(void)
2662 if (token.type == '{')
2665 while (token.type != '}') {
2666 if (token.type == T_EOF)
2668 if (token.type == '{') {
2676 static initializer_t *create_empty_initializer(void)
2678 static initializer_t empty_initializer
2679 = { .list = { { INITIALIZER_LIST }, 0 } };
2680 return &empty_initializer;
2684 * Parse a part of an initialiser for a struct or union,
2686 static initializer_t *parse_sub_initializer(type_path_t *path,
2687 type_t *outer_type, size_t top_path_level,
2688 parse_initializer_env_t *env)
2690 if (token.type == '}') {
2691 /* empty initializer */
2692 return create_empty_initializer();
2695 type_t *orig_type = path->top_type;
2696 type_t *type = NULL;
2698 if (orig_type == NULL) {
2699 /* We are initializing an empty compound. */
2701 type = skip_typeref(orig_type);
2704 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2707 designator_t *designator = NULL;
2708 if (token.type == '.' || token.type == '[') {
2709 designator = parse_designation();
2710 goto finish_designator;
2711 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2712 /* GNU-style designator ("identifier: value") */
2713 designator = allocate_ast_zero(sizeof(designator[0]));
2714 designator->source_position = token.source_position;
2715 designator->symbol = token.v.symbol;
2720 /* reset path to toplevel, evaluate designator from there */
2721 ascend_to(path, top_path_level);
2722 if (!walk_designator(path, designator, false)) {
2723 /* can't continue after designation error */
2727 initializer_t *designator_initializer
2728 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2729 designator_initializer->designator.designator = designator;
2730 ARR_APP1(initializer_t*, initializers, designator_initializer);
2732 orig_type = path->top_type;
2733 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2738 if (token.type == '{') {
2739 if (type != NULL && is_type_scalar(type)) {
2740 sub = parse_scalar_initializer(type, env->must_be_constant);
2744 if (env->entity != NULL) {
2746 "extra brace group at end of initializer for '%Y'",
2747 env->entity->base.symbol);
2749 errorf(HERE, "extra brace group at end of initializer");
2752 descend_into_subtype(path);
2754 add_anchor_token('}');
2755 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2757 rem_anchor_token('}');
2760 ascend_from_subtype(path);
2764 goto error_parse_next;
2768 /* must be an expression */
2769 expression_t *expression = parse_assignment_expression();
2771 if (env->must_be_constant && !is_initializer_constant(expression)) {
2772 errorf(&expression->base.source_position,
2773 "Initialisation expression '%E' is not constant\n",
2778 /* we are already outside, ... */
2779 type_t *const outer_type_skip = skip_typeref(outer_type);
2780 if (is_type_compound(outer_type_skip) &&
2781 !outer_type_skip->compound.compound->complete) {
2782 goto error_parse_next;
2787 /* handle { "string" } special case */
2788 if ((expression->kind == EXPR_STRING_LITERAL
2789 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2790 && outer_type != NULL) {
2791 sub = initializer_from_expression(outer_type, expression);
2793 if (token.type == ',') {
2796 if (token.type != '}' && warning.other) {
2797 warningf(HERE, "excessive elements in initializer for type '%T'",
2800 /* TODO: eat , ... */
2805 /* descend into subtypes until expression matches type */
2807 orig_type = path->top_type;
2808 type = skip_typeref(orig_type);
2810 sub = initializer_from_expression(orig_type, expression);
2814 if (!is_type_valid(type)) {
2817 if (is_type_scalar(type)) {
2818 errorf(&expression->base.source_position,
2819 "expression '%E' doesn't match expected type '%T'",
2820 expression, orig_type);
2824 descend_into_subtype(path);
2828 /* update largest index of top array */
2829 const type_path_entry_t *first = &path->path[0];
2830 type_t *first_type = first->type;
2831 first_type = skip_typeref(first_type);
2832 if (is_type_array(first_type)) {
2833 size_t index = first->v.index;
2834 if (index > path->max_index)
2835 path->max_index = index;
2839 /* append to initializers list */
2840 ARR_APP1(initializer_t*, initializers, sub);
2843 if (warning.other) {
2844 if (env->entity != NULL) {
2845 warningf(HERE, "excess elements in struct initializer for '%Y'",
2846 env->entity->base.symbol);
2848 warningf(HERE, "excess elements in struct initializer");
2854 if (token.type == '}') {
2858 if (token.type == '}') {
2863 /* advance to the next declaration if we are not at the end */
2864 advance_current_object(path, top_path_level);
2865 orig_type = path->top_type;
2866 if (orig_type != NULL)
2867 type = skip_typeref(orig_type);
2873 size_t len = ARR_LEN(initializers);
2874 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2875 initializer_t *result = allocate_ast_zero(size);
2876 result->kind = INITIALIZER_LIST;
2877 result->list.len = len;
2878 memcpy(&result->list.initializers, initializers,
2879 len * sizeof(initializers[0]));
2881 DEL_ARR_F(initializers);
2882 ascend_to(path, top_path_level+1);
2887 skip_initializers();
2888 DEL_ARR_F(initializers);
2889 ascend_to(path, top_path_level+1);
2894 * Parses an initializer. Parsers either a compound literal
2895 * (env->declaration == NULL) or an initializer of a declaration.
2897 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2899 type_t *type = skip_typeref(env->type);
2900 initializer_t *result = NULL;
2903 if (is_type_scalar(type)) {
2904 result = parse_scalar_initializer(type, env->must_be_constant);
2905 } else if (token.type == '{') {
2909 memset(&path, 0, sizeof(path));
2910 path.top_type = env->type;
2911 path.path = NEW_ARR_F(type_path_entry_t, 0);
2913 descend_into_subtype(&path);
2915 add_anchor_token('}');
2916 result = parse_sub_initializer(&path, env->type, 1, env);
2917 rem_anchor_token('}');
2919 max_index = path.max_index;
2920 DEL_ARR_F(path.path);
2924 /* parse_scalar_initializer() also works in this case: we simply
2925 * have an expression without {} around it */
2926 result = parse_scalar_initializer(type, env->must_be_constant);
2929 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2930 * the array type size */
2931 if (is_type_array(type) && type->array.size_expression == NULL
2932 && result != NULL) {
2934 switch (result->kind) {
2935 case INITIALIZER_LIST:
2936 size = max_index + 1;
2939 case INITIALIZER_STRING:
2940 size = result->string.string.size;
2943 case INITIALIZER_WIDE_STRING:
2944 size = result->wide_string.string.size;
2947 case INITIALIZER_DESIGNATOR:
2948 case INITIALIZER_VALUE:
2949 /* can happen for parse errors */
2954 internal_errorf(HERE, "invalid initializer type");
2957 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2958 cnst->base.type = type_size_t;
2959 cnst->conste.v.int_value = size;
2961 type_t *new_type = duplicate_type(type);
2963 new_type->array.size_expression = cnst;
2964 new_type->array.size_constant = true;
2965 new_type->array.has_implicit_size = true;
2966 new_type->array.size = size;
2967 env->type = new_type;
2975 static void append_entity(scope_t *scope, entity_t *entity)
2977 if (scope->last_entity != NULL) {
2978 scope->last_entity->base.next = entity;
2980 scope->entities = entity;
2982 scope->last_entity = entity;
2986 static compound_t *parse_compound_type_specifier(bool is_struct)
2988 gnu_attribute_t *attributes = NULL;
2989 decl_modifiers_t modifiers = 0;
2996 symbol_t *symbol = NULL;
2997 compound_t *compound = NULL;
2999 if (token.type == T___attribute__) {
3000 modifiers |= parse_attributes(&attributes);
3003 if (token.type == T_IDENTIFIER) {
3004 symbol = token.v.symbol;
3007 namespace_t const namespc =
3008 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3009 entity_t *entity = get_entity(symbol, namespc);
3010 if (entity != NULL) {
3011 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3012 compound = &entity->compound;
3013 if (compound->base.parent_scope != scope &&
3014 (token.type == '{' || token.type == ';')) {
3015 /* we're in an inner scope and have a definition. Override
3016 existing definition in outer scope */
3018 } else if (compound->complete && token.type == '{') {
3019 assert(symbol != NULL);
3020 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3021 is_struct ? "struct" : "union", symbol,
3022 &compound->base.source_position);
3023 /* clear members in the hope to avoid further errors */
3024 compound->members.entities = NULL;
3027 } else if (token.type != '{') {
3029 parse_error_expected("while parsing struct type specifier",
3030 T_IDENTIFIER, '{', NULL);
3032 parse_error_expected("while parsing union type specifier",
3033 T_IDENTIFIER, '{', NULL);
3039 if (compound == NULL) {
3040 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3041 entity_t *entity = allocate_entity_zero(kind);
3042 compound = &entity->compound;
3044 compound->base.namespc =
3045 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3046 compound->base.source_position = token.source_position;
3047 compound->base.symbol = symbol;
3048 compound->base.parent_scope = scope;
3049 if (symbol != NULL) {
3050 environment_push(entity);
3052 append_entity(scope, entity);
3055 if (token.type == '{') {
3056 compound->complete = true;
3058 parse_compound_type_entries(compound);
3059 modifiers |= parse_attributes(&attributes);
3062 compound->modifiers |= modifiers;
3066 static void parse_enum_entries(type_t *const enum_type)
3070 if (token.type == '}') {
3072 errorf(HERE, "empty enum not allowed");
3076 add_anchor_token('}');
3078 if (token.type != T_IDENTIFIER) {
3079 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3081 rem_anchor_token('}');
3085 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3086 entity->enum_value.enum_type = enum_type;
3087 entity->base.symbol = token.v.symbol;
3088 entity->base.source_position = token.source_position;
3091 if (token.type == '=') {
3093 expression_t *value = parse_constant_expression();
3095 value = create_implicit_cast(value, enum_type);
3096 entity->enum_value.value = value;
3101 record_entity(entity, false);
3103 if (token.type != ',')
3106 } while (token.type != '}');
3107 rem_anchor_token('}');
3115 static type_t *parse_enum_specifier(void)
3117 gnu_attribute_t *attributes = NULL;
3122 if (token.type == T_IDENTIFIER) {
3123 symbol = token.v.symbol;
3126 entity = get_entity(symbol, NAMESPACE_ENUM);
3127 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3128 } else if (token.type != '{') {
3129 parse_error_expected("while parsing enum type specifier",
3130 T_IDENTIFIER, '{', NULL);
3137 if (entity == NULL) {
3138 entity = allocate_entity_zero(ENTITY_ENUM);
3139 entity->base.namespc = NAMESPACE_ENUM;
3140 entity->base.source_position = token.source_position;
3141 entity->base.symbol = symbol;
3142 entity->base.parent_scope = scope;
3145 type_t *const type = allocate_type_zero(TYPE_ENUM);
3146 type->enumt.enume = &entity->enume;
3148 if (token.type == '{') {
3149 if (entity->enume.complete) {
3150 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3151 symbol, &entity->base.source_position);
3153 if (symbol != NULL) {
3154 environment_push(entity);
3156 append_entity(scope, entity);
3157 entity->enume.complete = true;
3159 parse_enum_entries(type);
3160 parse_attributes(&attributes);
3161 } else if(!entity->enume.complete && !(c_mode & _GNUC)) {
3162 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3170 * if a symbol is a typedef to another type, return true
3172 static bool is_typedef_symbol(symbol_t *symbol)
3174 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3175 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3178 static type_t *parse_typeof(void)
3185 add_anchor_token(')');
3187 expression_t *expression = NULL;
3189 bool old_type_prop = in_type_prop;
3190 bool old_gcc_extension = in_gcc_extension;
3191 in_type_prop = true;
3193 while (token.type == T___extension__) {
3194 /* This can be a prefix to a typename or an expression. */
3196 in_gcc_extension = true;
3198 switch (token.type) {
3200 if (is_typedef_symbol(token.v.symbol)) {
3201 type = parse_typename();
3203 expression = parse_expression();
3204 type = expression->base.type;
3209 type = parse_typename();
3213 expression = parse_expression();
3214 type = expression->base.type;
3217 in_type_prop = old_type_prop;
3218 in_gcc_extension = old_gcc_extension;
3220 rem_anchor_token(')');
3223 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3224 typeof_type->typeoft.expression = expression;
3225 typeof_type->typeoft.typeof_type = type;
3232 typedef enum specifiers_t {
3233 SPECIFIER_SIGNED = 1 << 0,
3234 SPECIFIER_UNSIGNED = 1 << 1,
3235 SPECIFIER_LONG = 1 << 2,
3236 SPECIFIER_INT = 1 << 3,
3237 SPECIFIER_DOUBLE = 1 << 4,
3238 SPECIFIER_CHAR = 1 << 5,
3239 SPECIFIER_SHORT = 1 << 6,
3240 SPECIFIER_LONG_LONG = 1 << 7,
3241 SPECIFIER_FLOAT = 1 << 8,
3242 SPECIFIER_BOOL = 1 << 9,
3243 SPECIFIER_VOID = 1 << 10,
3244 SPECIFIER_INT8 = 1 << 11,
3245 SPECIFIER_INT16 = 1 << 12,
3246 SPECIFIER_INT32 = 1 << 13,
3247 SPECIFIER_INT64 = 1 << 14,
3248 SPECIFIER_INT128 = 1 << 15,
3249 SPECIFIER_COMPLEX = 1 << 16,
3250 SPECIFIER_IMAGINARY = 1 << 17,
3253 static type_t *create_builtin_type(symbol_t *const symbol,
3254 type_t *const real_type)
3256 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3257 type->builtin.symbol = symbol;
3258 type->builtin.real_type = real_type;
3260 type_t *result = typehash_insert(type);
3261 if (type != result) {
3268 static type_t *get_typedef_type(symbol_t *symbol)
3270 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3271 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3274 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3275 type->typedeft.typedefe = &entity->typedefe;
3281 * check for the allowed MS alignment values.
3283 static bool check_alignment_value(long long intvalue)
3285 if (intvalue < 1 || intvalue > 8192) {
3286 errorf(HERE, "illegal alignment value");
3289 unsigned v = (unsigned)intvalue;
3290 for (unsigned i = 1; i <= 8192; i += i) {
3294 errorf(HERE, "alignment must be power of two");
3298 #define DET_MOD(name, tag) do { \
3299 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3300 *modifiers |= tag; \
3303 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3305 decl_modifiers_t *modifiers = &specifiers->modifiers;
3308 if (token.type == T_restrict) {
3310 DET_MOD(restrict, DM_RESTRICT);
3312 } else if (token.type != T_IDENTIFIER)
3314 symbol_t *symbol = token.v.symbol;
3315 if (symbol == sym_align) {
3318 if (token.type != T_INTEGER)
3320 if (check_alignment_value(token.v.intvalue)) {
3321 if (specifiers->alignment != 0 && warning.other)
3322 warningf(HERE, "align used more than once");
3323 specifiers->alignment = (unsigned char)token.v.intvalue;
3327 } else if (symbol == sym_allocate) {
3330 if (token.type != T_IDENTIFIER)
3332 (void)token.v.symbol;
3334 } else if (symbol == sym_dllimport) {
3336 DET_MOD(dllimport, DM_DLLIMPORT);
3337 } else if (symbol == sym_dllexport) {
3339 DET_MOD(dllexport, DM_DLLEXPORT);
3340 } else if (symbol == sym_thread) {
3342 DET_MOD(thread, DM_THREAD);
3343 } else if (symbol == sym_naked) {
3345 DET_MOD(naked, DM_NAKED);
3346 } else if (symbol == sym_noinline) {
3348 DET_MOD(noinline, DM_NOINLINE);
3349 } else if (symbol == sym_noreturn) {
3351 DET_MOD(noreturn, DM_NORETURN);
3352 } else if (symbol == sym_nothrow) {
3354 DET_MOD(nothrow, DM_NOTHROW);
3355 } else if (symbol == sym_novtable) {
3357 DET_MOD(novtable, DM_NOVTABLE);
3358 } else if (symbol == sym_property) {
3362 bool is_get = false;
3363 if (token.type != T_IDENTIFIER)
3365 if (token.v.symbol == sym_get) {
3367 } else if (token.v.symbol == sym_put) {
3369 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3374 if (token.type != T_IDENTIFIER)
3377 if (specifiers->get_property_sym != NULL) {
3378 errorf(HERE, "get property name already specified");
3380 specifiers->get_property_sym = token.v.symbol;
3383 if (specifiers->put_property_sym != NULL) {
3384 errorf(HERE, "put property name already specified");
3386 specifiers->put_property_sym = token.v.symbol;
3390 if (token.type == ',') {
3397 } else if (symbol == sym_selectany) {
3399 DET_MOD(selectany, DM_SELECTANY);
3400 } else if (symbol == sym_uuid) {
3403 if (token.type != T_STRING_LITERAL)
3407 } else if (symbol == sym_deprecated) {
3409 if (specifiers->deprecated != 0 && warning.other)
3410 warningf(HERE, "deprecated used more than once");
3411 specifiers->deprecated = true;
3412 if (token.type == '(') {
3414 if (token.type == T_STRING_LITERAL) {
3415 specifiers->deprecated_string = token.v.string.begin;
3418 errorf(HERE, "string literal expected");
3422 } else if (symbol == sym_noalias) {
3424 DET_MOD(noalias, DM_NOALIAS);
3427 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3429 if (token.type == '(')
3433 if (token.type == ',')
3440 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3442 entity_t *entity = allocate_entity_zero(kind);
3443 entity->base.source_position = *HERE;
3444 entity->base.symbol = symbol;
3445 if (is_declaration(entity)) {
3446 entity->declaration.implicit = true;
3448 record_entity(entity, false);
3453 * Finish the construction of a struct type by calculating
3454 * its size, offsets, alignment.
3456 static void finish_struct_type(compound_type_t *type)
3458 assert(type->compound != NULL);
3460 compound_t *compound = type->compound;
3461 if (!compound->complete)
3466 il_alignment_t alignment = 1;
3467 bool need_pad = false;
3469 entity_t *entry = compound->members.entities;
3470 for (; entry != NULL; entry = entry->base.next) {
3471 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3474 type_t *m_type = skip_typeref(entry->declaration.type);
3475 if (! is_type_valid(m_type)) {
3476 /* simply ignore errors here */
3479 il_alignment_t m_alignment = m_type->base.alignment;
3480 if (m_alignment > alignment)
3481 alignment = m_alignment;
3483 offset = (size + m_alignment - 1) & -m_alignment;
3487 entry->compound_member.offset = offset;
3488 size = offset + m_type->base.size;
3490 if (type->base.alignment != 0) {
3491 alignment = type->base.alignment;
3494 offset = (size + alignment - 1) & -alignment;
3498 if (warning.padded && need_pad) {
3499 warningf(&compound->base.source_position,
3500 "'%#T' needs padding", type, compound->base.symbol);
3502 if (warning.packed && !need_pad) {
3503 warningf(&compound->base.source_position,
3504 "superfluous packed attribute on '%#T'",
3505 type, compound->base.symbol);
3508 type->base.size = offset;
3509 type->base.alignment = alignment;
3513 * Finish the construction of an union type by calculating
3514 * its size and alignment.
3516 static void finish_union_type(compound_type_t *type)
3518 assert(type->compound != NULL);
3520 compound_t *compound = type->compound;
3521 if (! compound->complete)
3525 il_alignment_t alignment = 1;
3527 entity_t *entry = compound->members.entities;
3528 for (; entry != NULL; entry = entry->base.next) {
3529 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3532 type_t *m_type = skip_typeref(entry->declaration.type);
3533 if (! is_type_valid(m_type))
3536 entry->compound_member.offset = 0;
3537 if (m_type->base.size > size)
3538 size = m_type->base.size;
3539 if (m_type->base.alignment > alignment)
3540 alignment = m_type->base.alignment;
3542 if (type->base.alignment != 0) {
3543 alignment = type->base.alignment;
3545 size = (size + alignment - 1) & -alignment;
3546 type->base.size = size;
3547 type->base.alignment = alignment;
3550 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3552 type_t *type = NULL;
3553 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3554 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3555 unsigned type_specifiers = 0;
3556 bool newtype = false;
3557 bool saw_error = false;
3558 bool old_gcc_extension = in_gcc_extension;
3560 specifiers->source_position = token.source_position;
3563 specifiers->modifiers
3564 |= parse_attributes(&specifiers->gnu_attributes);
3565 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3566 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3568 switch (token.type) {
3571 #define MATCH_STORAGE_CLASS(token, class) \
3573 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3574 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3576 specifiers->storage_class = class; \
3580 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3581 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3582 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3583 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3584 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3589 add_anchor_token(')');
3590 parse_microsoft_extended_decl_modifier(specifiers);
3591 rem_anchor_token(')');
3596 switch (specifiers->storage_class) {
3597 case STORAGE_CLASS_NONE:
3598 specifiers->storage_class = STORAGE_CLASS_THREAD;
3601 case STORAGE_CLASS_EXTERN:
3602 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3605 case STORAGE_CLASS_STATIC:
3606 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3610 errorf(HERE, "multiple storage classes in declaration specifiers");
3616 /* type qualifiers */
3617 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3619 qualifiers |= qualifier; \
3623 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3624 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3625 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3626 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3627 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3628 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3629 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3630 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3632 case T___extension__:
3634 in_gcc_extension = true;
3637 /* type specifiers */
3638 #define MATCH_SPECIFIER(token, specifier, name) \
3641 if (type_specifiers & specifier) { \
3642 errorf(HERE, "multiple " name " type specifiers given"); \
3644 type_specifiers |= specifier; \
3648 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3649 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3650 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3651 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3652 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3653 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3654 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3655 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3656 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3657 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3658 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3659 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3660 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3661 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3662 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3663 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3665 case T__forceinline:
3666 /* only in microsoft mode */
3667 specifiers->modifiers |= DM_FORCEINLINE;
3672 specifiers->is_inline = true;
3677 if (type_specifiers & SPECIFIER_LONG_LONG) {
3678 errorf(HERE, "multiple type specifiers given");
3679 } else if (type_specifiers & SPECIFIER_LONG) {
3680 type_specifiers |= SPECIFIER_LONG_LONG;
3682 type_specifiers |= SPECIFIER_LONG;
3687 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3689 type->compound.compound = parse_compound_type_specifier(true);
3690 finish_struct_type(&type->compound);
3694 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3695 type->compound.compound = parse_compound_type_specifier(false);
3696 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3697 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3698 finish_union_type(&type->compound);
3702 type = parse_enum_specifier();
3705 type = parse_typeof();
3707 case T___builtin_va_list:
3708 type = duplicate_type(type_valist);
3712 case T_IDENTIFIER: {
3713 /* only parse identifier if we haven't found a type yet */
3714 if (type != NULL || type_specifiers != 0) {
3715 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3716 * declaration, so it doesn't generate errors about expecting '(' or
3718 switch (look_ahead(1)->type) {
3725 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3728 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3733 goto finish_specifiers;
3737 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3738 if (typedef_type == NULL) {
3739 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3740 * declaration, so it doesn't generate 'implicit int' followed by more
3741 * errors later on. */
3742 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3747 errorf(HERE, "%K does not name a type", &token);
3750 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3752 type = allocate_type_zero(TYPE_TYPEDEF);
3753 type->typedeft.typedefe = &entity->typedefe;
3757 if (la1_type == '*')
3758 goto finish_specifiers;
3763 goto finish_specifiers;
3768 type = typedef_type;
3772 /* function specifier */
3774 goto finish_specifiers;
3779 in_gcc_extension = old_gcc_extension;
3781 if (type == NULL || (saw_error && type_specifiers != 0)) {
3782 atomic_type_kind_t atomic_type;
3784 /* match valid basic types */
3785 switch (type_specifiers) {
3786 case SPECIFIER_VOID:
3787 atomic_type = ATOMIC_TYPE_VOID;
3789 case SPECIFIER_CHAR:
3790 atomic_type = ATOMIC_TYPE_CHAR;
3792 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3793 atomic_type = ATOMIC_TYPE_SCHAR;
3795 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3796 atomic_type = ATOMIC_TYPE_UCHAR;
3798 case SPECIFIER_SHORT:
3799 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3800 case SPECIFIER_SHORT | SPECIFIER_INT:
3801 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3802 atomic_type = ATOMIC_TYPE_SHORT;
3804 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3805 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3806 atomic_type = ATOMIC_TYPE_USHORT;
3809 case SPECIFIER_SIGNED:
3810 case SPECIFIER_SIGNED | SPECIFIER_INT:
3811 atomic_type = ATOMIC_TYPE_INT;
3813 case SPECIFIER_UNSIGNED:
3814 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3815 atomic_type = ATOMIC_TYPE_UINT;
3817 case SPECIFIER_LONG:
3818 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3819 case SPECIFIER_LONG | SPECIFIER_INT:
3820 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3821 atomic_type = ATOMIC_TYPE_LONG;
3823 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3824 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3825 atomic_type = ATOMIC_TYPE_ULONG;
3828 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3829 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3830 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3831 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3833 atomic_type = ATOMIC_TYPE_LONGLONG;
3834 goto warn_about_long_long;
3836 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3837 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3839 atomic_type = ATOMIC_TYPE_ULONGLONG;
3840 warn_about_long_long:
3841 if (warning.long_long) {
3842 warningf(&specifiers->source_position,
3843 "ISO C90 does not support 'long long'");
3847 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3848 atomic_type = unsigned_int8_type_kind;
3851 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3852 atomic_type = unsigned_int16_type_kind;
3855 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3856 atomic_type = unsigned_int32_type_kind;
3859 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3860 atomic_type = unsigned_int64_type_kind;
3863 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3864 atomic_type = unsigned_int128_type_kind;
3867 case SPECIFIER_INT8:
3868 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3869 atomic_type = int8_type_kind;
3872 case SPECIFIER_INT16:
3873 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3874 atomic_type = int16_type_kind;
3877 case SPECIFIER_INT32:
3878 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3879 atomic_type = int32_type_kind;
3882 case SPECIFIER_INT64:
3883 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3884 atomic_type = int64_type_kind;
3887 case SPECIFIER_INT128:
3888 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3889 atomic_type = int128_type_kind;
3892 case SPECIFIER_FLOAT:
3893 atomic_type = ATOMIC_TYPE_FLOAT;
3895 case SPECIFIER_DOUBLE:
3896 atomic_type = ATOMIC_TYPE_DOUBLE;
3898 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3899 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3901 case SPECIFIER_BOOL:
3902 atomic_type = ATOMIC_TYPE_BOOL;
3904 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3905 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3906 atomic_type = ATOMIC_TYPE_FLOAT;
3908 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3909 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3910 atomic_type = ATOMIC_TYPE_DOUBLE;
3912 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3913 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3914 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3917 /* invalid specifier combination, give an error message */
3918 if (type_specifiers == 0) {
3922 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3923 if (!(c_mode & _CXX) && !strict_mode) {
3924 if (warning.implicit_int) {
3925 warningf(HERE, "no type specifiers in declaration, using 'int'");
3927 atomic_type = ATOMIC_TYPE_INT;
3930 errorf(HERE, "no type specifiers given in declaration");
3932 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3933 (type_specifiers & SPECIFIER_UNSIGNED)) {
3934 errorf(HERE, "signed and unsigned specifiers given");
3935 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3936 errorf(HERE, "only integer types can be signed or unsigned");
3938 errorf(HERE, "multiple datatypes in declaration");
3943 if (type_specifiers & SPECIFIER_COMPLEX) {
3944 type = allocate_type_zero(TYPE_COMPLEX);
3945 type->complex.akind = atomic_type;
3946 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3947 type = allocate_type_zero(TYPE_IMAGINARY);
3948 type->imaginary.akind = atomic_type;
3950 type = allocate_type_zero(TYPE_ATOMIC);
3951 type->atomic.akind = atomic_type;
3954 } else if (type_specifiers != 0) {
3955 errorf(HERE, "multiple datatypes in declaration");
3958 /* FIXME: check type qualifiers here */
3960 type->base.qualifiers = qualifiers;
3961 type->base.modifiers = modifiers;
3963 type_t *result = typehash_insert(type);
3964 if (newtype && result != type) {
3968 specifiers->type = result;
3972 specifiers->type = type_error_type;
3976 static type_qualifiers_t parse_type_qualifiers(void)
3978 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3981 switch (token.type) {
3982 /* type qualifiers */
3983 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3984 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3985 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3986 /* microsoft extended type modifiers */
3987 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3988 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3989 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3990 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3991 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4000 * Parses an K&R identifier list
4002 static void parse_identifier_list(scope_t *scope)
4005 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4006 entity->base.source_position = token.source_position;
4007 entity->base.namespc = NAMESPACE_NORMAL;
4008 entity->base.symbol = token.v.symbol;
4009 /* a K&R parameter has no type, yet */
4012 append_entity(scope, entity);
4014 if (token.type != ',') {
4018 } while (token.type == T_IDENTIFIER);
4021 static type_t *automatic_type_conversion(type_t *orig_type);
4023 static void semantic_parameter(declaration_t *declaration)
4025 /* TODO: improve error messages */
4026 source_position_t const* const pos = &declaration->base.source_position;
4029 switch (declaration->declared_storage_class) {
4030 /* Allowed storage classes */
4031 case STORAGE_CLASS_NONE:
4032 case STORAGE_CLASS_REGISTER:
4036 errorf(pos, "parameter may only have none or register storage class");
4040 type_t *const orig_type = declaration->type;
4041 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
4042 * sugar. Turn it into a pointer.
4043 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4044 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4046 type_t *const type = automatic_type_conversion(orig_type);
4047 declaration->type = type;
4049 if (is_type_incomplete(skip_typeref(type))) {
4050 errorf(pos, "parameter '%#T' is of incomplete type",
4051 orig_type, declaration->base.symbol);
4055 static entity_t *parse_parameter(void)
4057 declaration_specifiers_t specifiers;
4058 memset(&specifiers, 0, sizeof(specifiers));
4060 parse_declaration_specifiers(&specifiers);
4062 entity_t *entity = parse_declarator(&specifiers, true, false);
4067 * Parses function type parameters (and optionally creates variable_t entities
4068 * for them in a scope)
4070 static void parse_parameters(function_type_t *type, scope_t *scope)
4073 add_anchor_token(')');
4074 int saved_comma_state = save_and_reset_anchor_state(',');
4076 if (token.type == T_IDENTIFIER &&
4077 !is_typedef_symbol(token.v.symbol)) {
4078 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4079 if (la1_type == ',' || la1_type == ')') {
4080 type->kr_style_parameters = true;
4081 parse_identifier_list(scope);
4082 goto parameters_finished;
4086 if (token.type == ')') {
4087 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4088 if (!(c_mode & _CXX))
4089 type->unspecified_parameters = true;
4090 goto parameters_finished;
4093 function_parameter_t *parameter;
4094 function_parameter_t *last_parameter = NULL;
4097 switch (token.type) {
4100 type->variadic = true;
4101 goto parameters_finished;
4104 case T___extension__:
4107 entity_t *entity = parse_parameter();
4108 if (entity->kind == ENTITY_TYPEDEF) {
4109 errorf(&entity->base.source_position,
4110 "typedef not allowed as function parameter");
4113 assert(is_declaration(entity));
4115 /* func(void) is not a parameter */
4116 if (last_parameter == NULL
4117 && token.type == ')'
4118 && entity->base.symbol == NULL
4119 && skip_typeref(entity->declaration.type) == type_void) {
4120 goto parameters_finished;
4122 semantic_parameter(&entity->declaration);
4124 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4125 memset(parameter, 0, sizeof(parameter[0]));
4126 parameter->type = entity->declaration.type;
4128 if (scope != NULL) {
4129 append_entity(scope, entity);
4132 if (last_parameter != NULL) {
4133 last_parameter->next = parameter;
4135 type->parameters = parameter;
4137 last_parameter = parameter;
4142 goto parameters_finished;
4144 if (token.type != ',') {
4145 goto parameters_finished;
4151 parameters_finished:
4152 rem_anchor_token(')');
4156 restore_anchor_state(',', saved_comma_state);
4159 typedef enum construct_type_kind_t {
4164 } construct_type_kind_t;
4166 typedef struct construct_type_t construct_type_t;
4167 struct construct_type_t {
4168 construct_type_kind_t kind;
4169 construct_type_t *next;
4172 typedef struct parsed_pointer_t parsed_pointer_t;
4173 struct parsed_pointer_t {
4174 construct_type_t construct_type;
4175 type_qualifiers_t type_qualifiers;
4178 typedef struct construct_function_type_t construct_function_type_t;
4179 struct construct_function_type_t {
4180 construct_type_t construct_type;
4181 type_t *function_type;
4184 typedef struct parsed_array_t parsed_array_t;
4185 struct parsed_array_t {
4186 construct_type_t construct_type;
4187 type_qualifiers_t type_qualifiers;
4193 typedef struct construct_base_type_t construct_base_type_t;
4194 struct construct_base_type_t {
4195 construct_type_t construct_type;
4199 static construct_type_t *parse_pointer_declarator(void)
4203 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4204 memset(pointer, 0, sizeof(pointer[0]));
4205 pointer->construct_type.kind = CONSTRUCT_POINTER;
4206 pointer->type_qualifiers = parse_type_qualifiers();
4208 return (construct_type_t*) pointer;
4211 static construct_type_t *parse_array_declarator(void)
4214 add_anchor_token(']');
4216 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4217 memset(array, 0, sizeof(array[0]));
4218 array->construct_type.kind = CONSTRUCT_ARRAY;
4220 if (token.type == T_static) {
4221 array->is_static = true;
4225 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4226 if (type_qualifiers != 0) {
4227 if (token.type == T_static) {
4228 array->is_static = true;
4232 array->type_qualifiers = type_qualifiers;
4234 if (token.type == '*' && look_ahead(1)->type == ']') {
4235 array->is_variable = true;
4237 } else if (token.type != ']') {
4238 array->size = parse_assignment_expression();
4241 rem_anchor_token(']');
4245 return (construct_type_t*) array;
4248 static construct_type_t *parse_function_declarator(scope_t *scope)
4250 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4252 /* TODO: revive this... once we know exactly how to do it */
4254 decl_modifiers_t modifiers = entity->declaration.modifiers;
4256 unsigned mask = modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
4258 if (mask & (mask-1)) {
4259 const char *first = NULL, *second = NULL;
4261 /* more than one calling convention set */
4262 if (modifiers & DM_CDECL) {
4263 if (first == NULL) first = "cdecl";
4264 else if (second == NULL) second = "cdecl";
4266 if (modifiers & DM_STDCALL) {
4267 if (first == NULL) first = "stdcall";
4268 else if (second == NULL) second = "stdcall";
4270 if (modifiers & DM_FASTCALL) {
4271 if (first == NULL) first = "fastcall";
4272 else if (second == NULL) second = "fastcall";
4274 if (modifiers & DM_THISCALL) {
4275 if (first == NULL) first = "thiscall";
4276 else if (second == NULL) second = "thiscall";
4278 errorf(&entity->base.source_position,
4279 "%s and %s attributes are not compatible", first, second);
4282 if (modifiers & DM_CDECL)
4283 type->function.calling_convention = CC_CDECL;
4284 else if (modifiers & DM_STDCALL)
4285 type->function.calling_convention = CC_STDCALL;
4286 else if (modifiers & DM_FASTCALL)
4287 type->function.calling_convention = CC_FASTCALL;
4288 else if (modifiers & DM_THISCALL)
4289 type->function.calling_convention = CC_THISCALL;
4292 parse_parameters(&type->function, scope);
4294 construct_function_type_t *construct_function_type =
4295 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4296 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4297 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4298 construct_function_type->function_type = type;
4300 return &construct_function_type->construct_type;
4303 typedef struct parse_declarator_env_t {
4304 decl_modifiers_t modifiers;
4306 source_position_t source_position;
4308 } parse_declarator_env_t;
4310 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4311 bool may_be_abstract)
4313 /* construct a single linked list of construct_type_t's which describe
4314 * how to construct the final declarator type */
4315 construct_type_t *first = NULL;
4316 construct_type_t *last = NULL;
4317 gnu_attribute_t *attributes = NULL;
4319 decl_modifiers_t modifiers = parse_attributes(&attributes);
4322 while (token.type == '*') {
4323 construct_type_t *type = parse_pointer_declarator();
4333 /* TODO: find out if this is correct */
4334 modifiers |= parse_attributes(&attributes);
4338 env->modifiers |= modifiers;
4340 construct_type_t *inner_types = NULL;
4342 switch (token.type) {
4345 errorf(HERE, "no identifier expected in typename");
4347 env->symbol = token.v.symbol;
4348 env->source_position = token.source_position;
4354 add_anchor_token(')');
4355 inner_types = parse_inner_declarator(env, may_be_abstract);
4356 if (inner_types != NULL) {
4357 /* All later declarators only modify the return type */
4360 rem_anchor_token(')');
4364 if (may_be_abstract)
4366 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4371 construct_type_t *p = last;
4374 construct_type_t *type;
4375 switch (token.type) {
4377 scope_t *scope = NULL;
4379 scope = &env->parameters;
4381 type = parse_function_declarator(scope);
4385 type = parse_array_declarator();
4388 goto declarator_finished;
4391 /* insert in the middle of the list (behind p) */
4393 type->next = p->next;
4404 declarator_finished:
4405 /* append inner_types at the end of the list, we don't to set last anymore
4406 * as it's not needed anymore */
4408 assert(first == NULL);
4409 first = inner_types;
4411 last->next = inner_types;
4419 static void parse_declaration_attributes(entity_t *entity)
4421 gnu_attribute_t *attributes = NULL;
4422 decl_modifiers_t modifiers = parse_attributes(&attributes);
4428 if (entity->kind == ENTITY_TYPEDEF) {
4429 modifiers |= entity->typedefe.modifiers;
4430 type = entity->typedefe.type;
4432 assert(is_declaration(entity));
4433 modifiers |= entity->declaration.modifiers;
4434 type = entity->declaration.type;
4439 /* handle these strange/stupid mode attributes */
4440 gnu_attribute_t *attribute = attributes;
4441 for ( ; attribute != NULL; attribute = attribute->next) {
4442 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4445 atomic_type_kind_t akind = attribute->u.akind;
4446 if (!is_type_signed(type)) {
4448 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4449 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4450 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4451 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4453 panic("invalid akind in mode attribute");
4457 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4458 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4459 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4460 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4462 panic("invalid akind in mode attribute");
4466 type = make_atomic_type(akind, type->base.qualifiers);
4469 type_modifiers_t type_modifiers = type->base.modifiers;
4470 if (modifiers & DM_TRANSPARENT_UNION)
4471 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4473 if (type->base.modifiers != type_modifiers) {
4474 type_t *copy = duplicate_type(type);
4475 copy->base.modifiers = type_modifiers;
4477 type = typehash_insert(copy);
4479 obstack_free(type_obst, copy);
4483 if (entity->kind == ENTITY_TYPEDEF) {
4484 entity->typedefe.type = type;
4485 entity->typedefe.modifiers = modifiers;
4487 entity->declaration.type = type;
4488 entity->declaration.modifiers = modifiers;
4492 static type_t *construct_declarator_type(construct_type_t *construct_list,
4495 construct_type_t *iter = construct_list;
4496 for( ; iter != NULL; iter = iter->next) {
4497 switch (iter->kind) {
4498 case CONSTRUCT_INVALID:
4499 internal_errorf(HERE, "invalid type construction found");
4500 case CONSTRUCT_FUNCTION: {
4501 construct_function_type_t *construct_function_type
4502 = (construct_function_type_t*) iter;
4504 type_t *function_type = construct_function_type->function_type;
4506 function_type->function.return_type = type;
4508 type_t *skipped_return_type = skip_typeref(type);
4510 if (is_type_function(skipped_return_type)) {
4511 errorf(HERE, "function returning function is not allowed");
4512 } else if (is_type_array(skipped_return_type)) {
4513 errorf(HERE, "function returning array is not allowed");
4515 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4517 "type qualifiers in return type of function type are meaningless");
4521 type = function_type;
4525 case CONSTRUCT_POINTER: {
4526 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4527 type = make_pointer_type(type, parsed_pointer->type_qualifiers);
4531 case CONSTRUCT_ARRAY: {
4532 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4533 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4535 expression_t *size_expression = parsed_array->size;
4536 if (size_expression != NULL) {
4538 = create_implicit_cast(size_expression, type_size_t);
4541 array_type->base.qualifiers = parsed_array->type_qualifiers;
4542 array_type->array.element_type = type;
4543 array_type->array.is_static = parsed_array->is_static;
4544 array_type->array.is_variable = parsed_array->is_variable;
4545 array_type->array.size_expression = size_expression;
4547 if (size_expression != NULL) {
4548 if (is_constant_expression(size_expression)) {
4549 array_type->array.size_constant = true;
4550 array_type->array.size
4551 = fold_constant(size_expression);
4553 array_type->array.is_vla = true;
4557 type_t *skipped_type = skip_typeref(type);
4559 if (is_type_incomplete(skipped_type)) {
4560 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4561 } else if (is_type_function(skipped_type)) {
4562 errorf(HERE, "array of functions is not allowed");
4569 type_t *hashed_type = typehash_insert(type);
4570 if (hashed_type != type) {
4571 /* the function type was constructed earlier freeing it here will
4572 * destroy other types... */
4573 if (iter->kind != CONSTRUCT_FUNCTION) {
4583 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4584 bool may_be_abstract,
4585 bool create_compound_member)
4587 parse_declarator_env_t env;
4588 memset(&env, 0, sizeof(env));
4590 construct_type_t *construct_type
4591 = parse_inner_declarator(&env, may_be_abstract);
4592 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4594 if (construct_type != NULL) {
4595 obstack_free(&temp_obst, construct_type);
4599 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4600 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4601 entity->base.symbol = env.symbol;
4602 entity->base.source_position = env.source_position;
4603 entity->typedefe.type = type;
4605 if (create_compound_member) {
4606 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4607 } else if (is_type_function(skip_typeref(type))) {
4608 entity = allocate_entity_zero(ENTITY_FUNCTION);
4610 entity->function.is_inline = specifiers->is_inline;
4611 entity->function.parameters = env.parameters;
4613 entity = allocate_entity_zero(ENTITY_VARIABLE);
4615 entity->variable.get_property_sym = specifiers->get_property_sym;
4616 entity->variable.put_property_sym = specifiers->put_property_sym;
4617 if (specifiers->alignment != 0) {
4618 /* TODO: add checks here */
4619 entity->variable.alignment = specifiers->alignment;
4622 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4623 warningf(&env.source_position,
4624 "variable '%Y' declared 'inline'\n", env.symbol);
4628 entity->base.source_position = env.source_position;
4629 entity->base.symbol = env.symbol;
4630 entity->base.namespc = NAMESPACE_NORMAL;
4631 entity->declaration.type = type;
4632 entity->declaration.modifiers = env.modifiers | specifiers->modifiers;
4633 entity->declaration.deprecated_string = specifiers->deprecated_string;
4635 storage_class_t storage_class = specifiers->storage_class;
4636 entity->declaration.declared_storage_class = storage_class;
4638 if (storage_class == STORAGE_CLASS_NONE && scope != file_scope) {
4639 storage_class = STORAGE_CLASS_AUTO;
4641 entity->declaration.storage_class = storage_class;
4644 parse_declaration_attributes(entity);
4649 static type_t *parse_abstract_declarator(type_t *base_type)
4651 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4653 type_t *result = construct_declarator_type(construct_type, base_type);
4654 if (construct_type != NULL) {
4655 obstack_free(&temp_obst, construct_type);
4662 * Check if the declaration of main is suspicious. main should be a
4663 * function with external linkage, returning int, taking either zero
4664 * arguments, two, or three arguments of appropriate types, ie.
4666 * int main([ int argc, char **argv [, char **env ] ]).
4668 * @param decl the declaration to check
4669 * @param type the function type of the declaration
4671 static void check_type_of_main(const entity_t *entity)
4673 const source_position_t *pos = &entity->base.source_position;
4674 if (entity->kind != ENTITY_FUNCTION) {
4675 warningf(pos, "'main' is not a function");
4679 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4680 warningf(pos, "'main' is normally a non-static function");
4683 type_t *type = skip_typeref(entity->declaration.type);
4684 assert(is_type_function(type));
4686 function_type_t *func_type = &type->function;
4687 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4688 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4689 func_type->return_type);
4691 const function_parameter_t *parm = func_type->parameters;
4693 type_t *const first_type = parm->type;
4694 if (!types_compatible(skip_typeref(first_type), type_int)) {
4696 "first argument of 'main' should be 'int', but is '%T'",
4701 type_t *const second_type = parm->type;
4702 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4703 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4707 type_t *const third_type = parm->type;
4708 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4709 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4713 goto warn_arg_count;
4717 warningf(pos, "'main' takes only zero, two or three arguments");
4723 * Check if a symbol is the equal to "main".
4725 static bool is_sym_main(const symbol_t *const sym)
4727 return strcmp(sym->string, "main") == 0;
4731 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4732 * for various problems that occur for multiple definitions
4734 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4736 const symbol_t *const symbol = entity->base.symbol;
4737 const namespace_t namespc = entity->base.namespc;
4738 const source_position_t *pos = &entity->base.source_position;
4740 assert(symbol != NULL);
4741 entity_t *previous_entity = get_entity(symbol, namespc);
4742 /* pushing the same entity twice will break the stack structure */
4743 assert(previous_entity != entity);
4745 if (entity->kind == ENTITY_FUNCTION) {
4746 type_t *const orig_type = entity->declaration.type;
4747 type_t *const type = skip_typeref(orig_type);
4749 assert(is_type_function(type));
4750 if (type->function.unspecified_parameters &&
4751 warning.strict_prototypes &&
4752 previous_entity == NULL) {
4753 warningf(pos, "function declaration '%#T' is not a prototype",
4757 if (warning.main && scope == file_scope && is_sym_main(symbol)) {
4758 check_type_of_main(entity);
4762 if (is_declaration(entity)) {
4763 if (warning.nested_externs
4764 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4765 && scope != file_scope) {
4766 warningf(pos, "nested extern declaration of '%#T'",
4767 entity->declaration.type, symbol);
4771 if (previous_entity != NULL
4772 && previous_entity->base.parent_scope == ¤t_function->parameters
4773 && scope->depth == previous_entity->base.parent_scope->depth + 1) {
4775 assert(previous_entity->kind == ENTITY_VARIABLE);
4777 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4778 entity->declaration.type, symbol,
4779 previous_entity->declaration.type, symbol,
4780 &previous_entity->base.source_position);
4784 if (previous_entity != NULL
4785 && previous_entity->base.parent_scope == scope) {
4787 if (previous_entity->kind != entity->kind) {
4789 "redeclaration of '%Y' as different kind of symbol (declared %P)",
4790 symbol, &previous_entity->base.source_position);
4793 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4795 "redeclaration of enum entry '%Y' (declared %P)",
4796 symbol, &previous_entity->base.source_position);
4799 if (previous_entity->kind == ENTITY_TYPEDEF) {
4800 /* TODO: C++ allows this for exactly the same type */
4802 "redefinition of typedef '%Y' (declared %P)",
4803 symbol, &previous_entity->base.source_position);
4807 /* at this point we should have only VARIABLES or FUNCTIONS */
4808 assert(is_declaration(previous_entity) && is_declaration(entity));
4810 /* can happen for K&R style declarations */
4811 if (previous_entity->kind == ENTITY_VARIABLE
4812 && previous_entity->declaration.type == NULL
4813 && entity->kind == ENTITY_VARIABLE) {
4814 previous_entity->declaration.type = entity->declaration.type;
4815 previous_entity->declaration.storage_class
4816 = entity->declaration.storage_class;
4817 previous_entity->declaration.declared_storage_class
4818 = entity->declaration.declared_storage_class;
4819 previous_entity->declaration.modifiers
4820 = entity->declaration.modifiers;
4821 previous_entity->declaration.deprecated_string
4822 = entity->declaration.deprecated_string;
4824 assert(entity->declaration.type != NULL);
4826 declaration_t *const previous_declaration
4827 = &previous_entity->declaration;
4828 declaration_t *const declaration = &entity->declaration;
4829 type_t *const orig_type = entity->declaration.type;
4830 type_t *const type = skip_typeref(orig_type);
4832 type_t *prev_type = skip_typeref(previous_declaration->type);
4834 if (!types_compatible(type, prev_type)) {
4836 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4837 orig_type, symbol, previous_declaration->type, symbol,
4838 &previous_entity->base.source_position);
4840 unsigned old_storage_class = previous_declaration->storage_class;
4841 if (warning.redundant_decls && is_definition
4842 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4843 && !(previous_declaration->modifiers & DM_USED)
4844 && !previous_declaration->used) {
4845 warningf(&previous_entity->base.source_position,
4846 "unnecessary static forward declaration for '%#T'",
4847 previous_declaration->type, symbol);
4850 unsigned new_storage_class = declaration->storage_class;
4851 if (is_type_incomplete(prev_type)) {
4852 previous_declaration->type = type;
4856 /* pretend no storage class means extern for function
4857 * declarations (except if the previous declaration is neither
4858 * none nor extern) */
4859 if (entity->kind == ENTITY_FUNCTION) {
4860 if (prev_type->function.unspecified_parameters) {
4861 previous_declaration->type = type;
4865 switch (old_storage_class) {
4866 case STORAGE_CLASS_NONE:
4867 old_storage_class = STORAGE_CLASS_EXTERN;
4870 case STORAGE_CLASS_EXTERN:
4871 if (is_definition) {
4872 if (warning.missing_prototypes &&
4873 prev_type->function.unspecified_parameters &&
4874 !is_sym_main(symbol)) {
4875 warningf(pos, "no previous prototype for '%#T'",
4878 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4879 new_storage_class = STORAGE_CLASS_EXTERN;
4888 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4889 new_storage_class == STORAGE_CLASS_EXTERN) {
4890 warn_redundant_declaration:
4891 if (!is_definition &&
4892 warning.redundant_decls &&
4893 is_type_valid(prev_type) &&
4894 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4896 "redundant declaration for '%Y' (declared %P)",
4897 symbol, &previous_entity->base.source_position);
4899 } else if (current_function == NULL) {
4900 if (old_storage_class != STORAGE_CLASS_STATIC &&
4901 new_storage_class == STORAGE_CLASS_STATIC) {
4903 "static declaration of '%Y' follows non-static declaration (declared %P)",
4904 symbol, &previous_entity->base.source_position);
4905 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4906 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4907 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4909 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4911 goto error_redeclaration;
4912 goto warn_redundant_declaration;
4914 } else if (is_type_valid(prev_type)) {
4915 if (old_storage_class == new_storage_class) {
4916 error_redeclaration:
4917 errorf(pos, "redeclaration of '%Y' (declared %P)",
4918 symbol, &previous_entity->base.source_position);
4921 "redeclaration of '%Y' with different linkage (declared %P)",
4922 symbol, &previous_entity->base.source_position);
4927 previous_declaration->modifiers |= declaration->modifiers;
4928 if (entity->kind == ENTITY_FUNCTION) {
4929 previous_entity->function.is_inline |= entity->function.is_inline;
4931 return previous_entity;
4934 if (entity->kind == ENTITY_FUNCTION) {
4935 if (is_definition &&
4936 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4937 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4938 warningf(pos, "no previous prototype for '%#T'",
4939 entity->declaration.type, symbol);
4940 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4941 warningf(pos, "no previous declaration for '%#T'",
4942 entity->declaration.type, symbol);
4945 } else if (warning.missing_declarations
4946 && entity->kind == ENTITY_VARIABLE
4947 && scope == file_scope) {
4948 declaration_t *declaration = &entity->declaration;
4949 if (declaration->storage_class == STORAGE_CLASS_NONE ||
4950 declaration->storage_class == STORAGE_CLASS_THREAD) {
4951 warningf(pos, "no previous declaration for '%#T'",
4952 declaration->type, symbol);
4957 assert(entity->base.parent_scope == NULL);
4958 assert(scope != NULL);
4960 entity->base.parent_scope = scope;
4961 entity->base.namespc = NAMESPACE_NORMAL;
4962 environment_push(entity);
4963 append_entity(scope, entity);
4968 static void parser_error_multiple_definition(entity_t *entity,
4969 const source_position_t *source_position)
4971 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4972 entity->base.symbol, &entity->base.source_position);
4975 static bool is_declaration_specifier(const token_t *token,
4976 bool only_specifiers_qualifiers)
4978 switch (token->type) {
4983 return is_typedef_symbol(token->v.symbol);
4985 case T___extension__:
4987 return !only_specifiers_qualifiers;
4994 static void parse_init_declarator_rest(entity_t *entity)
4996 assert(is_declaration(entity));
4997 declaration_t *const declaration = &entity->declaration;
5001 type_t *orig_type = declaration->type;
5002 type_t *type = skip_typeref(orig_type);
5004 if (entity->kind == ENTITY_VARIABLE
5005 && entity->variable.initializer != NULL) {
5006 parser_error_multiple_definition(entity, HERE);
5009 bool must_be_constant = false;
5010 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5011 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5012 entity->base.parent_scope == file_scope) {
5013 must_be_constant = true;
5016 if (is_type_function(type)) {
5017 errorf(&entity->base.source_position,
5018 "function '%#T' is initialized like a variable",
5019 orig_type, entity->base.symbol);
5020 orig_type = type_error_type;
5023 parse_initializer_env_t env;
5024 env.type = orig_type;
5025 env.must_be_constant = must_be_constant;
5026 env.entity = entity;
5027 current_init_decl = entity;
5029 initializer_t *initializer = parse_initializer(&env);
5030 current_init_decl = NULL;
5032 if (entity->kind == ENTITY_VARIABLE) {
5033 /* § 6.7.5 (22) array initializers for arrays with unknown size
5034 * determine the array type size */
5035 declaration->type = env.type;
5036 entity->variable.initializer = initializer;
5040 /* parse rest of a declaration without any declarator */
5041 static void parse_anonymous_declaration_rest(
5042 const declaration_specifiers_t *specifiers)
5046 if (warning.other) {
5047 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5048 warningf(&specifiers->source_position,
5049 "useless storage class in empty declaration");
5052 type_t *type = specifiers->type;
5053 switch (type->kind) {
5054 case TYPE_COMPOUND_STRUCT:
5055 case TYPE_COMPOUND_UNION: {
5056 if (type->compound.compound->base.symbol == NULL) {
5057 warningf(&specifiers->source_position,
5058 "unnamed struct/union that defines no instances");
5067 warningf(&specifiers->source_position, "empty declaration");
5073 static void parse_declaration_rest(entity_t *ndeclaration,
5074 const declaration_specifiers_t *specifiers,
5075 parsed_declaration_func finished_declaration)
5077 add_anchor_token(';');
5078 add_anchor_token(',');
5080 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5082 if (token.type == '=') {
5083 parse_init_declarator_rest(entity);
5086 if (token.type != ',')
5090 add_anchor_token('=');
5091 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5092 rem_anchor_token('=');
5097 rem_anchor_token(';');
5098 rem_anchor_token(',');
5101 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5103 symbol_t *symbol = entity->base.symbol;
5104 if (symbol == NULL) {
5105 errorf(HERE, "anonymous declaration not valid as function parameter");
5109 assert(entity->base.namespc == NAMESPACE_NORMAL);
5110 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5111 if (previous_entity == NULL
5112 || previous_entity->base.parent_scope != scope) {
5113 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5118 if (is_definition) {
5119 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5122 return record_entity(entity, false);
5125 static void parse_declaration(parsed_declaration_func finished_declaration)
5127 declaration_specifiers_t specifiers;
5128 memset(&specifiers, 0, sizeof(specifiers));
5130 add_anchor_token(';');
5131 parse_declaration_specifiers(&specifiers);
5132 rem_anchor_token(';');
5134 if (token.type == ';') {
5135 parse_anonymous_declaration_rest(&specifiers);
5137 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5138 parse_declaration_rest(entity, &specifiers, finished_declaration);
5142 static type_t *get_default_promoted_type(type_t *orig_type)
5144 type_t *result = orig_type;
5146 type_t *type = skip_typeref(orig_type);
5147 if (is_type_integer(type)) {
5148 result = promote_integer(type);
5149 } else if (type == type_float) {
5150 result = type_double;
5156 static void parse_kr_declaration_list(entity_t *entity)
5158 if (entity->kind != ENTITY_FUNCTION)
5161 type_t *type = skip_typeref(entity->declaration.type);
5162 assert(is_type_function(type));
5163 if (!type->function.kr_style_parameters)
5167 add_anchor_token('{');
5169 /* push function parameters */
5170 size_t const top = environment_top();
5171 scope_push(&entity->function.parameters);
5173 entity_t *parameter = entity->function.parameters.entities;
5174 for ( ; parameter != NULL; parameter = parameter->base.next) {
5175 assert(parameter->base.parent_scope == NULL);
5176 parameter->base.parent_scope = scope;
5177 environment_push(parameter);
5180 /* parse declaration list */
5181 while (is_declaration_specifier(&token, false)) {
5182 parse_declaration(finished_kr_declaration);
5185 /* pop function parameters */
5186 assert(scope == &entity->function.parameters);
5188 environment_pop_to(top);
5190 /* update function type */
5191 type_t *new_type = duplicate_type(type);
5193 function_parameter_t *parameters = NULL;
5194 function_parameter_t *last_parameter = NULL;
5196 entity_t *parameter_declaration = entity->function.parameters.entities;
5197 for( ; parameter_declaration != NULL;
5198 parameter_declaration = parameter_declaration->base.next) {
5199 type_t *parameter_type = parameter_declaration->declaration.type;
5200 if (parameter_type == NULL) {
5202 errorf(HERE, "no type specified for function parameter '%Y'",
5203 parameter_declaration->base.symbol);
5205 if (warning.implicit_int) {
5206 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5207 parameter_declaration->base.symbol);
5209 parameter_type = type_int;
5210 parameter_declaration->declaration.type = parameter_type;
5214 semantic_parameter(¶meter_declaration->declaration);
5215 parameter_type = parameter_declaration->declaration.type;
5218 * we need the default promoted types for the function type
5220 parameter_type = get_default_promoted_type(parameter_type);
5222 function_parameter_t *function_parameter
5223 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5224 memset(function_parameter, 0, sizeof(function_parameter[0]));
5226 function_parameter->type = parameter_type;
5227 if (last_parameter != NULL) {
5228 last_parameter->next = function_parameter;
5230 parameters = function_parameter;
5232 last_parameter = function_parameter;
5235 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5237 new_type->function.parameters = parameters;
5238 new_type->function.unspecified_parameters = true;
5240 type = typehash_insert(new_type);
5241 if (type != new_type) {
5242 obstack_free(type_obst, new_type);
5245 entity->declaration.type = type;
5247 rem_anchor_token('{');
5250 static bool first_err = true;
5253 * When called with first_err set, prints the name of the current function,
5256 static void print_in_function(void)
5260 diagnosticf("%s: In function '%Y':\n",
5261 current_function->base.base.source_position.input_name,
5262 current_function->base.base.symbol);
5267 * Check if all labels are defined in the current function.
5268 * Check if all labels are used in the current function.
5270 static void check_labels(void)
5272 for (const goto_statement_t *goto_statement = goto_first;
5273 goto_statement != NULL;
5274 goto_statement = goto_statement->next) {
5275 /* skip computed gotos */
5276 if (goto_statement->expression != NULL)
5279 label_t *label = goto_statement->label;
5282 if (label->base.source_position.input_name == NULL) {
5283 print_in_function();
5284 errorf(&goto_statement->base.source_position,
5285 "label '%Y' used but not defined", label->base.symbol);
5291 if (warning.unused_label) {
5292 for (const label_statement_t *label_statement = label_first;
5293 label_statement != NULL;
5294 label_statement = label_statement->next) {
5295 label_t *label = label_statement->label;
5297 if (! label->used) {
5298 print_in_function();
5299 warningf(&label_statement->base.source_position,
5300 "label '%Y' defined but not used", label->base.symbol);
5304 label_first = label_last = NULL;
5307 static void warn_unused_decl(entity_t *entity, entity_t *end,
5308 char const *const what)
5310 for (; entity != NULL; entity = entity->base.next) {
5311 if (!is_declaration(entity))
5314 declaration_t *declaration = &entity->declaration;
5315 if (declaration->implicit)
5318 if (!declaration->used) {
5319 print_in_function();
5320 warningf(&entity->base.source_position, "%s '%Y' is unused",
5321 what, entity->base.symbol);
5322 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5323 print_in_function();
5324 warningf(&entity->base.source_position, "%s '%Y' is never read",
5325 what, entity->base.symbol);
5333 static void check_unused_variables(statement_t *const stmt, void *const env)
5337 switch (stmt->kind) {
5338 case STATEMENT_DECLARATION: {
5339 declaration_statement_t const *const decls = &stmt->declaration;
5340 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5346 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5355 * Check declarations of current_function for unused entities.
5357 static void check_declarations(void)
5359 if (warning.unused_parameter) {
5360 const scope_t *scope = ¤t_function->parameters;
5362 /* do not issue unused warnings for main */
5363 if (!is_sym_main(current_function->base.base.symbol)) {
5364 warn_unused_decl(scope->entities, NULL, "parameter");
5367 if (warning.unused_variable) {
5368 walk_statements(current_function->statement, check_unused_variables,
5373 static int determine_truth(expression_t const* const cond)
5376 !is_constant_expression(cond) ? 0 :
5377 fold_constant(cond) != 0 ? 1 :
5381 static bool expression_returns(expression_t const *const expr)
5383 switch (expr->kind) {
5385 expression_t const *const func = expr->call.function;
5386 if (func->kind == EXPR_REFERENCE) {
5387 entity_t *entity = func->reference.entity;
5388 if (entity->kind == ENTITY_FUNCTION
5389 && entity->declaration.modifiers & DM_NORETURN)
5393 if (!expression_returns(func))
5396 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5397 if (!expression_returns(arg->expression))
5404 case EXPR_REFERENCE:
5405 case EXPR_REFERENCE_ENUM_VALUE:
5407 case EXPR_CHARACTER_CONSTANT:
5408 case EXPR_WIDE_CHARACTER_CONSTANT:
5409 case EXPR_STRING_LITERAL:
5410 case EXPR_WIDE_STRING_LITERAL:
5411 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5412 case EXPR_LABEL_ADDRESS:
5413 case EXPR_CLASSIFY_TYPE:
5414 case EXPR_SIZEOF: // TODO handle obscure VLA case
5417 case EXPR_BUILTIN_SYMBOL:
5418 case EXPR_BUILTIN_CONSTANT_P:
5419 case EXPR_BUILTIN_PREFETCH:
5421 case EXPR_STATEMENT: // TODO implement
5424 case EXPR_CONDITIONAL:
5425 // TODO handle constant expression
5427 expression_returns(expr->conditional.condition) && (
5428 expression_returns(expr->conditional.true_expression) ||
5429 expression_returns(expr->conditional.false_expression)
5433 return expression_returns(expr->select.compound);
5435 case EXPR_ARRAY_ACCESS:
5437 expression_returns(expr->array_access.array_ref) &&
5438 expression_returns(expr->array_access.index);
5441 return expression_returns(expr->va_starte.ap);
5444 return expression_returns(expr->va_arge.ap);
5446 EXPR_UNARY_CASES_MANDATORY
5447 return expression_returns(expr->unary.value);
5449 case EXPR_UNARY_THROW:
5453 // TODO handle constant lhs of && and ||
5455 expression_returns(expr->binary.left) &&
5456 expression_returns(expr->binary.right);
5463 panic("unhandled expression");
5466 static bool noreturn_candidate;
5468 static void check_reachable(statement_t *const stmt)
5470 if (stmt->base.reachable)
5472 if (stmt->kind != STATEMENT_DO_WHILE)
5473 stmt->base.reachable = true;
5475 statement_t *last = stmt;
5477 switch (stmt->kind) {
5478 case STATEMENT_INVALID:
5479 case STATEMENT_EMPTY:
5480 case STATEMENT_DECLARATION:
5481 case STATEMENT_LOCAL_LABEL:
5483 next = stmt->base.next;
5486 case STATEMENT_COMPOUND:
5487 next = stmt->compound.statements;
5490 case STATEMENT_RETURN:
5491 noreturn_candidate = false;
5494 case STATEMENT_IF: {
5495 if_statement_t const* const ifs = &stmt->ifs;
5496 int const val = determine_truth(ifs->condition);
5499 check_reachable(ifs->true_statement);
5504 if (ifs->false_statement != NULL) {
5505 check_reachable(ifs->false_statement);
5509 next = stmt->base.next;
5513 case STATEMENT_SWITCH: {
5514 switch_statement_t const *const switchs = &stmt->switchs;
5515 expression_t const *const expr = switchs->expression;
5517 if (is_constant_expression(expr)) {
5518 long const val = fold_constant(expr);
5519 case_label_statement_t * defaults = NULL;
5520 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5521 if (i->expression == NULL) {
5526 if (i->first_case <= val && val <= i->last_case) {
5527 check_reachable((statement_t*)i);
5532 if (defaults != NULL) {
5533 check_reachable((statement_t*)defaults);
5537 bool has_default = false;
5538 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5539 if (i->expression == NULL)
5542 check_reachable((statement_t*)i);
5549 next = stmt->base.next;
5553 case STATEMENT_EXPRESSION: {
5554 /* Check for noreturn function call */
5555 expression_t const *const expr = stmt->expression.expression;
5556 if (!expression_returns(expr))
5559 next = stmt->base.next;
5563 case STATEMENT_CONTINUE: {
5564 statement_t *parent = stmt;
5566 parent = parent->base.parent;
5567 if (parent == NULL) /* continue not within loop */
5571 switch (parent->kind) {
5572 case STATEMENT_WHILE: goto continue_while;
5573 case STATEMENT_DO_WHILE: goto continue_do_while;
5574 case STATEMENT_FOR: goto continue_for;
5581 case STATEMENT_BREAK: {
5582 statement_t *parent = stmt;
5584 parent = parent->base.parent;
5585 if (parent == NULL) /* break not within loop/switch */
5588 switch (parent->kind) {
5589 case STATEMENT_SWITCH:
5590 case STATEMENT_WHILE:
5591 case STATEMENT_DO_WHILE:
5594 next = parent->base.next;
5595 goto found_break_parent;
5604 case STATEMENT_GOTO:
5605 if (stmt->gotos.expression) {
5606 statement_t *parent = stmt->base.parent;
5607 if (parent == NULL) /* top level goto */
5611 next = stmt->gotos.label->statement;
5612 if (next == NULL) /* missing label */
5617 case STATEMENT_LABEL:
5618 next = stmt->label.statement;
5621 case STATEMENT_CASE_LABEL:
5622 next = stmt->case_label.statement;
5625 case STATEMENT_WHILE: {
5626 while_statement_t const *const whiles = &stmt->whiles;
5627 int const val = determine_truth(whiles->condition);
5630 check_reachable(whiles->body);
5635 next = stmt->base.next;
5639 case STATEMENT_DO_WHILE:
5640 next = stmt->do_while.body;
5643 case STATEMENT_FOR: {
5644 for_statement_t *const fors = &stmt->fors;
5646 if (fors->condition_reachable)
5648 fors->condition_reachable = true;
5650 expression_t const *const cond = fors->condition;
5652 cond == NULL ? 1 : determine_truth(cond);
5655 check_reachable(fors->body);
5660 next = stmt->base.next;
5664 case STATEMENT_MS_TRY: {
5665 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5666 check_reachable(ms_try->try_statement);
5667 next = ms_try->final_statement;
5671 case STATEMENT_LEAVE: {
5672 statement_t *parent = stmt;
5674 parent = parent->base.parent;
5675 if (parent == NULL) /* __leave not within __try */
5678 if (parent->kind == STATEMENT_MS_TRY) {
5680 next = parent->ms_try.final_statement;
5688 while (next == NULL) {
5689 next = last->base.parent;
5691 noreturn_candidate = false;
5693 type_t *const type = current_function->base.type;
5694 assert(is_type_function(type));
5695 type_t *const ret = skip_typeref(type->function.return_type);
5696 if (warning.return_type &&
5697 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5698 is_type_valid(ret) &&
5699 !is_sym_main(current_function->base.base.symbol)) {
5700 warningf(&stmt->base.source_position,
5701 "control reaches end of non-void function");
5706 switch (next->kind) {
5707 case STATEMENT_INVALID:
5708 case STATEMENT_EMPTY:
5709 case STATEMENT_DECLARATION:
5710 case STATEMENT_LOCAL_LABEL:
5711 case STATEMENT_EXPRESSION:
5713 case STATEMENT_RETURN:
5714 case STATEMENT_CONTINUE:
5715 case STATEMENT_BREAK:
5716 case STATEMENT_GOTO:
5717 case STATEMENT_LEAVE:
5718 panic("invalid control flow in function");
5720 case STATEMENT_COMPOUND:
5722 case STATEMENT_SWITCH:
5723 case STATEMENT_LABEL:
5724 case STATEMENT_CASE_LABEL:
5726 next = next->base.next;
5729 case STATEMENT_WHILE: {
5731 if (next->base.reachable)
5733 next->base.reachable = true;
5735 while_statement_t const *const whiles = &next->whiles;
5736 int const val = determine_truth(whiles->condition);
5739 check_reachable(whiles->body);
5745 next = next->base.next;
5749 case STATEMENT_DO_WHILE: {
5751 if (next->base.reachable)
5753 next->base.reachable = true;
5755 do_while_statement_t const *const dw = &next->do_while;
5756 int const val = determine_truth(dw->condition);
5759 check_reachable(dw->body);
5765 next = next->base.next;
5769 case STATEMENT_FOR: {
5771 for_statement_t *const fors = &next->fors;
5773 fors->step_reachable = true;
5775 if (fors->condition_reachable)
5777 fors->condition_reachable = true;
5779 expression_t const *const cond = fors->condition;
5781 cond == NULL ? 1 : determine_truth(cond);
5784 check_reachable(fors->body);
5790 next = next->base.next;
5794 case STATEMENT_MS_TRY:
5796 next = next->ms_try.final_statement;
5801 check_reachable(next);
5804 static void check_unreachable(statement_t* const stmt, void *const env)
5808 switch (stmt->kind) {
5809 case STATEMENT_DO_WHILE:
5810 if (!stmt->base.reachable) {
5811 expression_t const *const cond = stmt->do_while.condition;
5812 if (determine_truth(cond) >= 0) {
5813 warningf(&cond->base.source_position,
5814 "condition of do-while-loop is unreachable");
5819 case STATEMENT_FOR: {
5820 for_statement_t const* const fors = &stmt->fors;
5822 // if init and step are unreachable, cond is unreachable, too
5823 if (!stmt->base.reachable && !fors->step_reachable) {
5824 warningf(&stmt->base.source_position, "statement is unreachable");
5826 if (!stmt->base.reachable && fors->initialisation != NULL) {
5827 warningf(&fors->initialisation->base.source_position,
5828 "initialisation of for-statement is unreachable");
5831 if (!fors->condition_reachable && fors->condition != NULL) {
5832 warningf(&fors->condition->base.source_position,
5833 "condition of for-statement is unreachable");
5836 if (!fors->step_reachable && fors->step != NULL) {
5837 warningf(&fors->step->base.source_position,
5838 "step of for-statement is unreachable");
5844 case STATEMENT_COMPOUND:
5845 if (stmt->compound.statements != NULL)
5850 if (!stmt->base.reachable)
5851 warningf(&stmt->base.source_position, "statement is unreachable");
5856 static void parse_external_declaration(void)
5858 /* function-definitions and declarations both start with declaration
5860 declaration_specifiers_t specifiers;
5861 memset(&specifiers, 0, sizeof(specifiers));
5863 add_anchor_token(';');
5864 parse_declaration_specifiers(&specifiers);
5865 rem_anchor_token(';');
5867 /* must be a declaration */
5868 if (token.type == ';') {
5869 parse_anonymous_declaration_rest(&specifiers);
5873 add_anchor_token(',');
5874 add_anchor_token('=');
5875 add_anchor_token(';');
5876 add_anchor_token('{');
5878 /* declarator is common to both function-definitions and declarations */
5879 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5881 rem_anchor_token('{');
5882 rem_anchor_token(';');
5883 rem_anchor_token('=');
5884 rem_anchor_token(',');
5886 /* must be a declaration */
5887 switch (token.type) {
5891 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
5895 /* must be a function definition */
5896 parse_kr_declaration_list(ndeclaration);
5898 if (token.type != '{') {
5899 parse_error_expected("while parsing function definition", '{', NULL);
5900 eat_until_matching_token(';');
5904 assert(is_declaration(ndeclaration));
5905 type_t *type = ndeclaration->declaration.type;
5907 /* note that we don't skip typerefs: the standard doesn't allow them here
5908 * (so we can't use is_type_function here) */
5909 if (type->kind != TYPE_FUNCTION) {
5910 if (is_type_valid(type)) {
5911 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5912 type, ndeclaration->base.symbol);
5918 if (warning.aggregate_return &&
5919 is_type_compound(skip_typeref(type->function.return_type))) {
5920 warningf(HERE, "function '%Y' returns an aggregate",
5921 ndeclaration->base.symbol);
5923 if (warning.traditional && !type->function.unspecified_parameters) {
5924 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5925 ndeclaration->base.symbol);
5927 if (warning.old_style_definition && type->function.unspecified_parameters) {
5928 warningf(HERE, "old-style function definition '%Y'",
5929 ndeclaration->base.symbol);
5932 /* § 6.7.5.3 (14) a function definition with () means no
5933 * parameters (and not unspecified parameters) */
5934 if (type->function.unspecified_parameters
5935 && type->function.parameters == NULL
5936 && !type->function.kr_style_parameters) {
5937 type_t *duplicate = duplicate_type(type);
5938 duplicate->function.unspecified_parameters = false;
5940 type = typehash_insert(duplicate);
5941 if (type != duplicate) {
5942 obstack_free(type_obst, duplicate);
5944 ndeclaration->declaration.type = type;
5947 entity_t *const entity = record_entity(ndeclaration, true);
5948 assert(entity->kind == ENTITY_FUNCTION);
5949 assert(ndeclaration->kind == ENTITY_FUNCTION);
5951 function_t *function = &entity->function;
5952 if (ndeclaration != entity) {
5953 function->parameters = ndeclaration->function.parameters;
5955 assert(is_declaration(entity));
5956 type = skip_typeref(entity->declaration.type);
5958 /* push function parameters and switch scope */
5959 size_t const top = environment_top();
5960 scope_push(&function->parameters);
5962 entity_t *parameter = function->parameters.entities;
5963 for( ; parameter != NULL; parameter = parameter->base.next) {
5964 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5965 parameter->base.parent_scope = scope;
5967 assert(parameter->base.parent_scope == NULL
5968 || parameter->base.parent_scope == scope);
5969 parameter->base.parent_scope = scope;
5970 if (parameter->base.symbol == NULL) {
5971 errorf(¶meter->base.source_position, "parameter name omitted");
5974 environment_push(parameter);
5977 if (function->statement != NULL) {
5978 parser_error_multiple_definition(entity, HERE);
5981 /* parse function body */
5982 int label_stack_top = label_top();
5983 function_t *old_current_function = current_function;
5984 current_function = function;
5985 current_parent = NULL;
5987 statement_t *const body = parse_compound_statement(false);
5988 function->statement = body;
5991 check_declarations();
5992 if (warning.return_type ||
5993 warning.unreachable_code ||
5994 (warning.missing_noreturn
5995 && !(function->base.modifiers & DM_NORETURN))) {
5996 noreturn_candidate = true;
5997 check_reachable(body);
5998 if (warning.unreachable_code)
5999 walk_statements(body, check_unreachable, NULL);
6000 if (warning.missing_noreturn &&
6001 noreturn_candidate &&
6002 !(function->base.modifiers & DM_NORETURN)) {
6003 warningf(&body->base.source_position,
6004 "function '%#T' is candidate for attribute 'noreturn'",
6005 type, entity->base.symbol);
6009 assert(current_parent == NULL);
6010 assert(current_function == function);
6011 current_function = old_current_function;
6012 label_pop_to(label_stack_top);
6015 assert(scope == &function->parameters);
6017 environment_pop_to(top);
6020 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6021 source_position_t *source_position,
6022 const symbol_t *symbol)
6024 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6026 type->bitfield.base_type = base_type;
6027 type->bitfield.size_expression = size;
6030 type_t *skipped_type = skip_typeref(base_type);
6031 if (!is_type_integer(skipped_type)) {
6032 errorf(HERE, "bitfield base type '%T' is not an integer type",
6036 bit_size = skipped_type->base.size * 8;
6039 if (is_constant_expression(size)) {
6040 long v = fold_constant(size);
6043 errorf(source_position, "negative width in bit-field '%Y'",
6045 } else if (v == 0) {
6046 errorf(source_position, "zero width for bit-field '%Y'",
6048 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6049 errorf(source_position, "width of '%Y' exceeds its type",
6052 type->bitfield.bit_size = v;
6059 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6061 entity_t *iter = compound->members.entities;
6062 for( ; iter != NULL; iter = iter->base.next) {
6063 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6066 if (iter->base.symbol == NULL) {
6067 type_t *type = skip_typeref(iter->declaration.type);
6068 if (is_type_compound(type)) {
6070 = find_compound_entry(type->compound.compound, symbol);
6077 if (iter->base.symbol == symbol) {
6085 static void parse_compound_declarators(compound_t *compound,
6086 const declaration_specifiers_t *specifiers)
6091 if (token.type == ':') {
6092 source_position_t source_position = *HERE;
6095 type_t *base_type = specifiers->type;
6096 expression_t *size = parse_constant_expression();
6098 type_t *type = make_bitfield_type(base_type, size,
6099 &source_position, sym_anonymous);
6101 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6102 entity->base.namespc = NAMESPACE_NORMAL;
6103 entity->base.source_position = source_position;
6104 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6105 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6106 entity->declaration.modifiers = specifiers->modifiers;
6107 entity->declaration.type = type;
6109 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6111 assert(is_declaration(entity));
6112 type_t *orig_type = entity->declaration.type;
6113 type_t *type = skip_typeref(orig_type);
6115 if (token.type == ':') {
6116 source_position_t source_position = *HERE;
6118 expression_t *size = parse_constant_expression();
6120 type_t *bitfield_type = make_bitfield_type(orig_type, size,
6121 &source_position, entity->base.symbol);
6122 entity->declaration.type = bitfield_type;
6124 /* TODO we ignore arrays for now... what is missing is a check
6125 * that they're at the end of the struct */
6126 if (is_type_incomplete(type) && !is_type_array(type)) {
6128 "compound member '%Y' has incomplete type '%T'",
6129 entity->base.symbol, orig_type);
6130 } else if (is_type_function(type)) {
6131 errorf(HERE, "compound member '%Y' must not have function type '%T'",
6132 entity->base.symbol, orig_type);
6137 /* make sure we don't define a symbol multiple times */
6138 symbol_t *symbol = entity->base.symbol;
6139 if (symbol != NULL) {
6140 entity_t *prev = find_compound_entry(compound, symbol);
6143 assert(prev->base.symbol == symbol);
6144 errorf(&entity->base.source_position,
6145 "multiple declarations of symbol '%Y' (declared %P)",
6146 symbol, &prev->base.source_position);
6150 append_entity(&compound->members, entity);
6152 if (token.type != ',')
6162 static void parse_compound_type_entries(compound_t *compound)
6165 add_anchor_token('}');
6167 while (token.type != '}') {
6168 if (token.type == T_EOF) {
6169 errorf(HERE, "EOF while parsing struct");
6172 declaration_specifiers_t specifiers;
6173 memset(&specifiers, 0, sizeof(specifiers));
6174 parse_declaration_specifiers(&specifiers);
6176 parse_compound_declarators(compound, &specifiers);
6178 rem_anchor_token('}');
6182 static type_t *parse_typename(void)
6184 declaration_specifiers_t specifiers;
6185 memset(&specifiers, 0, sizeof(specifiers));
6186 parse_declaration_specifiers(&specifiers);
6187 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6188 /* TODO: improve error message, user does probably not know what a
6189 * storage class is...
6191 errorf(HERE, "typename may not have a storage class");
6194 type_t *result = parse_abstract_declarator(specifiers.type);
6202 typedef expression_t* (*parse_expression_function)(void);
6203 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6205 typedef struct expression_parser_function_t expression_parser_function_t;
6206 struct expression_parser_function_t {
6207 parse_expression_function parser;
6208 unsigned infix_precedence;
6209 parse_expression_infix_function infix_parser;
6212 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6215 * Prints an error message if an expression was expected but not read
6217 static expression_t *expected_expression_error(void)
6219 /* skip the error message if the error token was read */
6220 if (token.type != T_ERROR) {
6221 errorf(HERE, "expected expression, got token '%K'", &token);
6225 return create_invalid_expression();
6229 * Parse a string constant.
6231 static expression_t *parse_string_const(void)
6234 if (token.type == T_STRING_LITERAL) {
6235 string_t res = token.v.string;
6237 while (token.type == T_STRING_LITERAL) {
6238 res = concat_strings(&res, &token.v.string);
6241 if (token.type != T_WIDE_STRING_LITERAL) {
6242 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6243 /* note: that we use type_char_ptr here, which is already the
6244 * automatic converted type. revert_automatic_type_conversion
6245 * will construct the array type */
6246 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6247 cnst->string.value = res;
6251 wres = concat_string_wide_string(&res, &token.v.wide_string);
6253 wres = token.v.wide_string;
6258 switch (token.type) {
6259 case T_WIDE_STRING_LITERAL:
6260 wres = concat_wide_strings(&wres, &token.v.wide_string);
6263 case T_STRING_LITERAL:
6264 wres = concat_wide_string_string(&wres, &token.v.string);
6268 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6269 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6270 cnst->wide_string.value = wres;
6279 * Parse an integer constant.
6281 static expression_t *parse_int_const(void)
6283 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6284 cnst->base.source_position = *HERE;
6285 cnst->base.type = token.datatype;
6286 cnst->conste.v.int_value = token.v.intvalue;
6294 * Parse a character constant.
6296 static expression_t *parse_character_constant(void)
6298 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6300 cnst->base.source_position = *HERE;
6301 cnst->base.type = token.datatype;
6302 cnst->conste.v.character = token.v.string;
6304 if (cnst->conste.v.character.size != 1) {
6305 if (warning.multichar && GNU_MODE) {
6306 warningf(HERE, "multi-character character constant");
6308 errorf(HERE, "more than 1 characters in character constant");
6317 * Parse a wide character constant.
6319 static expression_t *parse_wide_character_constant(void)
6321 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6323 cnst->base.source_position = *HERE;
6324 cnst->base.type = token.datatype;
6325 cnst->conste.v.wide_character = token.v.wide_string;
6327 if (cnst->conste.v.wide_character.size != 1) {
6328 if (warning.multichar && GNU_MODE) {
6329 warningf(HERE, "multi-character character constant");
6331 errorf(HERE, "more than 1 characters in character constant");
6340 * Parse a float constant.
6342 static expression_t *parse_float_const(void)
6344 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6345 cnst->base.type = token.datatype;
6346 cnst->conste.v.float_value = token.v.floatvalue;
6353 static entity_t *create_implicit_function(symbol_t *symbol,
6354 const source_position_t *source_position)
6356 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6357 ntype->function.return_type = type_int;
6358 ntype->function.unspecified_parameters = true;
6360 type_t *type = typehash_insert(ntype);
6361 if (type != ntype) {
6365 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6366 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6367 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6368 entity->declaration.type = type;
6369 entity->declaration.implicit = true;
6370 entity->base.symbol = symbol;
6371 entity->base.source_position = *source_position;
6373 bool strict_prototypes_old = warning.strict_prototypes;
6374 warning.strict_prototypes = false;
6375 record_entity(entity, false);
6376 warning.strict_prototypes = strict_prototypes_old;
6382 * Creates a return_type (func)(argument_type) function type if not
6385 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6386 type_t *argument_type2)
6388 function_parameter_t *parameter2
6389 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6390 memset(parameter2, 0, sizeof(parameter2[0]));
6391 parameter2->type = argument_type2;
6393 function_parameter_t *parameter1
6394 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6395 memset(parameter1, 0, sizeof(parameter1[0]));
6396 parameter1->type = argument_type1;
6397 parameter1->next = parameter2;
6399 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6400 type->function.return_type = return_type;
6401 type->function.parameters = parameter1;
6403 type_t *result = typehash_insert(type);
6404 if (result != type) {
6412 * Creates a return_type (func)(argument_type) function type if not
6415 * @param return_type the return type
6416 * @param argument_type the argument type
6418 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6420 function_parameter_t *parameter
6421 = obstack_alloc(type_obst, sizeof(parameter[0]));
6422 memset(parameter, 0, sizeof(parameter[0]));
6423 parameter->type = argument_type;
6425 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6426 type->function.return_type = return_type;
6427 type->function.parameters = parameter;
6429 type_t *result = typehash_insert(type);
6430 if (result != type) {
6437 static type_t *make_function_0_type(type_t *return_type)
6439 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6440 type->function.return_type = return_type;
6441 type->function.parameters = NULL;
6443 type_t *result = typehash_insert(type);
6444 if (result != type) {
6452 * Creates a function type for some function like builtins.
6454 * @param symbol the symbol describing the builtin
6456 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6458 switch (symbol->ID) {
6459 case T___builtin_alloca:
6460 return make_function_1_type(type_void_ptr, type_size_t);
6461 case T___builtin_huge_val:
6462 return make_function_0_type(type_double);
6463 case T___builtin_inf:
6464 return make_function_0_type(type_double);
6465 case T___builtin_inff:
6466 return make_function_0_type(type_float);
6467 case T___builtin_infl:
6468 return make_function_0_type(type_long_double);
6469 case T___builtin_nan:
6470 return make_function_1_type(type_double, type_char_ptr);
6471 case T___builtin_nanf:
6472 return make_function_1_type(type_float, type_char_ptr);
6473 case T___builtin_nanl:
6474 return make_function_1_type(type_long_double, type_char_ptr);
6475 case T___builtin_va_end:
6476 return make_function_1_type(type_void, type_valist);
6477 case T___builtin_expect:
6478 return make_function_2_type(type_long, type_long, type_long);
6480 internal_errorf(HERE, "not implemented builtin symbol found");
6485 * Performs automatic type cast as described in § 6.3.2.1.
6487 * @param orig_type the original type
6489 static type_t *automatic_type_conversion(type_t *orig_type)
6491 type_t *type = skip_typeref(orig_type);
6492 if (is_type_array(type)) {
6493 array_type_t *array_type = &type->array;
6494 type_t *element_type = array_type->element_type;
6495 unsigned qualifiers = array_type->base.qualifiers;
6497 return make_pointer_type(element_type, qualifiers);
6500 if (is_type_function(type)) {
6501 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6508 * reverts the automatic casts of array to pointer types and function
6509 * to function-pointer types as defined § 6.3.2.1
6511 type_t *revert_automatic_type_conversion(const expression_t *expression)
6513 switch (expression->kind) {
6514 case EXPR_REFERENCE: {
6515 entity_t *entity = expression->reference.entity;
6516 if (is_declaration(entity)) {
6517 return entity->declaration.type;
6518 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6519 return entity->enum_value.enum_type;
6521 panic("no declaration or enum in reference");
6526 entity_t *entity = expression->select.compound_entry;
6527 assert(is_declaration(entity));
6528 type_t *type = entity->declaration.type;
6529 return get_qualified_type(type,
6530 expression->base.type->base.qualifiers);
6533 case EXPR_UNARY_DEREFERENCE: {
6534 const expression_t *const value = expression->unary.value;
6535 type_t *const type = skip_typeref(value->base.type);
6536 assert(is_type_pointer(type));
6537 return type->pointer.points_to;
6540 case EXPR_BUILTIN_SYMBOL:
6541 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6543 case EXPR_ARRAY_ACCESS: {
6544 const expression_t *array_ref = expression->array_access.array_ref;
6545 type_t *type_left = skip_typeref(array_ref->base.type);
6546 if (!is_type_valid(type_left))
6548 assert(is_type_pointer(type_left));
6549 return type_left->pointer.points_to;
6552 case EXPR_STRING_LITERAL: {
6553 size_t size = expression->string.value.size;
6554 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6557 case EXPR_WIDE_STRING_LITERAL: {
6558 size_t size = expression->wide_string.value.size;
6559 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6562 case EXPR_COMPOUND_LITERAL:
6563 return expression->compound_literal.type;
6568 return expression->base.type;
6571 static expression_t *parse_reference(void)
6573 symbol_t *const symbol = token.v.symbol;
6575 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6577 if (entity == NULL) {
6578 if (!strict_mode && look_ahead(1)->type == '(') {
6579 /* an implicitly declared function */
6580 if (warning.implicit_function_declaration) {
6581 warningf(HERE, "implicit declaration of function '%Y'",
6585 entity = create_implicit_function(symbol, HERE);
6587 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6588 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6594 if (is_declaration(entity)) {
6595 orig_type = entity->declaration.type;
6596 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6597 orig_type = entity->enum_value.enum_type;
6599 panic("expected declaration or enum value in reference");
6602 /* we always do the auto-type conversions; the & and sizeof parser contains
6603 * code to revert this! */
6604 type_t *type = automatic_type_conversion(orig_type);
6606 expression_kind_t kind = EXPR_REFERENCE;
6607 if (entity->kind == ENTITY_ENUM_VALUE)
6608 kind = EXPR_REFERENCE_ENUM_VALUE;
6610 expression_t *expression = allocate_expression_zero(kind);
6611 expression->reference.entity = entity;
6612 expression->base.type = type;
6614 /* this declaration is used */
6615 if (is_declaration(entity)) {
6616 entity->declaration.used = true;
6619 if (entity->base.parent_scope != file_scope
6620 && entity->base.parent_scope->depth < current_function->parameters.depth
6621 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6622 if (entity->kind == ENTITY_VARIABLE) {
6623 /* access of a variable from an outer function */
6624 entity->variable.address_taken = true;
6626 current_function->need_closure = true;
6629 /* check for deprecated functions */
6630 if (warning.deprecated_declarations
6631 && is_declaration(entity)
6632 && entity->declaration.modifiers & DM_DEPRECATED) {
6633 declaration_t *declaration = &entity->declaration;
6635 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6636 "function" : "variable";
6638 if (declaration->deprecated_string != NULL) {
6639 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6640 prefix, entity->base.symbol, &entity->base.source_position,
6641 declaration->deprecated_string);
6643 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6644 entity->base.symbol, &entity->base.source_position);
6648 if (warning.init_self && entity == current_init_decl && !in_type_prop
6649 && entity->kind == ENTITY_VARIABLE) {
6650 current_init_decl = NULL;
6651 warningf(HERE, "variable '%#T' is initialized by itself",
6652 entity->declaration.type, entity->base.symbol);
6659 static bool semantic_cast(expression_t *cast)
6661 expression_t *expression = cast->unary.value;
6662 type_t *orig_dest_type = cast->base.type;
6663 type_t *orig_type_right = expression->base.type;
6664 type_t const *dst_type = skip_typeref(orig_dest_type);
6665 type_t const *src_type = skip_typeref(orig_type_right);
6666 source_position_t const *pos = &cast->base.source_position;
6668 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6669 if (dst_type == type_void)
6672 /* only integer and pointer can be casted to pointer */
6673 if (is_type_pointer(dst_type) &&
6674 !is_type_pointer(src_type) &&
6675 !is_type_integer(src_type) &&
6676 is_type_valid(src_type)) {
6677 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6681 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6682 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6686 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6687 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6691 if (warning.cast_qual &&
6692 is_type_pointer(src_type) &&
6693 is_type_pointer(dst_type)) {
6694 type_t *src = skip_typeref(src_type->pointer.points_to);
6695 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6696 unsigned missing_qualifiers =
6697 src->base.qualifiers & ~dst->base.qualifiers;
6698 if (missing_qualifiers != 0) {
6700 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6701 missing_qualifiers, orig_type_right);
6707 static expression_t *parse_compound_literal(type_t *type)
6709 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6711 parse_initializer_env_t env;
6714 env.must_be_constant = false;
6715 initializer_t *initializer = parse_initializer(&env);
6718 expression->compound_literal.initializer = initializer;
6719 expression->compound_literal.type = type;
6720 expression->base.type = automatic_type_conversion(type);
6726 * Parse a cast expression.
6728 static expression_t *parse_cast(void)
6730 add_anchor_token(')');
6732 source_position_t source_position = token.source_position;
6734 type_t *type = parse_typename();
6736 rem_anchor_token(')');
6739 if (token.type == '{') {
6740 return parse_compound_literal(type);
6743 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6744 cast->base.source_position = source_position;
6746 expression_t *value = parse_sub_expression(PREC_CAST);
6747 cast->base.type = type;
6748 cast->unary.value = value;
6750 if (! semantic_cast(cast)) {
6751 /* TODO: record the error in the AST. else it is impossible to detect it */
6756 return create_invalid_expression();
6760 * Parse a statement expression.
6762 static expression_t *parse_statement_expression(void)
6764 add_anchor_token(')');
6766 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6768 statement_t *statement = parse_compound_statement(true);
6769 expression->statement.statement = statement;
6770 expression->base.source_position = statement->base.source_position;
6772 /* find last statement and use its type */
6773 type_t *type = type_void;
6774 const statement_t *stmt = statement->compound.statements;
6776 while (stmt->base.next != NULL)
6777 stmt = stmt->base.next;
6779 if (stmt->kind == STATEMENT_EXPRESSION) {
6780 type = stmt->expression.expression->base.type;
6782 } else if (warning.other) {
6783 warningf(&expression->base.source_position, "empty statement expression ({})");
6785 expression->base.type = type;
6787 rem_anchor_token(')');
6795 * Parse a parenthesized expression.
6797 static expression_t *parse_parenthesized_expression(void)
6801 switch (token.type) {
6803 /* gcc extension: a statement expression */
6804 return parse_statement_expression();
6808 return parse_cast();
6810 if (is_typedef_symbol(token.v.symbol)) {
6811 return parse_cast();
6815 add_anchor_token(')');
6816 expression_t *result = parse_expression();
6817 rem_anchor_token(')');
6824 static expression_t *parse_function_keyword(void)
6829 if (current_function == NULL) {
6830 errorf(HERE, "'__func__' used outside of a function");
6833 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6834 expression->base.type = type_char_ptr;
6835 expression->funcname.kind = FUNCNAME_FUNCTION;
6840 static expression_t *parse_pretty_function_keyword(void)
6842 eat(T___PRETTY_FUNCTION__);
6844 if (current_function == NULL) {
6845 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6848 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6849 expression->base.type = type_char_ptr;
6850 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6855 static expression_t *parse_funcsig_keyword(void)
6859 if (current_function == NULL) {
6860 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6863 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6864 expression->base.type = type_char_ptr;
6865 expression->funcname.kind = FUNCNAME_FUNCSIG;
6870 static expression_t *parse_funcdname_keyword(void)
6872 eat(T___FUNCDNAME__);
6874 if (current_function == NULL) {
6875 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6878 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6879 expression->base.type = type_char_ptr;
6880 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6885 static designator_t *parse_designator(void)
6887 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6888 result->source_position = *HERE;
6890 if (token.type != T_IDENTIFIER) {
6891 parse_error_expected("while parsing member designator",
6892 T_IDENTIFIER, NULL);
6895 result->symbol = token.v.symbol;
6898 designator_t *last_designator = result;
6900 if (token.type == '.') {
6902 if (token.type != T_IDENTIFIER) {
6903 parse_error_expected("while parsing member designator",
6904 T_IDENTIFIER, NULL);
6907 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6908 designator->source_position = *HERE;
6909 designator->symbol = token.v.symbol;
6912 last_designator->next = designator;
6913 last_designator = designator;
6916 if (token.type == '[') {
6918 add_anchor_token(']');
6919 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6920 designator->source_position = *HERE;
6921 designator->array_index = parse_expression();
6922 rem_anchor_token(']');
6924 if (designator->array_index == NULL) {
6928 last_designator->next = designator;
6929 last_designator = designator;
6941 * Parse the __builtin_offsetof() expression.
6943 static expression_t *parse_offsetof(void)
6945 eat(T___builtin_offsetof);
6947 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6948 expression->base.type = type_size_t;
6951 add_anchor_token(',');
6952 type_t *type = parse_typename();
6953 rem_anchor_token(',');
6955 add_anchor_token(')');
6956 designator_t *designator = parse_designator();
6957 rem_anchor_token(')');
6960 expression->offsetofe.type = type;
6961 expression->offsetofe.designator = designator;
6964 memset(&path, 0, sizeof(path));
6965 path.top_type = type;
6966 path.path = NEW_ARR_F(type_path_entry_t, 0);
6968 descend_into_subtype(&path);
6970 if (!walk_designator(&path, designator, true)) {
6971 return create_invalid_expression();
6974 DEL_ARR_F(path.path);
6978 return create_invalid_expression();
6982 * Parses a _builtin_va_start() expression.
6984 static expression_t *parse_va_start(void)
6986 eat(T___builtin_va_start);
6988 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6991 add_anchor_token(',');
6992 expression->va_starte.ap = parse_assignment_expression();
6993 rem_anchor_token(',');
6995 expression_t *const expr = parse_assignment_expression();
6996 if (expr->kind == EXPR_REFERENCE) {
6997 entity_t *const entity = expr->reference.entity;
6998 if (entity->base.parent_scope != ¤t_function->parameters
6999 || entity->base.next != NULL
7000 || entity->kind != ENTITY_VARIABLE) {
7001 errorf(&expr->base.source_position,
7002 "second argument of 'va_start' must be last parameter of the current function");
7004 expression->va_starte.parameter = &entity->variable;
7011 return create_invalid_expression();
7015 * Parses a _builtin_va_arg() expression.
7017 static expression_t *parse_va_arg(void)
7019 eat(T___builtin_va_arg);
7021 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7024 expression->va_arge.ap = parse_assignment_expression();
7026 expression->base.type = parse_typename();
7031 return create_invalid_expression();
7034 static expression_t *parse_builtin_symbol(void)
7036 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7038 symbol_t *symbol = token.v.symbol;
7040 expression->builtin_symbol.symbol = symbol;
7043 type_t *type = get_builtin_symbol_type(symbol);
7044 type = automatic_type_conversion(type);
7046 expression->base.type = type;
7051 * Parses a __builtin_constant() expression.
7053 static expression_t *parse_builtin_constant(void)
7055 eat(T___builtin_constant_p);
7057 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7060 add_anchor_token(')');
7061 expression->builtin_constant.value = parse_assignment_expression();
7062 rem_anchor_token(')');
7064 expression->base.type = type_int;
7068 return create_invalid_expression();
7072 * Parses a __builtin_prefetch() expression.
7074 static expression_t *parse_builtin_prefetch(void)
7076 eat(T___builtin_prefetch);
7078 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7081 add_anchor_token(')');
7082 expression->builtin_prefetch.adr = parse_assignment_expression();
7083 if (token.type == ',') {
7085 expression->builtin_prefetch.rw = parse_assignment_expression();
7087 if (token.type == ',') {
7089 expression->builtin_prefetch.locality = parse_assignment_expression();
7091 rem_anchor_token(')');
7093 expression->base.type = type_void;
7097 return create_invalid_expression();
7101 * Parses a __builtin_is_*() compare expression.
7103 static expression_t *parse_compare_builtin(void)
7105 expression_t *expression;
7107 switch (token.type) {
7108 case T___builtin_isgreater:
7109 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7111 case T___builtin_isgreaterequal:
7112 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7114 case T___builtin_isless:
7115 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7117 case T___builtin_islessequal:
7118 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7120 case T___builtin_islessgreater:
7121 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7123 case T___builtin_isunordered:
7124 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7127 internal_errorf(HERE, "invalid compare builtin found");
7129 expression->base.source_position = *HERE;
7133 expression->binary.left = parse_assignment_expression();
7135 expression->binary.right = parse_assignment_expression();
7138 type_t *const orig_type_left = expression->binary.left->base.type;
7139 type_t *const orig_type_right = expression->binary.right->base.type;
7141 type_t *const type_left = skip_typeref(orig_type_left);
7142 type_t *const type_right = skip_typeref(orig_type_right);
7143 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7144 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7145 type_error_incompatible("invalid operands in comparison",
7146 &expression->base.source_position, orig_type_left, orig_type_right);
7149 semantic_comparison(&expression->binary);
7154 return create_invalid_expression();
7159 * Parses a __builtin_expect() expression.
7161 static expression_t *parse_builtin_expect(void)
7163 eat(T___builtin_expect);
7165 expression_t *expression
7166 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7169 expression->binary.left = parse_assignment_expression();
7171 expression->binary.right = parse_constant_expression();
7174 expression->base.type = expression->binary.left->base.type;
7178 return create_invalid_expression();
7183 * Parses a MS assume() expression.
7185 static expression_t *parse_assume(void)
7189 expression_t *expression
7190 = allocate_expression_zero(EXPR_UNARY_ASSUME);
7193 add_anchor_token(')');
7194 expression->unary.value = parse_assignment_expression();
7195 rem_anchor_token(')');
7198 expression->base.type = type_void;
7201 return create_invalid_expression();
7205 * Return the declaration for a given label symbol or create a new one.
7207 * @param symbol the symbol of the label
7209 static label_t *get_label(symbol_t *symbol)
7212 assert(current_function != NULL);
7214 label = get_entity(symbol, NAMESPACE_LOCAL_LABEL);
7215 /* if we found a local label, we already created the declaration */
7216 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7217 if (label->base.parent_scope != scope) {
7218 assert(label->base.parent_scope->depth < scope->depth);
7219 current_function->goto_to_outer = true;
7221 return &label->label;
7224 label = get_entity(symbol, NAMESPACE_LABEL);
7225 /* if we found a label in the same function, then we already created the
7228 && label->base.parent_scope == ¤t_function->parameters) {
7229 return &label->label;
7232 /* otherwise we need to create a new one */
7233 label = allocate_entity_zero(ENTITY_LABEL);
7234 label->base.namespc = NAMESPACE_LABEL;
7235 label->base.symbol = symbol;
7239 return &label->label;
7243 * Parses a GNU && label address expression.
7245 static expression_t *parse_label_address(void)
7247 source_position_t source_position = token.source_position;
7249 if (token.type != T_IDENTIFIER) {
7250 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7253 symbol_t *symbol = token.v.symbol;
7256 label_t *label = get_label(symbol);
7258 label->address_taken = true;
7260 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7261 expression->base.source_position = source_position;
7263 /* label address is threaten as a void pointer */
7264 expression->base.type = type_void_ptr;
7265 expression->label_address.label = label;
7268 return create_invalid_expression();
7272 * Parse a microsoft __noop expression.
7274 static expression_t *parse_noop_expression(void)
7276 source_position_t source_position = *HERE;
7279 if (token.type == '(') {
7280 /* parse arguments */
7282 add_anchor_token(')');
7283 add_anchor_token(',');
7285 if (token.type != ')') {
7287 (void)parse_assignment_expression();
7288 if (token.type != ',')
7294 rem_anchor_token(',');
7295 rem_anchor_token(')');
7298 /* the result is a (int)0 */
7299 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7300 cnst->base.source_position = source_position;
7301 cnst->base.type = type_int;
7302 cnst->conste.v.int_value = 0;
7303 cnst->conste.is_ms_noop = true;
7308 return create_invalid_expression();
7312 * Parses a primary expression.
7314 static expression_t *parse_primary_expression(void)
7316 switch (token.type) {
7317 case T_INTEGER: return parse_int_const();
7318 case T_CHARACTER_CONSTANT: return parse_character_constant();
7319 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7320 case T_FLOATINGPOINT: return parse_float_const();
7321 case T_STRING_LITERAL:
7322 case T_WIDE_STRING_LITERAL: return parse_string_const();
7323 case T_IDENTIFIER: return parse_reference();
7324 case T___FUNCTION__:
7325 case T___func__: return parse_function_keyword();
7326 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7327 case T___FUNCSIG__: return parse_funcsig_keyword();
7328 case T___FUNCDNAME__: return parse_funcdname_keyword();
7329 case T___builtin_offsetof: return parse_offsetof();
7330 case T___builtin_va_start: return parse_va_start();
7331 case T___builtin_va_arg: return parse_va_arg();
7332 case T___builtin_expect:
7333 case T___builtin_alloca:
7334 case T___builtin_inf:
7335 case T___builtin_inff:
7336 case T___builtin_infl:
7337 case T___builtin_nan:
7338 case T___builtin_nanf:
7339 case T___builtin_nanl:
7340 case T___builtin_huge_val:
7341 case T___builtin_va_end: return parse_builtin_symbol();
7342 case T___builtin_isgreater:
7343 case T___builtin_isgreaterequal:
7344 case T___builtin_isless:
7345 case T___builtin_islessequal:
7346 case T___builtin_islessgreater:
7347 case T___builtin_isunordered: return parse_compare_builtin();
7348 case T___builtin_constant_p: return parse_builtin_constant();
7349 case T___builtin_prefetch: return parse_builtin_prefetch();
7350 case T__assume: return parse_assume();
7353 return parse_label_address();
7356 case '(': return parse_parenthesized_expression();
7357 case T___noop: return parse_noop_expression();
7360 errorf(HERE, "unexpected token %K, expected an expression", &token);
7361 return create_invalid_expression();
7365 * Check if the expression has the character type and issue a warning then.
7367 static void check_for_char_index_type(const expression_t *expression)
7369 type_t *const type = expression->base.type;
7370 const type_t *const base_type = skip_typeref(type);
7372 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7373 warning.char_subscripts) {
7374 warningf(&expression->base.source_position,
7375 "array subscript has type '%T'", type);
7379 static expression_t *parse_array_expression(expression_t *left)
7382 add_anchor_token(']');
7384 expression_t *inside = parse_expression();
7386 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7388 array_access_expression_t *array_access = &expression->array_access;
7390 type_t *const orig_type_left = left->base.type;
7391 type_t *const orig_type_inside = inside->base.type;
7393 type_t *const type_left = skip_typeref(orig_type_left);
7394 type_t *const type_inside = skip_typeref(orig_type_inside);
7396 type_t *return_type;
7397 if (is_type_pointer(type_left)) {
7398 return_type = type_left->pointer.points_to;
7399 array_access->array_ref = left;
7400 array_access->index = inside;
7401 check_for_char_index_type(inside);
7402 } else if (is_type_pointer(type_inside)) {
7403 return_type = type_inside->pointer.points_to;
7404 array_access->array_ref = inside;
7405 array_access->index = left;
7406 array_access->flipped = true;
7407 check_for_char_index_type(left);
7409 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7411 "array access on object with non-pointer types '%T', '%T'",
7412 orig_type_left, orig_type_inside);
7414 return_type = type_error_type;
7415 array_access->array_ref = left;
7416 array_access->index = inside;
7419 expression->base.type = automatic_type_conversion(return_type);
7421 rem_anchor_token(']');
7422 if (token.type == ']') {
7425 parse_error_expected("Problem while parsing array access", ']', NULL);
7430 static expression_t *parse_typeprop(expression_kind_t const kind,
7431 source_position_t const pos)
7433 expression_t *tp_expression = allocate_expression_zero(kind);
7434 tp_expression->base.type = type_size_t;
7435 tp_expression->base.source_position = pos;
7437 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7439 /* we only refer to a type property, mark this case */
7440 bool old = in_type_prop;
7441 in_type_prop = true;
7444 expression_t *expression;
7445 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7447 add_anchor_token(')');
7448 orig_type = parse_typename();
7449 rem_anchor_token(')');
7452 if (token.type == '{') {
7453 /* It was not sizeof(type) after all. It is sizeof of an expression
7454 * starting with a compound literal */
7455 expression = parse_compound_literal(orig_type);
7456 goto typeprop_expression;
7459 expression = parse_sub_expression(PREC_UNARY);
7461 typeprop_expression:
7462 tp_expression->typeprop.tp_expression = expression;
7464 orig_type = revert_automatic_type_conversion(expression);
7465 expression->base.type = orig_type;
7468 tp_expression->typeprop.type = orig_type;
7469 type_t const* const type = skip_typeref(orig_type);
7470 char const* const wrong_type =
7471 is_type_incomplete(type) ? "incomplete" :
7472 type->kind == TYPE_FUNCTION ? "function designator" :
7473 type->kind == TYPE_BITFIELD ? "bitfield" :
7475 if (wrong_type != NULL) {
7476 errorf(&pos, "operand of %s expression must not be of %s type '%T'",
7477 what, wrong_type, orig_type);
7482 return tp_expression;
7485 static expression_t *parse_sizeof(void)
7487 source_position_t pos = *HERE;
7489 return parse_typeprop(EXPR_SIZEOF, pos);
7492 static expression_t *parse_alignof(void)
7494 source_position_t pos = *HERE;
7496 return parse_typeprop(EXPR_ALIGNOF, pos);
7499 static expression_t *parse_select_expression(expression_t *compound)
7501 assert(token.type == '.' || token.type == T_MINUSGREATER);
7503 bool is_pointer = (token.type == T_MINUSGREATER);
7506 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7507 select->select.compound = compound;
7509 if (token.type != T_IDENTIFIER) {
7510 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7513 symbol_t *symbol = token.v.symbol;
7516 type_t *const orig_type = compound->base.type;
7517 type_t *const type = skip_typeref(orig_type);
7520 bool saw_error = false;
7521 if (is_type_pointer(type)) {
7524 "request for member '%Y' in something not a struct or union, but '%T'",
7528 type_left = skip_typeref(type->pointer.points_to);
7530 if (is_pointer && is_type_valid(type)) {
7531 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7538 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7539 type_left->kind == TYPE_COMPOUND_UNION) {
7540 compound_t *compound = type_left->compound.compound;
7542 if (!compound->complete) {
7543 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7545 goto create_error_entry;
7548 entry = find_compound_entry(compound, symbol);
7549 if (entry == NULL) {
7550 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7551 goto create_error_entry;
7554 if (is_type_valid(type_left) && !saw_error) {
7556 "request for member '%Y' in something not a struct or union, but '%T'",
7560 return create_invalid_expression();
7563 assert(is_declaration(entry));
7564 select->select.compound_entry = entry;
7566 type_t *entry_type = entry->declaration.type;
7568 = get_qualified_type(entry_type, type_left->base.qualifiers);
7570 /* we always do the auto-type conversions; the & and sizeof parser contains
7571 * code to revert this! */
7572 select->base.type = automatic_type_conversion(res_type);
7574 type_t *skipped = skip_typeref(res_type);
7575 if (skipped->kind == TYPE_BITFIELD) {
7576 select->base.type = skipped->bitfield.base_type;
7582 static void check_call_argument(const function_parameter_t *parameter,
7583 call_argument_t *argument, unsigned pos)
7585 type_t *expected_type = parameter->type;
7586 type_t *expected_type_skip = skip_typeref(expected_type);
7587 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7588 expression_t *arg_expr = argument->expression;
7589 type_t *arg_type = skip_typeref(arg_expr->base.type);
7591 /* handle transparent union gnu extension */
7592 if (is_type_union(expected_type_skip)
7593 && (expected_type_skip->base.modifiers
7594 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7595 compound_t *union_decl = expected_type_skip->compound.compound;
7596 type_t *best_type = NULL;
7597 entity_t *entry = union_decl->members.entities;
7598 for ( ; entry != NULL; entry = entry->base.next) {
7599 assert(is_declaration(entry));
7600 type_t *decl_type = entry->declaration.type;
7601 error = semantic_assign(decl_type, arg_expr);
7602 if (error == ASSIGN_ERROR_INCOMPATIBLE
7603 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7606 if (error == ASSIGN_SUCCESS) {
7607 best_type = decl_type;
7608 } else if (best_type == NULL) {
7609 best_type = decl_type;
7613 if (best_type != NULL) {
7614 expected_type = best_type;
7618 error = semantic_assign(expected_type, arg_expr);
7619 argument->expression = create_implicit_cast(argument->expression,
7622 if (error != ASSIGN_SUCCESS) {
7623 /* report exact scope in error messages (like "in argument 3") */
7625 snprintf(buf, sizeof(buf), "call argument %u", pos);
7626 report_assign_error(error, expected_type, arg_expr, buf,
7627 &arg_expr->base.source_position);
7628 } else if (warning.traditional || warning.conversion) {
7629 type_t *const promoted_type = get_default_promoted_type(arg_type);
7630 if (!types_compatible(expected_type_skip, promoted_type) &&
7631 !types_compatible(expected_type_skip, type_void_ptr) &&
7632 !types_compatible(type_void_ptr, promoted_type)) {
7633 /* Deliberately show the skipped types in this warning */
7634 warningf(&arg_expr->base.source_position,
7635 "passing call argument %u as '%T' rather than '%T' due to prototype",
7636 pos, expected_type_skip, promoted_type);
7642 * Parse a call expression, ie. expression '( ... )'.
7644 * @param expression the function address
7646 static expression_t *parse_call_expression(expression_t *expression)
7648 expression_t *result = allocate_expression_zero(EXPR_CALL);
7649 result->base.source_position = expression->base.source_position;
7651 call_expression_t *call = &result->call;
7652 call->function = expression;
7654 type_t *const orig_type = expression->base.type;
7655 type_t *const type = skip_typeref(orig_type);
7657 function_type_t *function_type = NULL;
7658 if (is_type_pointer(type)) {
7659 type_t *const to_type = skip_typeref(type->pointer.points_to);
7661 if (is_type_function(to_type)) {
7662 function_type = &to_type->function;
7663 call->base.type = function_type->return_type;
7667 if (function_type == NULL && is_type_valid(type)) {
7668 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7671 /* parse arguments */
7673 add_anchor_token(')');
7674 add_anchor_token(',');
7676 if (token.type != ')') {
7677 call_argument_t *last_argument = NULL;
7680 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7682 argument->expression = parse_assignment_expression();
7683 if (last_argument == NULL) {
7684 call->arguments = argument;
7686 last_argument->next = argument;
7688 last_argument = argument;
7690 if (token.type != ',')
7695 rem_anchor_token(',');
7696 rem_anchor_token(')');
7699 if (function_type == NULL)
7702 function_parameter_t *parameter = function_type->parameters;
7703 call_argument_t *argument = call->arguments;
7704 if (!function_type->unspecified_parameters) {
7705 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7706 parameter = parameter->next, argument = argument->next) {
7707 check_call_argument(parameter, argument, ++pos);
7710 if (parameter != NULL) {
7711 errorf(HERE, "too few arguments to function '%E'", expression);
7712 } else if (argument != NULL && !function_type->variadic) {
7713 errorf(HERE, "too many arguments to function '%E'", expression);
7717 /* do default promotion */
7718 for( ; argument != NULL; argument = argument->next) {
7719 type_t *type = argument->expression->base.type;
7721 type = get_default_promoted_type(type);
7723 argument->expression
7724 = create_implicit_cast(argument->expression, type);
7727 check_format(&result->call);
7729 if (warning.aggregate_return &&
7730 is_type_compound(skip_typeref(function_type->return_type))) {
7731 warningf(&result->base.source_position,
7732 "function call has aggregate value");
7739 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7741 static bool same_compound_type(const type_t *type1, const type_t *type2)
7744 is_type_compound(type1) &&
7745 type1->kind == type2->kind &&
7746 type1->compound.compound == type2->compound.compound;
7750 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7752 * @param expression the conditional expression
7754 static expression_t *parse_conditional_expression(expression_t *expression)
7756 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7758 conditional_expression_t *conditional = &result->conditional;
7759 conditional->base.source_position = *HERE;
7760 conditional->condition = expression;
7763 add_anchor_token(':');
7766 type_t *const condition_type_orig = expression->base.type;
7767 type_t *const condition_type = skip_typeref(condition_type_orig);
7768 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7769 type_error("expected a scalar type in conditional condition",
7770 &expression->base.source_position, condition_type_orig);
7773 expression_t *true_expression = expression;
7774 bool gnu_cond = false;
7775 if (GNU_MODE && token.type == ':') {
7778 true_expression = parse_expression();
7780 rem_anchor_token(':');
7782 expression_t *false_expression =
7783 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7785 type_t *const orig_true_type = true_expression->base.type;
7786 type_t *const orig_false_type = false_expression->base.type;
7787 type_t *const true_type = skip_typeref(orig_true_type);
7788 type_t *const false_type = skip_typeref(orig_false_type);
7791 type_t *result_type;
7792 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7793 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7794 /* ISO/IEC 14882:1998(E) §5.16:2 */
7795 if (true_expression->kind == EXPR_UNARY_THROW) {
7796 result_type = false_type;
7797 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7798 result_type = true_type;
7800 if (warning.other && (
7801 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7802 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7804 warningf(&conditional->base.source_position,
7805 "ISO C forbids conditional expression with only one void side");
7807 result_type = type_void;
7809 } else if (is_type_arithmetic(true_type)
7810 && is_type_arithmetic(false_type)) {
7811 result_type = semantic_arithmetic(true_type, false_type);
7813 true_expression = create_implicit_cast(true_expression, result_type);
7814 false_expression = create_implicit_cast(false_expression, result_type);
7816 conditional->true_expression = true_expression;
7817 conditional->false_expression = false_expression;
7818 conditional->base.type = result_type;
7819 } else if (same_compound_type(true_type, false_type)) {
7820 /* just take 1 of the 2 types */
7821 result_type = true_type;
7822 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7823 type_t *pointer_type;
7825 expression_t *other_expression;
7826 if (is_type_pointer(true_type) &&
7827 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7828 pointer_type = true_type;
7829 other_type = false_type;
7830 other_expression = false_expression;
7832 pointer_type = false_type;
7833 other_type = true_type;
7834 other_expression = true_expression;
7837 if (is_null_pointer_constant(other_expression)) {
7838 result_type = pointer_type;
7839 } else if (is_type_pointer(other_type)) {
7840 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7841 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7844 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7845 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7847 } else if (types_compatible(get_unqualified_type(to1),
7848 get_unqualified_type(to2))) {
7851 if (warning.other) {
7852 warningf(&conditional->base.source_position,
7853 "pointer types '%T' and '%T' in conditional expression are incompatible",
7854 true_type, false_type);
7859 type_t *const type =
7860 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7861 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7862 } else if (is_type_integer(other_type)) {
7863 if (warning.other) {
7864 warningf(&conditional->base.source_position,
7865 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7867 result_type = pointer_type;
7869 if (is_type_valid(other_type)) {
7870 type_error_incompatible("while parsing conditional",
7871 &expression->base.source_position, true_type, false_type);
7873 result_type = type_error_type;
7876 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7877 type_error_incompatible("while parsing conditional",
7878 &conditional->base.source_position, true_type,
7881 result_type = type_error_type;
7884 conditional->true_expression
7885 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7886 conditional->false_expression
7887 = create_implicit_cast(false_expression, result_type);
7888 conditional->base.type = result_type;
7891 return create_invalid_expression();
7895 * Parse an extension expression.
7897 static expression_t *parse_extension(void)
7899 eat(T___extension__);
7901 bool old_gcc_extension = in_gcc_extension;
7902 in_gcc_extension = true;
7903 expression_t *expression = parse_sub_expression(PREC_UNARY);
7904 in_gcc_extension = old_gcc_extension;
7909 * Parse a __builtin_classify_type() expression.
7911 static expression_t *parse_builtin_classify_type(void)
7913 eat(T___builtin_classify_type);
7915 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7916 result->base.type = type_int;
7919 add_anchor_token(')');
7920 expression_t *expression = parse_expression();
7921 rem_anchor_token(')');
7923 result->classify_type.type_expression = expression;
7927 return create_invalid_expression();
7931 * Parse a delete expression
7932 * ISO/IEC 14882:1998(E) §5.3.5
7934 static expression_t *parse_delete(void)
7936 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7937 result->base.source_position = *HERE;
7938 result->base.type = type_void;
7942 if (token.type == '[') {
7944 result->kind = EXPR_UNARY_DELETE_ARRAY;
7949 expression_t *const value = parse_sub_expression(PREC_CAST);
7950 result->unary.value = value;
7952 type_t *const type = skip_typeref(value->base.type);
7953 if (!is_type_pointer(type)) {
7954 errorf(&value->base.source_position,
7955 "operand of delete must have pointer type");
7956 } else if (warning.other &&
7957 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7958 warningf(&value->base.source_position,
7959 "deleting 'void*' is undefined");
7966 * Parse a throw expression
7967 * ISO/IEC 14882:1998(E) §15:1
7969 static expression_t *parse_throw(void)
7971 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7972 result->base.source_position = *HERE;
7973 result->base.type = type_void;
7977 expression_t *value = NULL;
7978 switch (token.type) {
7980 value = parse_assignment_expression();
7981 /* ISO/IEC 14882:1998(E) §15.1:3 */
7982 type_t *const orig_type = value->base.type;
7983 type_t *const type = skip_typeref(orig_type);
7984 if (is_type_incomplete(type)) {
7985 errorf(&value->base.source_position,
7986 "cannot throw object of incomplete type '%T'", orig_type);
7987 } else if (is_type_pointer(type)) {
7988 type_t *const points_to = skip_typeref(type->pointer.points_to);
7989 if (is_type_incomplete(points_to) &&
7990 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7991 errorf(&value->base.source_position,
7992 "cannot throw pointer to incomplete type '%T'", orig_type);
8000 result->unary.value = value;
8005 static bool check_pointer_arithmetic(const source_position_t *source_position,
8006 type_t *pointer_type,
8007 type_t *orig_pointer_type)
8009 type_t *points_to = pointer_type->pointer.points_to;
8010 points_to = skip_typeref(points_to);
8012 if (is_type_incomplete(points_to)) {
8013 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8014 errorf(source_position,
8015 "arithmetic with pointer to incomplete type '%T' not allowed",
8018 } else if (warning.pointer_arith) {
8019 warningf(source_position,
8020 "pointer of type '%T' used in arithmetic",
8023 } else if (is_type_function(points_to)) {
8025 errorf(source_position,
8026 "arithmetic with pointer to function type '%T' not allowed",
8029 } else if (warning.pointer_arith) {
8030 warningf(source_position,
8031 "pointer to a function '%T' used in arithmetic",
8038 static bool is_lvalue(const expression_t *expression)
8040 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8041 switch (expression->kind) {
8042 case EXPR_REFERENCE:
8043 case EXPR_ARRAY_ACCESS:
8045 case EXPR_UNARY_DEREFERENCE:
8049 /* Claim it is an lvalue, if the type is invalid. There was a parse
8050 * error before, which maybe prevented properly recognizing it as
8052 return !is_type_valid(skip_typeref(expression->base.type));
8056 static void semantic_incdec(unary_expression_t *expression)
8058 type_t *const orig_type = expression->value->base.type;
8059 type_t *const type = skip_typeref(orig_type);
8060 if (is_type_pointer(type)) {
8061 if (!check_pointer_arithmetic(&expression->base.source_position,
8065 } else if (!is_type_real(type) && is_type_valid(type)) {
8066 /* TODO: improve error message */
8067 errorf(&expression->base.source_position,
8068 "operation needs an arithmetic or pointer type");
8071 if (!is_lvalue(expression->value)) {
8072 /* TODO: improve error message */
8073 errorf(&expression->base.source_position, "lvalue required as operand");
8075 expression->base.type = orig_type;
8078 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8080 type_t *const orig_type = expression->value->base.type;
8081 type_t *const type = skip_typeref(orig_type);
8082 if (!is_type_arithmetic(type)) {
8083 if (is_type_valid(type)) {
8084 /* TODO: improve error message */
8085 errorf(&expression->base.source_position,
8086 "operation needs an arithmetic type");
8091 expression->base.type = orig_type;
8094 static void semantic_unexpr_plus(unary_expression_t *expression)
8096 semantic_unexpr_arithmetic(expression);
8097 if (warning.traditional)
8098 warningf(&expression->base.source_position,
8099 "traditional C rejects the unary plus operator");
8102 static expression_t const *get_reference_address(expression_t const *expr)
8104 bool regular_take_address = true;
8106 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8107 expr = expr->unary.value;
8109 regular_take_address = false;
8112 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8115 expr = expr->unary.value;
8118 /* special case for functions which are automatically converted to a
8119 * pointer to function without an extra TAKE_ADDRESS operation */
8120 if (!regular_take_address && expr->kind == EXPR_REFERENCE
8121 && expr->reference.entity->kind == ENTITY_FUNCTION) {
8128 static void warn_function_address_as_bool(expression_t const* expr)
8130 if (!warning.address)
8133 expr = get_reference_address(expr);
8135 warningf(&expr->base.source_position,
8136 "the address of '%Y' will always evaluate as 'true'",
8137 expr->reference.entity->base.symbol);
8141 static void semantic_not(unary_expression_t *expression)
8143 type_t *const orig_type = expression->value->base.type;
8144 type_t *const type = skip_typeref(orig_type);
8145 if (!is_type_scalar(type) && is_type_valid(type)) {
8146 errorf(&expression->base.source_position,
8147 "operand of ! must be of scalar type");
8150 warn_function_address_as_bool(expression->value);
8152 expression->base.type = type_int;
8155 static void semantic_unexpr_integer(unary_expression_t *expression)
8157 type_t *const orig_type = expression->value->base.type;
8158 type_t *const type = skip_typeref(orig_type);
8159 if (!is_type_integer(type)) {
8160 if (is_type_valid(type)) {
8161 errorf(&expression->base.source_position,
8162 "operand of ~ must be of integer type");
8167 expression->base.type = orig_type;
8170 static void semantic_dereference(unary_expression_t *expression)
8172 type_t *const orig_type = expression->value->base.type;
8173 type_t *const type = skip_typeref(orig_type);
8174 if (!is_type_pointer(type)) {
8175 if (is_type_valid(type)) {
8176 errorf(&expression->base.source_position,
8177 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8182 type_t *result_type = type->pointer.points_to;
8183 result_type = automatic_type_conversion(result_type);
8184 expression->base.type = result_type;
8188 * Record that an address is taken (expression represents an lvalue).
8190 * @param expression the expression
8191 * @param may_be_register if true, the expression might be an register
8193 static void set_address_taken(expression_t *expression, bool may_be_register)
8195 if (expression->kind != EXPR_REFERENCE)
8198 entity_t *const entity = expression->reference.entity;
8200 if (entity->kind != ENTITY_VARIABLE)
8203 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8204 && !may_be_register) {
8205 errorf(&expression->base.source_position,
8206 "address of register variable '%Y' requested",
8207 entity->base.symbol);
8210 entity->variable.address_taken = true;
8214 * Check the semantic of the address taken expression.
8216 static void semantic_take_addr(unary_expression_t *expression)
8218 expression_t *value = expression->value;
8219 value->base.type = revert_automatic_type_conversion(value);
8221 type_t *orig_type = value->base.type;
8222 type_t *type = skip_typeref(orig_type);
8223 if (!is_type_valid(type))
8227 if (value->kind != EXPR_ARRAY_ACCESS
8228 && value->kind != EXPR_UNARY_DEREFERENCE
8229 && !is_lvalue(value)) {
8230 errorf(&expression->base.source_position,
8231 "'&' requires an lvalue");
8233 if (type->kind == TYPE_BITFIELD) {
8234 errorf(&expression->base.source_position,
8235 "'&' not allowed on object with bitfield type '%T'",
8239 set_address_taken(value, false);
8241 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8244 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8245 static expression_t *parse_##unexpression_type(void) \
8247 expression_t *unary_expression \
8248 = allocate_expression_zero(unexpression_type); \
8249 unary_expression->base.source_position = *HERE; \
8251 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8253 sfunc(&unary_expression->unary); \
8255 return unary_expression; \
8258 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8259 semantic_unexpr_arithmetic)
8260 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8261 semantic_unexpr_plus)
8262 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8264 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8265 semantic_dereference)
8266 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8268 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8269 semantic_unexpr_integer)
8270 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8272 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8275 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8277 static expression_t *parse_##unexpression_type(expression_t *left) \
8279 expression_t *unary_expression \
8280 = allocate_expression_zero(unexpression_type); \
8281 unary_expression->base.source_position = *HERE; \
8283 unary_expression->unary.value = left; \
8285 sfunc(&unary_expression->unary); \
8287 return unary_expression; \
8290 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8291 EXPR_UNARY_POSTFIX_INCREMENT,
8293 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8294 EXPR_UNARY_POSTFIX_DECREMENT,
8297 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8299 /* TODO: handle complex + imaginary types */
8301 type_left = get_unqualified_type(type_left);
8302 type_right = get_unqualified_type(type_right);
8304 /* § 6.3.1.8 Usual arithmetic conversions */
8305 if (type_left == type_long_double || type_right == type_long_double) {
8306 return type_long_double;
8307 } else if (type_left == type_double || type_right == type_double) {
8309 } else if (type_left == type_float || type_right == type_float) {
8313 type_left = promote_integer(type_left);
8314 type_right = promote_integer(type_right);
8316 if (type_left == type_right)
8319 bool const signed_left = is_type_signed(type_left);
8320 bool const signed_right = is_type_signed(type_right);
8321 int const rank_left = get_rank(type_left);
8322 int const rank_right = get_rank(type_right);
8324 if (signed_left == signed_right)
8325 return rank_left >= rank_right ? type_left : type_right;
8334 u_rank = rank_right;
8335 u_type = type_right;
8337 s_rank = rank_right;
8338 s_type = type_right;
8343 if (u_rank >= s_rank)
8346 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8348 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8349 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8353 case ATOMIC_TYPE_INT: return type_unsigned_int;
8354 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8355 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8357 default: panic("invalid atomic type");
8362 * Check the semantic restrictions for a binary expression.
8364 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8366 expression_t *const left = expression->left;
8367 expression_t *const right = expression->right;
8368 type_t *const orig_type_left = left->base.type;
8369 type_t *const orig_type_right = right->base.type;
8370 type_t *const type_left = skip_typeref(orig_type_left);
8371 type_t *const type_right = skip_typeref(orig_type_right);
8373 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8374 /* TODO: improve error message */
8375 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8376 errorf(&expression->base.source_position,
8377 "operation needs arithmetic types");
8382 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8383 expression->left = create_implicit_cast(left, arithmetic_type);
8384 expression->right = create_implicit_cast(right, arithmetic_type);
8385 expression->base.type = arithmetic_type;
8388 static void warn_div_by_zero(binary_expression_t const *const expression)
8390 if (!warning.div_by_zero ||
8391 !is_type_integer(expression->base.type))
8394 expression_t const *const right = expression->right;
8395 /* The type of the right operand can be different for /= */
8396 if (is_type_integer(right->base.type) &&
8397 is_constant_expression(right) &&
8398 fold_constant(right) == 0) {
8399 warningf(&expression->base.source_position, "division by zero");
8404 * Check the semantic restrictions for a div/mod expression.
8406 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8407 semantic_binexpr_arithmetic(expression);
8408 warn_div_by_zero(expression);
8411 static void semantic_shift_op(binary_expression_t *expression)
8413 expression_t *const left = expression->left;
8414 expression_t *const right = expression->right;
8415 type_t *const orig_type_left = left->base.type;
8416 type_t *const orig_type_right = right->base.type;
8417 type_t * type_left = skip_typeref(orig_type_left);
8418 type_t * type_right = skip_typeref(orig_type_right);
8420 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8421 /* TODO: improve error message */
8422 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8423 errorf(&expression->base.source_position,
8424 "operands of shift operation must have integer types");
8429 type_left = promote_integer(type_left);
8430 type_right = promote_integer(type_right);
8432 expression->left = create_implicit_cast(left, type_left);
8433 expression->right = create_implicit_cast(right, type_right);
8434 expression->base.type = type_left;
8437 static void semantic_add(binary_expression_t *expression)
8439 expression_t *const left = expression->left;
8440 expression_t *const right = expression->right;
8441 type_t *const orig_type_left = left->base.type;
8442 type_t *const orig_type_right = right->base.type;
8443 type_t *const type_left = skip_typeref(orig_type_left);
8444 type_t *const type_right = skip_typeref(orig_type_right);
8447 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8448 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8449 expression->left = create_implicit_cast(left, arithmetic_type);
8450 expression->right = create_implicit_cast(right, arithmetic_type);
8451 expression->base.type = arithmetic_type;
8453 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8454 check_pointer_arithmetic(&expression->base.source_position,
8455 type_left, orig_type_left);
8456 expression->base.type = type_left;
8457 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8458 check_pointer_arithmetic(&expression->base.source_position,
8459 type_right, orig_type_right);
8460 expression->base.type = type_right;
8461 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8462 errorf(&expression->base.source_position,
8463 "invalid operands to binary + ('%T', '%T')",
8464 orig_type_left, orig_type_right);
8468 static void semantic_sub(binary_expression_t *expression)
8470 expression_t *const left = expression->left;
8471 expression_t *const right = expression->right;
8472 type_t *const orig_type_left = left->base.type;
8473 type_t *const orig_type_right = right->base.type;
8474 type_t *const type_left = skip_typeref(orig_type_left);
8475 type_t *const type_right = skip_typeref(orig_type_right);
8476 source_position_t const *const pos = &expression->base.source_position;
8479 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8480 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8481 expression->left = create_implicit_cast(left, arithmetic_type);
8482 expression->right = create_implicit_cast(right, arithmetic_type);
8483 expression->base.type = arithmetic_type;
8485 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8486 check_pointer_arithmetic(&expression->base.source_position,
8487 type_left, orig_type_left);
8488 expression->base.type = type_left;
8489 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8490 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8491 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8492 if (!types_compatible(unqual_left, unqual_right)) {
8494 "subtracting pointers to incompatible types '%T' and '%T'",
8495 orig_type_left, orig_type_right);
8496 } else if (!is_type_object(unqual_left)) {
8497 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8498 errorf(pos, "subtracting pointers to non-object types '%T'",
8500 } else if (warning.other) {
8501 warningf(pos, "subtracting pointers to void");
8504 expression->base.type = type_ptrdiff_t;
8505 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8506 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8507 orig_type_left, orig_type_right);
8511 static void warn_string_literal_address(expression_t const* expr)
8513 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8514 expr = expr->unary.value;
8515 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8517 expr = expr->unary.value;
8520 if (expr->kind == EXPR_STRING_LITERAL ||
8521 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8522 warningf(&expr->base.source_position,
8523 "comparison with string literal results in unspecified behaviour");
8528 * Check the semantics of comparison expressions.
8530 * @param expression The expression to check.
8532 static void semantic_comparison(binary_expression_t *expression)
8534 expression_t *left = expression->left;
8535 expression_t *right = expression->right;
8537 if (warning.address) {
8538 warn_string_literal_address(left);
8539 warn_string_literal_address(right);
8541 expression_t const* const func_left = get_reference_address(left);
8542 if (func_left != NULL && is_null_pointer_constant(right)) {
8543 warningf(&expression->base.source_position,
8544 "the address of '%Y' will never be NULL",
8545 func_left->reference.entity->base.symbol);
8548 expression_t const* const func_right = get_reference_address(right);
8549 if (func_right != NULL && is_null_pointer_constant(right)) {
8550 warningf(&expression->base.source_position,
8551 "the address of '%Y' will never be NULL",
8552 func_right->reference.entity->base.symbol);
8556 type_t *orig_type_left = left->base.type;
8557 type_t *orig_type_right = right->base.type;
8558 type_t *type_left = skip_typeref(orig_type_left);
8559 type_t *type_right = skip_typeref(orig_type_right);
8561 /* TODO non-arithmetic types */
8562 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8563 /* test for signed vs unsigned compares */
8564 if (warning.sign_compare &&
8565 (expression->base.kind != EXPR_BINARY_EQUAL &&
8566 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8567 (is_type_signed(type_left) != is_type_signed(type_right))) {
8569 /* check if 1 of the operands is a constant, in this case we just
8570 * check wether we can safely represent the resulting constant in
8571 * the type of the other operand. */
8572 expression_t *const_expr = NULL;
8573 expression_t *other_expr = NULL;
8575 if (is_constant_expression(left)) {
8578 } else if (is_constant_expression(right)) {
8583 if (const_expr != NULL) {
8584 type_t *other_type = skip_typeref(other_expr->base.type);
8585 long val = fold_constant(const_expr);
8586 /* TODO: check if val can be represented by other_type */
8590 warningf(&expression->base.source_position,
8591 "comparison between signed and unsigned");
8593 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8594 expression->left = create_implicit_cast(left, arithmetic_type);
8595 expression->right = create_implicit_cast(right, arithmetic_type);
8596 expression->base.type = arithmetic_type;
8597 if (warning.float_equal &&
8598 (expression->base.kind == EXPR_BINARY_EQUAL ||
8599 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8600 is_type_float(arithmetic_type)) {
8601 warningf(&expression->base.source_position,
8602 "comparing floating point with == or != is unsafe");
8604 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8605 /* TODO check compatibility */
8606 } else if (is_type_pointer(type_left)) {
8607 expression->right = create_implicit_cast(right, type_left);
8608 } else if (is_type_pointer(type_right)) {
8609 expression->left = create_implicit_cast(left, type_right);
8610 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8611 type_error_incompatible("invalid operands in comparison",
8612 &expression->base.source_position,
8613 type_left, type_right);
8615 expression->base.type = type_int;
8619 * Checks if a compound type has constant fields.
8621 static bool has_const_fields(const compound_type_t *type)
8623 compound_t *compound = type->compound;
8624 entity_t *entry = compound->members.entities;
8626 for (; entry != NULL; entry = entry->base.next) {
8627 if (!is_declaration(entry))
8630 const type_t *decl_type = skip_typeref(entry->declaration.type);
8631 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8638 static bool is_valid_assignment_lhs(expression_t const* const left)
8640 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8641 type_t *const type_left = skip_typeref(orig_type_left);
8643 if (!is_lvalue(left)) {
8644 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8649 if (is_type_array(type_left)) {
8650 errorf(HERE, "cannot assign to arrays ('%E')", left);
8653 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8654 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8658 if (is_type_incomplete(type_left)) {
8659 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8660 left, orig_type_left);
8663 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8664 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8665 left, orig_type_left);
8672 static void semantic_arithmetic_assign(binary_expression_t *expression)
8674 expression_t *left = expression->left;
8675 expression_t *right = expression->right;
8676 type_t *orig_type_left = left->base.type;
8677 type_t *orig_type_right = right->base.type;
8679 if (!is_valid_assignment_lhs(left))
8682 type_t *type_left = skip_typeref(orig_type_left);
8683 type_t *type_right = skip_typeref(orig_type_right);
8685 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8686 /* TODO: improve error message */
8687 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8688 errorf(&expression->base.source_position,
8689 "operation needs arithmetic types");
8694 /* combined instructions are tricky. We can't create an implicit cast on
8695 * the left side, because we need the uncasted form for the store.
8696 * The ast2firm pass has to know that left_type must be right_type
8697 * for the arithmetic operation and create a cast by itself */
8698 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8699 expression->right = create_implicit_cast(right, arithmetic_type);
8700 expression->base.type = type_left;
8703 static void semantic_divmod_assign(binary_expression_t *expression)
8705 semantic_arithmetic_assign(expression);
8706 warn_div_by_zero(expression);
8709 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8711 expression_t *const left = expression->left;
8712 expression_t *const right = expression->right;
8713 type_t *const orig_type_left = left->base.type;
8714 type_t *const orig_type_right = right->base.type;
8715 type_t *const type_left = skip_typeref(orig_type_left);
8716 type_t *const type_right = skip_typeref(orig_type_right);
8718 if (!is_valid_assignment_lhs(left))
8721 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8722 /* combined instructions are tricky. We can't create an implicit cast on
8723 * the left side, because we need the uncasted form for the store.
8724 * The ast2firm pass has to know that left_type must be right_type
8725 * for the arithmetic operation and create a cast by itself */
8726 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8727 expression->right = create_implicit_cast(right, arithmetic_type);
8728 expression->base.type = type_left;
8729 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8730 check_pointer_arithmetic(&expression->base.source_position,
8731 type_left, orig_type_left);
8732 expression->base.type = type_left;
8733 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8734 errorf(&expression->base.source_position,
8735 "incompatible types '%T' and '%T' in assignment",
8736 orig_type_left, orig_type_right);
8741 * Check the semantic restrictions of a logical expression.
8743 static void semantic_logical_op(binary_expression_t *expression)
8745 expression_t *const left = expression->left;
8746 expression_t *const right = expression->right;
8747 type_t *const orig_type_left = left->base.type;
8748 type_t *const orig_type_right = right->base.type;
8749 type_t *const type_left = skip_typeref(orig_type_left);
8750 type_t *const type_right = skip_typeref(orig_type_right);
8752 warn_function_address_as_bool(left);
8753 warn_function_address_as_bool(right);
8755 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8756 /* TODO: improve error message */
8757 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8758 errorf(&expression->base.source_position,
8759 "operation needs scalar types");
8764 expression->base.type = type_int;
8768 * Check the semantic restrictions of a binary assign expression.
8770 static void semantic_binexpr_assign(binary_expression_t *expression)
8772 expression_t *left = expression->left;
8773 type_t *orig_type_left = left->base.type;
8775 if (!is_valid_assignment_lhs(left))
8778 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8779 report_assign_error(error, orig_type_left, expression->right,
8780 "assignment", &left->base.source_position);
8781 expression->right = create_implicit_cast(expression->right, orig_type_left);
8782 expression->base.type = orig_type_left;
8786 * Determine if the outermost operation (or parts thereof) of the given
8787 * expression has no effect in order to generate a warning about this fact.
8788 * Therefore in some cases this only examines some of the operands of the
8789 * expression (see comments in the function and examples below).
8791 * f() + 23; // warning, because + has no effect
8792 * x || f(); // no warning, because x controls execution of f()
8793 * x ? y : f(); // warning, because y has no effect
8794 * (void)x; // no warning to be able to suppress the warning
8795 * This function can NOT be used for an "expression has definitely no effect"-
8797 static bool expression_has_effect(const expression_t *const expr)
8799 switch (expr->kind) {
8800 case EXPR_UNKNOWN: break;
8801 case EXPR_INVALID: return true; /* do NOT warn */
8802 case EXPR_REFERENCE: return false;
8803 case EXPR_REFERENCE_ENUM_VALUE: return false;
8804 /* suppress the warning for microsoft __noop operations */
8805 case EXPR_CONST: return expr->conste.is_ms_noop;
8806 case EXPR_CHARACTER_CONSTANT: return false;
8807 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8808 case EXPR_STRING_LITERAL: return false;
8809 case EXPR_WIDE_STRING_LITERAL: return false;
8810 case EXPR_LABEL_ADDRESS: return false;
8813 const call_expression_t *const call = &expr->call;
8814 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8817 switch (call->function->builtin_symbol.symbol->ID) {
8818 case T___builtin_va_end: return true;
8819 default: return false;
8823 /* Generate the warning if either the left or right hand side of a
8824 * conditional expression has no effect */
8825 case EXPR_CONDITIONAL: {
8826 const conditional_expression_t *const cond = &expr->conditional;
8828 expression_has_effect(cond->true_expression) &&
8829 expression_has_effect(cond->false_expression);
8832 case EXPR_SELECT: return false;
8833 case EXPR_ARRAY_ACCESS: return false;
8834 case EXPR_SIZEOF: return false;
8835 case EXPR_CLASSIFY_TYPE: return false;
8836 case EXPR_ALIGNOF: return false;
8838 case EXPR_FUNCNAME: return false;
8839 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8840 case EXPR_BUILTIN_CONSTANT_P: return false;
8841 case EXPR_BUILTIN_PREFETCH: return true;
8842 case EXPR_OFFSETOF: return false;
8843 case EXPR_VA_START: return true;
8844 case EXPR_VA_ARG: return true;
8845 case EXPR_STATEMENT: return true; // TODO
8846 case EXPR_COMPOUND_LITERAL: return false;
8848 case EXPR_UNARY_NEGATE: return false;
8849 case EXPR_UNARY_PLUS: return false;
8850 case EXPR_UNARY_BITWISE_NEGATE: return false;
8851 case EXPR_UNARY_NOT: return false;
8852 case EXPR_UNARY_DEREFERENCE: return false;
8853 case EXPR_UNARY_TAKE_ADDRESS: return false;
8854 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8855 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8856 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8857 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8859 /* Treat void casts as if they have an effect in order to being able to
8860 * suppress the warning */
8861 case EXPR_UNARY_CAST: {
8862 type_t *const type = skip_typeref(expr->base.type);
8863 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8866 case EXPR_UNARY_CAST_IMPLICIT: return true;
8867 case EXPR_UNARY_ASSUME: return true;
8868 case EXPR_UNARY_DELETE: return true;
8869 case EXPR_UNARY_DELETE_ARRAY: return true;
8870 case EXPR_UNARY_THROW: return true;
8872 case EXPR_BINARY_ADD: return false;
8873 case EXPR_BINARY_SUB: return false;
8874 case EXPR_BINARY_MUL: return false;
8875 case EXPR_BINARY_DIV: return false;
8876 case EXPR_BINARY_MOD: return false;
8877 case EXPR_BINARY_EQUAL: return false;
8878 case EXPR_BINARY_NOTEQUAL: return false;
8879 case EXPR_BINARY_LESS: return false;
8880 case EXPR_BINARY_LESSEQUAL: return false;
8881 case EXPR_BINARY_GREATER: return false;
8882 case EXPR_BINARY_GREATEREQUAL: return false;
8883 case EXPR_BINARY_BITWISE_AND: return false;
8884 case EXPR_BINARY_BITWISE_OR: return false;
8885 case EXPR_BINARY_BITWISE_XOR: return false;
8886 case EXPR_BINARY_SHIFTLEFT: return false;
8887 case EXPR_BINARY_SHIFTRIGHT: return false;
8888 case EXPR_BINARY_ASSIGN: return true;
8889 case EXPR_BINARY_MUL_ASSIGN: return true;
8890 case EXPR_BINARY_DIV_ASSIGN: return true;
8891 case EXPR_BINARY_MOD_ASSIGN: return true;
8892 case EXPR_BINARY_ADD_ASSIGN: return true;
8893 case EXPR_BINARY_SUB_ASSIGN: return true;
8894 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8895 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8896 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8897 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8898 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8900 /* Only examine the right hand side of && and ||, because the left hand
8901 * side already has the effect of controlling the execution of the right
8903 case EXPR_BINARY_LOGICAL_AND:
8904 case EXPR_BINARY_LOGICAL_OR:
8905 /* Only examine the right hand side of a comma expression, because the left
8906 * hand side has a separate warning */
8907 case EXPR_BINARY_COMMA:
8908 return expression_has_effect(expr->binary.right);
8910 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8911 case EXPR_BINARY_ISGREATER: return false;
8912 case EXPR_BINARY_ISGREATEREQUAL: return false;
8913 case EXPR_BINARY_ISLESS: return false;
8914 case EXPR_BINARY_ISLESSEQUAL: return false;
8915 case EXPR_BINARY_ISLESSGREATER: return false;
8916 case EXPR_BINARY_ISUNORDERED: return false;
8919 internal_errorf(HERE, "unexpected expression");
8922 static void semantic_comma(binary_expression_t *expression)
8924 if (warning.unused_value) {
8925 const expression_t *const left = expression->left;
8926 if (!expression_has_effect(left)) {
8927 warningf(&left->base.source_position,
8928 "left-hand operand of comma expression has no effect");
8931 expression->base.type = expression->right->base.type;
8935 * @param prec_r precedence of the right operand
8937 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8938 static expression_t *parse_##binexpression_type(expression_t *left) \
8940 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8941 binexpr->base.source_position = *HERE; \
8942 binexpr->binary.left = left; \
8945 expression_t *right = parse_sub_expression(prec_r); \
8947 binexpr->binary.right = right; \
8948 sfunc(&binexpr->binary); \
8953 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8954 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8955 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8956 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8957 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8958 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8959 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8960 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8961 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8962 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8963 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8964 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8965 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8966 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8967 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8968 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8969 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8970 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8971 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8972 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8973 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8974 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8975 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8976 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8977 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8978 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8979 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8980 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8981 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8982 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8985 static expression_t *parse_sub_expression(precedence_t precedence)
8987 if (token.type < 0) {
8988 return expected_expression_error();
8991 expression_parser_function_t *parser
8992 = &expression_parsers[token.type];
8993 source_position_t source_position = token.source_position;
8996 if (parser->parser != NULL) {
8997 left = parser->parser();
8999 left = parse_primary_expression();
9001 assert(left != NULL);
9002 left->base.source_position = source_position;
9005 if (token.type < 0) {
9006 return expected_expression_error();
9009 parser = &expression_parsers[token.type];
9010 if (parser->infix_parser == NULL)
9012 if (parser->infix_precedence < precedence)
9015 left = parser->infix_parser(left);
9017 assert(left != NULL);
9018 assert(left->kind != EXPR_UNKNOWN);
9019 left->base.source_position = source_position;
9026 * Parse an expression.
9028 static expression_t *parse_expression(void)
9030 return parse_sub_expression(PREC_EXPRESSION);
9034 * Register a parser for a prefix-like operator.
9036 * @param parser the parser function
9037 * @param token_type the token type of the prefix token
9039 static void register_expression_parser(parse_expression_function parser,
9042 expression_parser_function_t *entry = &expression_parsers[token_type];
9044 if (entry->parser != NULL) {
9045 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9046 panic("trying to register multiple expression parsers for a token");
9048 entry->parser = parser;
9052 * Register a parser for an infix operator with given precedence.
9054 * @param parser the parser function
9055 * @param token_type the token type of the infix operator
9056 * @param precedence the precedence of the operator
9058 static void register_infix_parser(parse_expression_infix_function parser,
9059 int token_type, unsigned precedence)
9061 expression_parser_function_t *entry = &expression_parsers[token_type];
9063 if (entry->infix_parser != NULL) {
9064 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9065 panic("trying to register multiple infix expression parsers for a "
9068 entry->infix_parser = parser;
9069 entry->infix_precedence = precedence;
9073 * Initialize the expression parsers.
9075 static void init_expression_parsers(void)
9077 memset(&expression_parsers, 0, sizeof(expression_parsers));
9079 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9080 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9081 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9082 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9083 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9084 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9085 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9086 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9087 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9088 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9089 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9090 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9091 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9092 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9093 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9094 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9095 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9096 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9097 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9098 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9099 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9100 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9101 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9102 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9103 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9104 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9105 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9106 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9107 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9108 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9109 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9110 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9111 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9112 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9113 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9114 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9115 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9117 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9118 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9119 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9120 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9121 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9122 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9123 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9124 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9125 register_expression_parser(parse_sizeof, T_sizeof);
9126 register_expression_parser(parse_alignof, T___alignof__);
9127 register_expression_parser(parse_extension, T___extension__);
9128 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9129 register_expression_parser(parse_delete, T_delete);
9130 register_expression_parser(parse_throw, T_throw);
9134 * Parse a asm statement arguments specification.
9136 static asm_argument_t *parse_asm_arguments(bool is_out)
9138 asm_argument_t *result = NULL;
9139 asm_argument_t *last = NULL;
9141 while (token.type == T_STRING_LITERAL || token.type == '[') {
9142 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9143 memset(argument, 0, sizeof(argument[0]));
9145 if (token.type == '[') {
9147 if (token.type != T_IDENTIFIER) {
9148 parse_error_expected("while parsing asm argument",
9149 T_IDENTIFIER, NULL);
9152 argument->symbol = token.v.symbol;
9157 argument->constraints = parse_string_literals();
9159 add_anchor_token(')');
9160 expression_t *expression = parse_expression();
9161 rem_anchor_token(')');
9163 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9164 * change size or type representation (e.g. int -> long is ok, but
9165 * int -> float is not) */
9166 if (expression->kind == EXPR_UNARY_CAST) {
9167 type_t *const type = expression->base.type;
9168 type_kind_t const kind = type->kind;
9169 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9172 if (kind == TYPE_ATOMIC) {
9173 atomic_type_kind_t const akind = type->atomic.akind;
9174 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9175 size = get_atomic_type_size(akind);
9177 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9178 size = get_atomic_type_size(get_intptr_kind());
9182 expression_t *const value = expression->unary.value;
9183 type_t *const value_type = value->base.type;
9184 type_kind_t const value_kind = value_type->kind;
9186 unsigned value_flags;
9187 unsigned value_size;
9188 if (value_kind == TYPE_ATOMIC) {
9189 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9190 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9191 value_size = get_atomic_type_size(value_akind);
9192 } else if (value_kind == TYPE_POINTER) {
9193 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9194 value_size = get_atomic_type_size(get_intptr_kind());
9199 if (value_flags != flags || value_size != size)
9203 } while (expression->kind == EXPR_UNARY_CAST);
9207 if (!is_lvalue(expression)) {
9208 errorf(&expression->base.source_position,
9209 "asm output argument is not an lvalue");
9212 if (argument->constraints.begin[0] == '+')
9213 mark_vars_read(expression, NULL);
9215 mark_vars_read(expression, NULL);
9217 argument->expression = expression;
9220 set_address_taken(expression, true);
9223 last->next = argument;
9229 if (token.type != ',')
9240 * Parse a asm statement clobber specification.
9242 static asm_clobber_t *parse_asm_clobbers(void)
9244 asm_clobber_t *result = NULL;
9245 asm_clobber_t *last = NULL;
9247 while(token.type == T_STRING_LITERAL) {
9248 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9249 clobber->clobber = parse_string_literals();
9252 last->next = clobber;
9258 if (token.type != ',')
9267 * Parse an asm statement.
9269 static statement_t *parse_asm_statement(void)
9271 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9272 asm_statement_t *asm_statement = &statement->asms;
9276 if (token.type == T_volatile) {
9278 asm_statement->is_volatile = true;
9282 add_anchor_token(')');
9283 add_anchor_token(':');
9284 asm_statement->asm_text = parse_string_literals();
9286 if (token.type != ':') {
9287 rem_anchor_token(':');
9292 asm_statement->outputs = parse_asm_arguments(true);
9293 if (token.type != ':') {
9294 rem_anchor_token(':');
9299 asm_statement->inputs = parse_asm_arguments(false);
9300 if (token.type != ':') {
9301 rem_anchor_token(':');
9304 rem_anchor_token(':');
9307 asm_statement->clobbers = parse_asm_clobbers();
9310 rem_anchor_token(')');
9314 if (asm_statement->outputs == NULL) {
9315 /* GCC: An 'asm' instruction without any output operands will be treated
9316 * identically to a volatile 'asm' instruction. */
9317 asm_statement->is_volatile = true;
9322 return create_invalid_statement();
9326 * Parse a case statement.
9328 static statement_t *parse_case_statement(void)
9330 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9331 source_position_t *const pos = &statement->base.source_position;
9335 expression_t *const expression = parse_expression();
9336 statement->case_label.expression = expression;
9337 if (!is_constant_expression(expression)) {
9338 /* This check does not prevent the error message in all cases of an
9339 * prior error while parsing the expression. At least it catches the
9340 * common case of a mistyped enum entry. */
9341 if (is_type_valid(skip_typeref(expression->base.type))) {
9342 errorf(pos, "case label does not reduce to an integer constant");
9344 statement->case_label.is_bad = true;
9346 long const val = fold_constant(expression);
9347 statement->case_label.first_case = val;
9348 statement->case_label.last_case = val;
9352 if (token.type == T_DOTDOTDOT) {
9354 expression_t *const end_range = parse_expression();
9355 statement->case_label.end_range = end_range;
9356 if (!is_constant_expression(end_range)) {
9357 /* This check does not prevent the error message in all cases of an
9358 * prior error while parsing the expression. At least it catches the
9359 * common case of a mistyped enum entry. */
9360 if (is_type_valid(skip_typeref(end_range->base.type))) {
9361 errorf(pos, "case range does not reduce to an integer constant");
9363 statement->case_label.is_bad = true;
9365 long const val = fold_constant(end_range);
9366 statement->case_label.last_case = val;
9368 if (warning.other && val < statement->case_label.first_case) {
9369 statement->case_label.is_empty_range = true;
9370 warningf(pos, "empty range specified");
9376 PUSH_PARENT(statement);
9380 if (current_switch != NULL) {
9381 if (! statement->case_label.is_bad) {
9382 /* Check for duplicate case values */
9383 case_label_statement_t *c = &statement->case_label;
9384 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9385 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9388 if (c->last_case < l->first_case || c->first_case > l->last_case)
9391 errorf(pos, "duplicate case value (previously used %P)",
9392 &l->base.source_position);
9396 /* link all cases into the switch statement */
9397 if (current_switch->last_case == NULL) {
9398 current_switch->first_case = &statement->case_label;
9400 current_switch->last_case->next = &statement->case_label;
9402 current_switch->last_case = &statement->case_label;
9404 errorf(pos, "case label not within a switch statement");
9407 statement_t *const inner_stmt = parse_statement();
9408 statement->case_label.statement = inner_stmt;
9409 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9410 errorf(&inner_stmt->base.source_position, "declaration after case label");
9417 return create_invalid_statement();
9421 * Parse a default statement.
9423 static statement_t *parse_default_statement(void)
9425 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9429 PUSH_PARENT(statement);
9432 if (current_switch != NULL) {
9433 const case_label_statement_t *def_label = current_switch->default_label;
9434 if (def_label != NULL) {
9435 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9436 &def_label->base.source_position);
9438 current_switch->default_label = &statement->case_label;
9440 /* link all cases into the switch statement */
9441 if (current_switch->last_case == NULL) {
9442 current_switch->first_case = &statement->case_label;
9444 current_switch->last_case->next = &statement->case_label;
9446 current_switch->last_case = &statement->case_label;
9449 errorf(&statement->base.source_position,
9450 "'default' label not within a switch statement");
9453 statement_t *const inner_stmt = parse_statement();
9454 statement->case_label.statement = inner_stmt;
9455 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9456 errorf(&inner_stmt->base.source_position, "declaration after default label");
9463 return create_invalid_statement();
9467 * Parse a label statement.
9469 static statement_t *parse_label_statement(void)
9471 assert(token.type == T_IDENTIFIER);
9472 symbol_t *symbol = token.v.symbol;
9473 label_t *label = get_label(symbol);
9475 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9476 statement->label.label = label;
9480 PUSH_PARENT(statement);
9482 /* if statement is already set then the label is defined twice,
9483 * otherwise it was just mentioned in a goto/local label declaration so far
9485 if (label->statement != NULL) {
9486 errorf(HERE, "duplicate label '%Y' (declared %P)",
9487 symbol, &label->base.source_position);
9489 label->base.source_position = token.source_position;
9490 label->statement = statement;
9495 if (token.type == '}') {
9496 /* TODO only warn? */
9497 if (warning.other && false) {
9498 warningf(HERE, "label at end of compound statement");
9499 statement->label.statement = create_empty_statement();
9501 errorf(HERE, "label at end of compound statement");
9502 statement->label.statement = create_invalid_statement();
9504 } else if (token.type == ';') {
9505 /* Eat an empty statement here, to avoid the warning about an empty
9506 * statement after a label. label:; is commonly used to have a label
9507 * before a closing brace. */
9508 statement->label.statement = create_empty_statement();
9511 statement_t *const inner_stmt = parse_statement();
9512 statement->label.statement = inner_stmt;
9513 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9514 errorf(&inner_stmt->base.source_position, "declaration after label");
9518 /* remember the labels in a list for later checking */
9519 if (label_last == NULL) {
9520 label_first = &statement->label;
9522 label_last->next = &statement->label;
9524 label_last = &statement->label;
9531 * Parse an if statement.
9533 static statement_t *parse_if(void)
9535 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9539 PUSH_PARENT(statement);
9541 add_anchor_token('{');
9544 add_anchor_token(')');
9545 expression_t *const expr = parse_expression();
9546 statement->ifs.condition = expr;
9547 mark_vars_read(expr, NULL);
9548 rem_anchor_token(')');
9552 rem_anchor_token('{');
9554 add_anchor_token(T_else);
9555 statement->ifs.true_statement = parse_statement();
9556 rem_anchor_token(T_else);
9558 if (token.type == T_else) {
9560 statement->ifs.false_statement = parse_statement();
9568 * Check that all enums are handled in a switch.
9570 * @param statement the switch statement to check
9572 static void check_enum_cases(const switch_statement_t *statement) {
9573 const type_t *type = skip_typeref(statement->expression->base.type);
9574 if (! is_type_enum(type))
9576 const enum_type_t *enumt = &type->enumt;
9578 /* if we have a default, no warnings */
9579 if (statement->default_label != NULL)
9582 /* FIXME: calculation of value should be done while parsing */
9583 /* TODO: quadratic algorithm here. Change to an n log n one */
9584 long last_value = -1;
9585 const entity_t *entry = enumt->enume->base.next;
9586 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9587 entry = entry->base.next) {
9588 const expression_t *expression = entry->enum_value.value;
9589 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9591 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9592 if (l->expression == NULL)
9594 if (l->first_case <= value && value <= l->last_case) {
9600 warningf(&statement->base.source_position,
9601 "enumeration value '%Y' not handled in switch",
9602 entry->base.symbol);
9609 * Parse a switch statement.
9611 static statement_t *parse_switch(void)
9613 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9617 PUSH_PARENT(statement);
9620 add_anchor_token(')');
9621 expression_t *const expr = parse_expression();
9622 mark_vars_read(expr, NULL);
9623 type_t * type = skip_typeref(expr->base.type);
9624 if (is_type_integer(type)) {
9625 type = promote_integer(type);
9626 if (warning.traditional) {
9627 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9628 warningf(&expr->base.source_position,
9629 "'%T' switch expression not converted to '%T' in ISO C",
9633 } else if (is_type_valid(type)) {
9634 errorf(&expr->base.source_position,
9635 "switch quantity is not an integer, but '%T'", type);
9636 type = type_error_type;
9638 statement->switchs.expression = create_implicit_cast(expr, type);
9640 rem_anchor_token(')');
9642 switch_statement_t *rem = current_switch;
9643 current_switch = &statement->switchs;
9644 statement->switchs.body = parse_statement();
9645 current_switch = rem;
9647 if (warning.switch_default &&
9648 statement->switchs.default_label == NULL) {
9649 warningf(&statement->base.source_position, "switch has no default case");
9651 if (warning.switch_enum)
9652 check_enum_cases(&statement->switchs);
9658 return create_invalid_statement();
9661 static statement_t *parse_loop_body(statement_t *const loop)
9663 statement_t *const rem = current_loop;
9664 current_loop = loop;
9666 statement_t *const body = parse_statement();
9673 * Parse a while statement.
9675 static statement_t *parse_while(void)
9677 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9681 PUSH_PARENT(statement);
9684 add_anchor_token(')');
9685 expression_t *const cond = parse_expression();
9686 statement->whiles.condition = cond;
9687 mark_vars_read(cond, NULL);
9688 rem_anchor_token(')');
9691 statement->whiles.body = parse_loop_body(statement);
9697 return create_invalid_statement();
9701 * Parse a do statement.
9703 static statement_t *parse_do(void)
9705 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9709 PUSH_PARENT(statement);
9711 add_anchor_token(T_while);
9712 statement->do_while.body = parse_loop_body(statement);
9713 rem_anchor_token(T_while);
9717 add_anchor_token(')');
9718 expression_t *const cond = parse_expression();
9719 statement->do_while.condition = cond;
9720 mark_vars_read(cond, NULL);
9721 rem_anchor_token(')');
9729 return create_invalid_statement();
9733 * Parse a for statement.
9735 static statement_t *parse_for(void)
9737 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9741 PUSH_PARENT(statement);
9743 size_t const top = environment_top();
9744 scope_push(&statement->fors.scope);
9747 add_anchor_token(')');
9749 if (token.type != ';') {
9750 if (is_declaration_specifier(&token, false)) {
9751 parse_declaration(record_entity);
9753 add_anchor_token(';');
9754 expression_t *const init = parse_expression();
9755 statement->fors.initialisation = init;
9756 mark_vars_read(init, VAR_ANY);
9757 if (warning.unused_value && !expression_has_effect(init)) {
9758 warningf(&init->base.source_position,
9759 "initialisation of 'for'-statement has no effect");
9761 rem_anchor_token(';');
9768 if (token.type != ';') {
9769 add_anchor_token(';');
9770 expression_t *const cond = parse_expression();
9771 statement->fors.condition = cond;
9772 mark_vars_read(cond, NULL);
9773 rem_anchor_token(';');
9776 if (token.type != ')') {
9777 expression_t *const step = parse_expression();
9778 statement->fors.step = step;
9779 mark_vars_read(step, VAR_ANY);
9780 if (warning.unused_value && !expression_has_effect(step)) {
9781 warningf(&step->base.source_position,
9782 "step of 'for'-statement has no effect");
9786 rem_anchor_token(')');
9787 statement->fors.body = parse_loop_body(statement);
9789 assert(scope == &statement->fors.scope);
9791 environment_pop_to(top);
9798 rem_anchor_token(')');
9799 assert(scope == &statement->fors.scope);
9801 environment_pop_to(top);
9803 return create_invalid_statement();
9807 * Parse a goto statement.
9809 static statement_t *parse_goto(void)
9811 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9814 if (GNU_MODE && token.type == '*') {
9816 expression_t *expression = parse_expression();
9817 mark_vars_read(expression, NULL);
9819 /* Argh: although documentation say the expression must be of type void *,
9820 * gcc excepts anything that can be casted into void * without error */
9821 type_t *type = expression->base.type;
9823 if (type != type_error_type) {
9824 if (!is_type_pointer(type) && !is_type_integer(type)) {
9825 errorf(&expression->base.source_position,
9826 "cannot convert to a pointer type");
9827 } else if (warning.other && type != type_void_ptr) {
9828 warningf(&expression->base.source_position,
9829 "type of computed goto expression should be 'void*' not '%T'", type);
9831 expression = create_implicit_cast(expression, type_void_ptr);
9834 statement->gotos.expression = expression;
9836 if (token.type != T_IDENTIFIER) {
9838 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9840 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9844 symbol_t *symbol = token.v.symbol;
9847 statement->gotos.label = get_label(symbol);
9850 /* remember the goto's in a list for later checking */
9851 if (goto_last == NULL) {
9852 goto_first = &statement->gotos;
9854 goto_last->next = &statement->gotos;
9856 goto_last = &statement->gotos;
9862 return create_invalid_statement();
9866 * Parse a continue statement.
9868 static statement_t *parse_continue(void)
9870 if (current_loop == NULL) {
9871 errorf(HERE, "continue statement not within loop");
9874 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9884 * Parse a break statement.
9886 static statement_t *parse_break(void)
9888 if (current_switch == NULL && current_loop == NULL) {
9889 errorf(HERE, "break statement not within loop or switch");
9892 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9902 * Parse a __leave statement.
9904 static statement_t *parse_leave_statement(void)
9906 if (current_try == NULL) {
9907 errorf(HERE, "__leave statement not within __try");
9910 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9920 * Check if a given entity represents a local variable.
9922 static bool is_local_variable(const entity_t *entity)
9924 if (entity->kind != ENTITY_VARIABLE)
9927 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9928 case STORAGE_CLASS_AUTO:
9929 case STORAGE_CLASS_REGISTER: {
9930 const type_t *type = skip_typeref(entity->declaration.type);
9931 if (is_type_function(type)) {
9943 * Check if a given expression represents a local variable.
9945 static bool expression_is_local_variable(const expression_t *expression)
9947 if (expression->base.kind != EXPR_REFERENCE) {
9950 const entity_t *entity = expression->reference.entity;
9951 return is_local_variable(entity);
9955 * Check if a given expression represents a local variable and
9956 * return its declaration then, else return NULL.
9958 entity_t *expression_is_variable(const expression_t *expression)
9960 if (expression->base.kind != EXPR_REFERENCE) {
9963 entity_t *entity = expression->reference.entity;
9964 if (entity->kind != ENTITY_VARIABLE)
9971 * Parse a return statement.
9973 static statement_t *parse_return(void)
9977 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9979 expression_t *return_value = NULL;
9980 if (token.type != ';') {
9981 return_value = parse_expression();
9982 mark_vars_read(return_value, NULL);
9985 const type_t *const func_type = current_function->base.type;
9986 assert(is_type_function(func_type));
9987 type_t *const return_type = skip_typeref(func_type->function.return_type);
9989 if (return_value != NULL) {
9990 type_t *return_value_type = skip_typeref(return_value->base.type);
9992 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
9993 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9994 if (warning.other) {
9995 warningf(&statement->base.source_position,
9996 "'return' with a value, in function returning void");
9998 return_value = NULL;
10000 assign_error_t error = semantic_assign(return_type, return_value);
10001 report_assign_error(error, return_type, return_value, "'return'",
10002 &statement->base.source_position);
10003 return_value = create_implicit_cast(return_value, return_type);
10005 /* check for returning address of a local var */
10006 if (warning.other && return_value != NULL
10007 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10008 const expression_t *expression = return_value->unary.value;
10009 if (expression_is_local_variable(expression)) {
10010 warningf(&statement->base.source_position,
10011 "function returns address of local variable");
10014 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10015 warningf(&statement->base.source_position,
10016 "'return' without value, in function returning non-void");
10018 statement->returns.value = return_value;
10027 * Parse a declaration statement.
10029 static statement_t *parse_declaration_statement(void)
10031 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10033 entity_t *before = scope->last_entity;
10035 parse_external_declaration();
10037 parse_declaration(record_entity);
10039 if (before == NULL) {
10040 statement->declaration.declarations_begin = scope->entities;
10042 statement->declaration.declarations_begin = before->base.next;
10044 statement->declaration.declarations_end = scope->last_entity;
10050 * Parse an expression statement, ie. expr ';'.
10052 static statement_t *parse_expression_statement(void)
10054 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10056 expression_t *const expr = parse_expression();
10057 statement->expression.expression = expr;
10058 mark_vars_read(expr, VAR_ANY);
10067 * Parse a microsoft __try { } __finally { } or
10068 * __try{ } __except() { }
10070 static statement_t *parse_ms_try_statment(void)
10072 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10075 PUSH_PARENT(statement);
10077 ms_try_statement_t *rem = current_try;
10078 current_try = &statement->ms_try;
10079 statement->ms_try.try_statement = parse_compound_statement(false);
10084 if (token.type == T___except) {
10087 add_anchor_token(')');
10088 expression_t *const expr = parse_expression();
10089 mark_vars_read(expr, NULL);
10090 type_t * type = skip_typeref(expr->base.type);
10091 if (is_type_integer(type)) {
10092 type = promote_integer(type);
10093 } else if (is_type_valid(type)) {
10094 errorf(&expr->base.source_position,
10095 "__expect expression is not an integer, but '%T'", type);
10096 type = type_error_type;
10098 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10099 rem_anchor_token(')');
10101 statement->ms_try.final_statement = parse_compound_statement(false);
10102 } else if (token.type == T__finally) {
10104 statement->ms_try.final_statement = parse_compound_statement(false);
10106 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10107 return create_invalid_statement();
10111 return create_invalid_statement();
10114 static statement_t *parse_empty_statement(void)
10116 if (warning.empty_statement) {
10117 warningf(HERE, "statement is empty");
10119 statement_t *const statement = create_empty_statement();
10124 static statement_t *parse_local_label_declaration(void)
10126 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10130 entity_t *begin = NULL, *end = NULL;
10133 if (token.type != T_IDENTIFIER) {
10134 parse_error_expected("while parsing local label declaration",
10135 T_IDENTIFIER, NULL);
10138 symbol_t *symbol = token.v.symbol;
10139 entity_t *entity = get_entity(symbol, NAMESPACE_LOCAL_LABEL);
10140 if (entity != NULL && entity->base.parent_scope == scope) {
10141 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10142 symbol, &entity->base.source_position);
10144 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10146 entity->base.parent_scope = scope;
10147 entity->base.namespc = NAMESPACE_LOCAL_LABEL;
10148 entity->base.source_position = token.source_position;
10149 entity->base.symbol = symbol;
10152 end->base.next = entity;
10157 local_label_push(entity);
10161 if (token.type != ',')
10167 statement->declaration.declarations_begin = begin;
10168 statement->declaration.declarations_end = end;
10173 * Parse a statement.
10174 * There's also parse_statement() which additionally checks for
10175 * "statement has no effect" warnings
10177 static statement_t *intern_parse_statement(void)
10179 statement_t *statement = NULL;
10181 /* declaration or statement */
10182 add_anchor_token(';');
10183 switch (token.type) {
10184 case T_IDENTIFIER: {
10185 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10186 if (la1_type == ':') {
10187 statement = parse_label_statement();
10188 } else if (is_typedef_symbol(token.v.symbol)) {
10189 statement = parse_declaration_statement();
10191 /* it's an identifier, the grammar says this must be an
10192 * expression statement. However it is common that users mistype
10193 * declaration types, so we guess a bit here to improve robustness
10194 * for incorrect programs */
10195 switch (la1_type) {
10197 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10198 goto expression_statment;
10203 statement = parse_declaration_statement();
10207 expression_statment:
10208 statement = parse_expression_statement();
10215 case T___extension__:
10216 /* This can be a prefix to a declaration or an expression statement.
10217 * We simply eat it now and parse the rest with tail recursion. */
10220 } while (token.type == T___extension__);
10221 bool old_gcc_extension = in_gcc_extension;
10222 in_gcc_extension = true;
10223 statement = parse_statement();
10224 in_gcc_extension = old_gcc_extension;
10228 statement = parse_declaration_statement();
10232 statement = parse_local_label_declaration();
10235 case ';': statement = parse_empty_statement(); break;
10236 case '{': statement = parse_compound_statement(false); break;
10237 case T___leave: statement = parse_leave_statement(); break;
10238 case T___try: statement = parse_ms_try_statment(); break;
10239 case T_asm: statement = parse_asm_statement(); break;
10240 case T_break: statement = parse_break(); break;
10241 case T_case: statement = parse_case_statement(); break;
10242 case T_continue: statement = parse_continue(); break;
10243 case T_default: statement = parse_default_statement(); break;
10244 case T_do: statement = parse_do(); break;
10245 case T_for: statement = parse_for(); break;
10246 case T_goto: statement = parse_goto(); break;
10247 case T_if: statement = parse_if(); break;
10248 case T_return: statement = parse_return(); break;
10249 case T_switch: statement = parse_switch(); break;
10250 case T_while: statement = parse_while(); break;
10253 statement = parse_expression_statement();
10257 errorf(HERE, "unexpected token %K while parsing statement", &token);
10258 statement = create_invalid_statement();
10263 rem_anchor_token(';');
10265 assert(statement != NULL
10266 && statement->base.source_position.input_name != NULL);
10272 * parse a statement and emits "statement has no effect" warning if needed
10273 * (This is really a wrapper around intern_parse_statement with check for 1
10274 * single warning. It is needed, because for statement expressions we have
10275 * to avoid the warning on the last statement)
10277 static statement_t *parse_statement(void)
10279 statement_t *statement = intern_parse_statement();
10281 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10282 expression_t *expression = statement->expression.expression;
10283 if (!expression_has_effect(expression)) {
10284 warningf(&expression->base.source_position,
10285 "statement has no effect");
10293 * Parse a compound statement.
10295 static statement_t *parse_compound_statement(bool inside_expression_statement)
10297 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10299 PUSH_PARENT(statement);
10302 add_anchor_token('}');
10304 size_t const top = environment_top();
10305 size_t const top_local = local_label_top();
10306 scope_push(&statement->compound.scope);
10308 statement_t **anchor = &statement->compound.statements;
10309 bool only_decls_so_far = true;
10310 while (token.type != '}') {
10311 if (token.type == T_EOF) {
10312 errorf(&statement->base.source_position,
10313 "EOF while parsing compound statement");
10316 statement_t *sub_statement = intern_parse_statement();
10317 if (is_invalid_statement(sub_statement)) {
10318 /* an error occurred. if we are at an anchor, return */
10324 if (warning.declaration_after_statement) {
10325 if (sub_statement->kind != STATEMENT_DECLARATION) {
10326 only_decls_so_far = false;
10327 } else if (!only_decls_so_far) {
10328 warningf(&sub_statement->base.source_position,
10329 "ISO C90 forbids mixed declarations and code");
10333 *anchor = sub_statement;
10335 while (sub_statement->base.next != NULL)
10336 sub_statement = sub_statement->base.next;
10338 anchor = &sub_statement->base.next;
10342 /* look over all statements again to produce no effect warnings */
10343 if (warning.unused_value) {
10344 statement_t *sub_statement = statement->compound.statements;
10345 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10346 if (sub_statement->kind != STATEMENT_EXPRESSION)
10348 /* don't emit a warning for the last expression in an expression
10349 * statement as it has always an effect */
10350 if (inside_expression_statement && sub_statement->base.next == NULL)
10353 expression_t *expression = sub_statement->expression.expression;
10354 if (!expression_has_effect(expression)) {
10355 warningf(&expression->base.source_position,
10356 "statement has no effect");
10362 rem_anchor_token('}');
10363 assert(scope == &statement->compound.scope);
10365 environment_pop_to(top);
10366 local_label_pop_to(top_local);
10373 * Initialize builtin types.
10375 static void initialize_builtin_types(void)
10377 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
10378 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
10379 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
10380 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
10381 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
10382 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
10383 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
10384 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
10386 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
10387 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
10388 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
10389 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
10391 /* const version of wchar_t */
10392 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF);
10393 type_const_wchar_t->typedeft.typedefe = type_wchar_t->typedeft.typedefe;
10394 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
10396 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
10400 * Check for unused global static functions and variables
10402 static void check_unused_globals(void)
10404 if (!warning.unused_function && !warning.unused_variable)
10407 for (const entity_t *entity = file_scope->entities; entity != NULL;
10408 entity = entity->base.next) {
10409 if (!is_declaration(entity))
10412 const declaration_t *declaration = &entity->declaration;
10413 if (declaration->used ||
10414 declaration->modifiers & DM_UNUSED ||
10415 declaration->modifiers & DM_USED ||
10416 declaration->storage_class != STORAGE_CLASS_STATIC)
10419 type_t *const type = declaration->type;
10421 if (entity->kind == ENTITY_FUNCTION) {
10422 /* inhibit warning for static inline functions */
10423 if (entity->function.is_inline)
10426 s = entity->function.statement != NULL ? "defined" : "declared";
10431 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10432 type, declaration->base.symbol, s);
10436 static void parse_global_asm(void)
10438 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10443 statement->asms.asm_text = parse_string_literals();
10444 statement->base.next = unit->global_asm;
10445 unit->global_asm = statement;
10454 * Parse a translation unit.
10456 static void parse_translation_unit(void)
10458 add_anchor_token(T_EOF);
10461 unsigned char token_anchor_copy[T_LAST_TOKEN];
10462 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10466 bool anchor_leak = false;
10467 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10468 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10470 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10471 anchor_leak = true;
10474 if (in_gcc_extension) {
10475 errorf(HERE, "Leaked __extension__");
10476 anchor_leak = true;
10483 switch (token.type) {
10486 case T___extension__:
10487 parse_external_declaration();
10491 parse_global_asm();
10495 rem_anchor_token(T_EOF);
10499 if (!strict_mode) {
10501 warningf(HERE, "stray ';' outside of function");
10508 errorf(HERE, "stray %K outside of function", &token);
10509 if (token.type == '(' || token.type == '{' || token.type == '[')
10510 eat_until_matching_token(token.type);
10520 * @return the translation unit or NULL if errors occurred.
10522 void start_parsing(void)
10524 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10525 label_stack = NEW_ARR_F(stack_entry_t, 0);
10526 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10527 diagnostic_count = 0;
10531 type_set_output(stderr);
10532 ast_set_output(stderr);
10534 assert(unit == NULL);
10535 unit = allocate_ast_zero(sizeof(unit[0]));
10537 assert(file_scope == NULL);
10538 file_scope = &unit->scope;
10540 assert(scope == NULL);
10541 scope_push(&unit->scope);
10543 initialize_builtin_types();
10546 translation_unit_t *finish_parsing(void)
10548 /* do NOT use scope_pop() here, this will crash, will it by hand */
10549 assert(scope == &unit->scope);
10552 assert(file_scope == &unit->scope);
10553 check_unused_globals();
10556 DEL_ARR_F(environment_stack);
10557 DEL_ARR_F(label_stack);
10558 DEL_ARR_F(local_label_stack);
10560 translation_unit_t *result = unit;
10567 lookahead_bufpos = 0;
10568 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10571 parse_translation_unit();
10575 * Initialize the parser.
10577 void init_parser(void)
10579 sym_anonymous = symbol_table_insert("<anonymous>");
10581 if (c_mode & _MS) {
10582 /* add predefined symbols for extended-decl-modifier */
10583 sym_align = symbol_table_insert("align");
10584 sym_allocate = symbol_table_insert("allocate");
10585 sym_dllimport = symbol_table_insert("dllimport");
10586 sym_dllexport = symbol_table_insert("dllexport");
10587 sym_naked = symbol_table_insert("naked");
10588 sym_noinline = symbol_table_insert("noinline");
10589 sym_noreturn = symbol_table_insert("noreturn");
10590 sym_nothrow = symbol_table_insert("nothrow");
10591 sym_novtable = symbol_table_insert("novtable");
10592 sym_property = symbol_table_insert("property");
10593 sym_get = symbol_table_insert("get");
10594 sym_put = symbol_table_insert("put");
10595 sym_selectany = symbol_table_insert("selectany");
10596 sym_thread = symbol_table_insert("thread");
10597 sym_uuid = symbol_table_insert("uuid");
10598 sym_deprecated = symbol_table_insert("deprecated");
10599 sym_restrict = symbol_table_insert("restrict");
10600 sym_noalias = symbol_table_insert("noalias");
10602 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10604 init_expression_parsers();
10605 obstack_init(&temp_obst);
10607 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10608 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10612 * Terminate the parser.
10614 void exit_parser(void)
10616 obstack_free(&temp_obst, NULL);