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 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 2
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool have_arguments; /**< True, if this attribute has arguments. */
68 atomic_type_kind_t akind;
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
81 decl_modifiers_t modifiers; /**< declaration modifiers */
82 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
83 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
84 symbol_t *get_property_sym; /**< the name of the get property if set. */
85 symbol_t *put_property_sym; /**< the name of the put property if set. */
90 * An environment for parsing initializers (and compound literals).
92 typedef struct parse_initializer_env_t {
93 type_t *type; /**< the type of the initializer. In case of an
94 array type with unspecified size this gets
95 adjusted to the actual size. */
96 entity_t *entity; /**< the variable that is initialized if any */
97 bool must_be_constant;
98 } parse_initializer_env_t;
100 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
102 /** The current token. */
103 static token_t token;
104 /** The lookahead ring-buffer. */
105 static token_t lookahead_buffer[MAX_LOOKAHEAD];
106 /** Position of the next token in the lookahead buffer. */
107 static int lookahead_bufpos;
108 static stack_entry_t *environment_stack = NULL;
109 static stack_entry_t *label_stack = NULL;
110 static scope_t *file_scope = NULL;
111 static scope_t *current_scope = NULL;
112 /** Point to the current function declaration if inside a function. */
113 static function_t *current_function = NULL;
114 static entity_t *current_init_decl = NULL;
115 static switch_statement_t *current_switch = NULL;
116 static statement_t *current_loop = NULL;
117 static statement_t *current_parent = NULL;
118 static ms_try_statement_t *current_try = NULL;
119 static linkage_kind_t current_linkage = LINKAGE_INVALID;
120 static goto_statement_t *goto_first = NULL;
121 static goto_statement_t *goto_last = NULL;
122 static label_statement_t *label_first = NULL;
123 static label_statement_t *label_last = NULL;
124 /** current translation unit. */
125 static translation_unit_t *unit = NULL;
126 /** true if we are in a type property context (evaluation only for type. */
127 static bool in_type_prop = false;
128 /** true in we are in a __extension__ context. */
129 static bool in_gcc_extension = false;
130 static struct obstack temp_obst;
133 #define PUSH_PARENT(stmt) \
134 statement_t *const prev_parent = current_parent; \
135 ((void)(current_parent = (stmt)))
136 #define POP_PARENT ((void)(current_parent = prev_parent))
138 /** special symbol used for anonymous entities. */
139 static const symbol_t *sym_anonymous = NULL;
141 /* symbols for Microsoft extended-decl-modifier */
142 static const symbol_t *sym_align = NULL;
143 static const symbol_t *sym_allocate = NULL;
144 static const symbol_t *sym_dllimport = NULL;
145 static const symbol_t *sym_dllexport = NULL;
146 static const symbol_t *sym_naked = NULL;
147 static const symbol_t *sym_noinline = NULL;
148 static const symbol_t *sym_noreturn = NULL;
149 static const symbol_t *sym_nothrow = NULL;
150 static const symbol_t *sym_novtable = NULL;
151 static const symbol_t *sym_property = NULL;
152 static const symbol_t *sym_get = NULL;
153 static const symbol_t *sym_put = NULL;
154 static const symbol_t *sym_selectany = NULL;
155 static const symbol_t *sym_thread = NULL;
156 static const symbol_t *sym_uuid = NULL;
157 static const symbol_t *sym_deprecated = NULL;
158 static const symbol_t *sym_restrict = NULL;
159 static const symbol_t *sym_noalias = NULL;
161 /** The token anchor set */
162 static unsigned char token_anchor_set[T_LAST_TOKEN];
164 /** The current source position. */
165 #define HERE (&token.source_position)
167 /** true if we are in GCC mode. */
168 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
170 static type_t *type_valist;
172 static statement_t *parse_compound_statement(bool inside_expression_statement);
173 static statement_t *parse_statement(void);
175 static expression_t *parse_sub_expression(precedence_t);
176 static expression_t *parse_expression(void);
177 static type_t *parse_typename(void);
178 static void parse_externals(void);
179 static void parse_external(void);
181 static void parse_compound_type_entries(compound_t *compound_declaration);
182 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
183 bool may_be_abstract,
184 bool create_compound_member);
185 static entity_t *record_entity(entity_t *entity, bool is_definition);
187 static void semantic_comparison(binary_expression_t *expression);
189 #define STORAGE_CLASSES \
197 #define STORAGE_CLASSES_NO_EXTERN \
204 #define TYPE_QUALIFIERS \
209 case T__forceinline: \
210 case T___attribute__:
212 #define COMPLEX_SPECIFIERS \
214 #define IMAGINARY_SPECIFIERS \
217 #define TYPE_SPECIFIERS \
219 case T___builtin_va_list: \
238 #define DECLARATION_START \
243 #define DECLARATION_START_NO_EXTERN \
244 STORAGE_CLASSES_NO_EXTERN \
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: \
306 * Allocate an AST node with given size and
307 * initialize all fields with zero.
309 static void *allocate_ast_zero(size_t size)
311 void *res = allocate_ast(size);
312 memset(res, 0, size);
316 static size_t get_entity_struct_size(entity_kind_t kind)
318 static const size_t sizes[] = {
319 [ENTITY_VARIABLE] = sizeof(variable_t),
320 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
321 [ENTITY_FUNCTION] = sizeof(function_t),
322 [ENTITY_TYPEDEF] = sizeof(typedef_t),
323 [ENTITY_STRUCT] = sizeof(compound_t),
324 [ENTITY_UNION] = sizeof(compound_t),
325 [ENTITY_ENUM] = sizeof(enum_t),
326 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
327 [ENTITY_LABEL] = sizeof(label_t),
328 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
329 [ENTITY_NAMESPACE] = sizeof(namespace_t)
331 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
332 assert(sizes[kind] != 0);
336 static entity_t *allocate_entity_zero(entity_kind_t kind)
338 size_t size = get_entity_struct_size(kind);
339 entity_t *entity = allocate_ast_zero(size);
345 * Returns the size of a statement node.
347 * @param kind the statement kind
349 static size_t get_statement_struct_size(statement_kind_t kind)
351 static const size_t sizes[] = {
352 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
353 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
354 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
355 [STATEMENT_RETURN] = sizeof(return_statement_t),
356 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
357 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
358 [STATEMENT_IF] = sizeof(if_statement_t),
359 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
360 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
361 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
362 [STATEMENT_BREAK] = sizeof(statement_base_t),
363 [STATEMENT_GOTO] = sizeof(goto_statement_t),
364 [STATEMENT_LABEL] = sizeof(label_statement_t),
365 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
366 [STATEMENT_WHILE] = sizeof(while_statement_t),
367 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
368 [STATEMENT_FOR] = sizeof(for_statement_t),
369 [STATEMENT_ASM] = sizeof(asm_statement_t),
370 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
371 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
373 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
374 assert(sizes[kind] != 0);
379 * Returns the size of an expression node.
381 * @param kind the expression kind
383 static size_t get_expression_struct_size(expression_kind_t kind)
385 static const size_t sizes[] = {
386 [EXPR_INVALID] = sizeof(expression_base_t),
387 [EXPR_REFERENCE] = sizeof(reference_expression_t),
388 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
389 [EXPR_CONST] = sizeof(const_expression_t),
390 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
391 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
392 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
393 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
394 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
395 [EXPR_CALL] = sizeof(call_expression_t),
396 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
397 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
398 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
399 [EXPR_SELECT] = sizeof(select_expression_t),
400 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
401 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
402 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
403 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
404 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
405 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
406 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
407 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
408 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
409 [EXPR_VA_START] = sizeof(va_start_expression_t),
410 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
411 [EXPR_STATEMENT] = sizeof(statement_expression_t),
412 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
414 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
415 return sizes[EXPR_UNARY_FIRST];
417 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
418 return sizes[EXPR_BINARY_FIRST];
420 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
421 assert(sizes[kind] != 0);
426 * Allocate a statement node of given kind and initialize all
429 static statement_t *allocate_statement_zero(statement_kind_t kind)
431 size_t size = get_statement_struct_size(kind);
432 statement_t *res = allocate_ast_zero(size);
434 res->base.kind = kind;
435 res->base.parent = current_parent;
436 res->base.source_position = token.source_position;
441 * Allocate an expression node of given kind and initialize all
444 static expression_t *allocate_expression_zero(expression_kind_t kind)
446 size_t size = get_expression_struct_size(kind);
447 expression_t *res = allocate_ast_zero(size);
449 res->base.kind = kind;
450 res->base.type = type_error_type;
451 res->base.source_position = token.source_position;
456 * Creates a new invalid expression.
458 static expression_t *create_invalid_expression(void)
460 return allocate_expression_zero(EXPR_INVALID);
464 * Creates a new invalid statement.
466 static statement_t *create_invalid_statement(void)
468 return allocate_statement_zero(STATEMENT_INVALID);
472 * Allocate a new empty statement.
474 static statement_t *create_empty_statement(void)
476 return allocate_statement_zero(STATEMENT_EMPTY);
480 * Returns the size of a type node.
482 * @param kind the type kind
484 static size_t get_type_struct_size(type_kind_t kind)
486 static const size_t sizes[] = {
487 [TYPE_ATOMIC] = sizeof(atomic_type_t),
488 [TYPE_COMPLEX] = sizeof(complex_type_t),
489 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
490 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
491 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
492 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
493 [TYPE_ENUM] = sizeof(enum_type_t),
494 [TYPE_FUNCTION] = sizeof(function_type_t),
495 [TYPE_POINTER] = sizeof(pointer_type_t),
496 [TYPE_ARRAY] = sizeof(array_type_t),
497 [TYPE_BUILTIN] = sizeof(builtin_type_t),
498 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
499 [TYPE_TYPEOF] = sizeof(typeof_type_t),
501 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
502 assert(kind <= TYPE_TYPEOF);
503 assert(sizes[kind] != 0);
508 * Allocate a type node of given kind and initialize all
511 * @param kind type kind to allocate
513 static type_t *allocate_type_zero(type_kind_t kind)
515 size_t size = get_type_struct_size(kind);
516 type_t *res = obstack_alloc(type_obst, size);
517 memset(res, 0, size);
518 res->base.kind = kind;
524 * Returns the size of an initializer node.
526 * @param kind the initializer kind
528 static size_t get_initializer_size(initializer_kind_t kind)
530 static const size_t sizes[] = {
531 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
532 [INITIALIZER_STRING] = sizeof(initializer_string_t),
533 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
534 [INITIALIZER_LIST] = sizeof(initializer_list_t),
535 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
537 assert(kind < sizeof(sizes) / sizeof(*sizes));
538 assert(sizes[kind] != 0);
543 * Allocate an initializer node of given kind and initialize all
546 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
548 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
555 * Free a type from the type obstack.
557 static void free_type(void *type)
559 obstack_free(type_obst, type);
563 * Returns the index of the top element of the environment stack.
565 static size_t environment_top(void)
567 return ARR_LEN(environment_stack);
571 * Returns the index of the top element of the global label stack.
573 static size_t label_top(void)
575 return ARR_LEN(label_stack);
579 * Return the next token.
581 static inline void next_token(void)
583 token = lookahead_buffer[lookahead_bufpos];
584 lookahead_buffer[lookahead_bufpos] = lexer_token;
587 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
590 print_token(stderr, &token);
591 fprintf(stderr, "\n");
596 * Return the next token with a given lookahead.
598 static inline const token_t *look_ahead(int num)
600 assert(num > 0 && num <= MAX_LOOKAHEAD);
601 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
602 return &lookahead_buffer[pos];
606 * Adds a token to the token anchor set (a multi-set).
608 static void add_anchor_token(int token_type)
610 assert(0 <= token_type && token_type < T_LAST_TOKEN);
611 ++token_anchor_set[token_type];
614 static int save_and_reset_anchor_state(int token_type)
616 assert(0 <= token_type && token_type < T_LAST_TOKEN);
617 int count = token_anchor_set[token_type];
618 token_anchor_set[token_type] = 0;
622 static void restore_anchor_state(int token_type, int count)
624 assert(0 <= token_type && token_type < T_LAST_TOKEN);
625 token_anchor_set[token_type] = count;
629 * Remove a token from the token anchor set (a multi-set).
631 static void rem_anchor_token(int token_type)
633 assert(0 <= token_type && token_type < T_LAST_TOKEN);
634 assert(token_anchor_set[token_type] != 0);
635 --token_anchor_set[token_type];
638 static bool at_anchor(void)
642 return token_anchor_set[token.type];
646 * Eat tokens until a matching token is found.
648 static void eat_until_matching_token(int type)
652 case '(': end_token = ')'; break;
653 case '{': end_token = '}'; break;
654 case '[': end_token = ']'; break;
655 default: end_token = type; break;
658 unsigned parenthesis_count = 0;
659 unsigned brace_count = 0;
660 unsigned bracket_count = 0;
661 while (token.type != end_token ||
662 parenthesis_count != 0 ||
664 bracket_count != 0) {
665 switch (token.type) {
667 case '(': ++parenthesis_count; break;
668 case '{': ++brace_count; break;
669 case '[': ++bracket_count; break;
672 if (parenthesis_count > 0)
682 if (bracket_count > 0)
685 if (token.type == end_token &&
686 parenthesis_count == 0 &&
700 * Eat input tokens until an anchor is found.
702 static void eat_until_anchor(void)
704 while (token_anchor_set[token.type] == 0) {
705 if (token.type == '(' || token.type == '{' || token.type == '[')
706 eat_until_matching_token(token.type);
711 static void eat_block(void)
713 eat_until_matching_token('{');
714 if (token.type == '}')
718 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
721 * Report a parse error because an expected token was not found.
724 #if defined __GNUC__ && __GNUC__ >= 4
725 __attribute__((sentinel))
727 void parse_error_expected(const char *message, ...)
729 if (message != NULL) {
730 errorf(HERE, "%s", message);
733 va_start(ap, message);
734 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
739 * Report a type error.
741 static void type_error(const char *msg, const source_position_t *source_position,
744 errorf(source_position, "%s, but found type '%T'", msg, type);
748 * Report an incompatible type.
750 static void type_error_incompatible(const char *msg,
751 const source_position_t *source_position, type_t *type1, type_t *type2)
753 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
758 * Expect the the current token is the expected token.
759 * If not, generate an error, eat the current statement,
760 * and goto the end_error label.
762 #define expect(expected) \
764 if (UNLIKELY(token.type != (expected))) { \
765 parse_error_expected(NULL, (expected), NULL); \
766 add_anchor_token(expected); \
767 eat_until_anchor(); \
768 if (token.type == expected) \
770 rem_anchor_token(expected); \
776 static void scope_push(scope_t *new_scope)
778 if (current_scope != NULL) {
779 new_scope->depth = current_scope->depth + 1;
781 new_scope->parent = current_scope;
782 current_scope = new_scope;
785 static void scope_pop(void)
787 current_scope = current_scope->parent;
791 * Search an entity by its symbol in a given namespace.
793 static entity_t *get_entity(const symbol_t *const symbol,
794 namespace_tag_t namespc)
796 entity_t *entity = symbol->entity;
797 for( ; entity != NULL; entity = entity->base.symbol_next) {
798 if (entity->base.namespc == namespc)
806 * pushs an entity on the environment stack and links the corresponding symbol
809 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
811 symbol_t *symbol = entity->base.symbol;
812 entity_namespace_t namespc = entity->base.namespc;
813 assert(namespc != NAMESPACE_INVALID);
815 /* replace/add entity into entity list of the symbol */
818 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
823 /* replace an entry? */
824 if (iter->base.namespc == namespc) {
825 entity->base.symbol_next = iter->base.symbol_next;
831 /* remember old declaration */
833 entry.symbol = symbol;
834 entry.old_entity = iter;
835 entry.namespc = namespc;
836 ARR_APP1(stack_entry_t, *stack_ptr, entry);
840 * Push an entity on the environment stack.
842 static void environment_push(entity_t *entity)
844 assert(entity->base.source_position.input_name != NULL);
845 assert(entity->base.parent_scope != NULL);
846 stack_push(&environment_stack, entity);
850 * Push a declaration on the global label stack.
852 * @param declaration the declaration
854 static void label_push(entity_t *label)
856 /* we abuse the parameters scope as parent for the labels */
857 label->base.parent_scope = ¤t_function->parameters;
858 stack_push(&label_stack, label);
862 * pops symbols from the environment stack until @p new_top is the top element
864 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
866 stack_entry_t *stack = *stack_ptr;
867 size_t top = ARR_LEN(stack);
870 assert(new_top <= top);
874 for(i = top; i > new_top; --i) {
875 stack_entry_t *entry = &stack[i - 1];
877 entity_t *old_entity = entry->old_entity;
878 symbol_t *symbol = entry->symbol;
879 entity_namespace_t namespc = entry->namespc;
881 /* replace with old_entity/remove */
884 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
886 assert(iter != NULL);
887 /* replace an entry? */
888 if (iter->base.namespc == namespc)
892 /* restore definition from outer scopes (if there was one) */
893 if (old_entity != NULL) {
894 old_entity->base.symbol_next = iter->base.symbol_next;
895 *anchor = old_entity;
897 /* remove entry from list */
898 *anchor = iter->base.symbol_next;
902 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
906 * Pop all entries from the environment stack until the new_top
909 * @param new_top the new stack top
911 static void environment_pop_to(size_t new_top)
913 stack_pop_to(&environment_stack, new_top);
917 * Pop all entries from the global label stack until the new_top
920 * @param new_top the new stack top
922 static void label_pop_to(size_t new_top)
924 stack_pop_to(&label_stack, new_top);
927 static int get_akind_rank(atomic_type_kind_t akind)
932 static int get_rank(const type_t *type)
934 assert(!is_typeref(type));
935 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
936 * and esp. footnote 108). However we can't fold constants (yet), so we
937 * can't decide whether unsigned int is possible, while int always works.
938 * (unsigned int would be preferable when possible... for stuff like
939 * struct { enum { ... } bla : 4; } ) */
940 if (type->kind == TYPE_ENUM)
941 return get_akind_rank(ATOMIC_TYPE_INT);
943 assert(type->kind == TYPE_ATOMIC);
944 return get_akind_rank(type->atomic.akind);
947 static type_t *promote_integer(type_t *type)
949 if (type->kind == TYPE_BITFIELD)
950 type = type->bitfield.base_type;
952 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
959 * Create a cast expression.
961 * @param expression the expression to cast
962 * @param dest_type the destination type
964 static expression_t *create_cast_expression(expression_t *expression,
967 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
969 cast->unary.value = expression;
970 cast->base.type = dest_type;
976 * Check if a given expression represents the 0 pointer constant.
978 static bool is_null_pointer_constant(const expression_t *expression)
980 /* skip void* cast */
981 if (expression->kind == EXPR_UNARY_CAST
982 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
983 expression = expression->unary.value;
986 /* TODO: not correct yet, should be any constant integer expression
987 * which evaluates to 0 */
988 if (expression->kind != EXPR_CONST)
991 type_t *const type = skip_typeref(expression->base.type);
992 if (!is_type_integer(type))
995 return expression->conste.v.int_value == 0;
999 * Create an implicit cast expression.
1001 * @param expression the expression to cast
1002 * @param dest_type the destination type
1004 static expression_t *create_implicit_cast(expression_t *expression,
1007 type_t *const source_type = expression->base.type;
1009 if (source_type == dest_type)
1012 return create_cast_expression(expression, dest_type);
1015 typedef enum assign_error_t {
1017 ASSIGN_ERROR_INCOMPATIBLE,
1018 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1019 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1020 ASSIGN_WARNING_POINTER_FROM_INT,
1021 ASSIGN_WARNING_INT_FROM_POINTER
1024 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1025 const expression_t *const right,
1026 const char *context,
1027 const source_position_t *source_position)
1029 type_t *const orig_type_right = right->base.type;
1030 type_t *const type_left = skip_typeref(orig_type_left);
1031 type_t *const type_right = skip_typeref(orig_type_right);
1034 case ASSIGN_SUCCESS:
1036 case ASSIGN_ERROR_INCOMPATIBLE:
1037 errorf(source_position,
1038 "destination type '%T' in %s is incompatible with type '%T'",
1039 orig_type_left, context, orig_type_right);
1042 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1043 if (warning.other) {
1044 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1045 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1047 /* the left type has all qualifiers from the right type */
1048 unsigned missing_qualifiers
1049 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1050 warningf(source_position,
1051 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1052 orig_type_left, context, orig_type_right, missing_qualifiers);
1057 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1058 if (warning.other) {
1059 warningf(source_position,
1060 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1061 orig_type_left, context, right, orig_type_right);
1065 case ASSIGN_WARNING_POINTER_FROM_INT:
1066 if (warning.other) {
1067 warningf(source_position,
1068 "%s makes pointer '%T' from integer '%T' without a cast",
1069 context, orig_type_left, orig_type_right);
1073 case ASSIGN_WARNING_INT_FROM_POINTER:
1074 if (warning.other) {
1075 warningf(source_position,
1076 "%s makes integer '%T' from pointer '%T' without a cast",
1077 context, orig_type_left, orig_type_right);
1082 panic("invalid error value");
1086 /** Implements the rules from § 6.5.16.1 */
1087 static assign_error_t semantic_assign(type_t *orig_type_left,
1088 const expression_t *const right)
1090 type_t *const orig_type_right = right->base.type;
1091 type_t *const type_left = skip_typeref(orig_type_left);
1092 type_t *const type_right = skip_typeref(orig_type_right);
1094 if (is_type_pointer(type_left)) {
1095 if (is_null_pointer_constant(right)) {
1096 return ASSIGN_SUCCESS;
1097 } else if (is_type_pointer(type_right)) {
1098 type_t *points_to_left
1099 = skip_typeref(type_left->pointer.points_to);
1100 type_t *points_to_right
1101 = skip_typeref(type_right->pointer.points_to);
1102 assign_error_t res = ASSIGN_SUCCESS;
1104 /* the left type has all qualifiers from the right type */
1105 unsigned missing_qualifiers
1106 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1107 if (missing_qualifiers != 0) {
1108 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1111 points_to_left = get_unqualified_type(points_to_left);
1112 points_to_right = get_unqualified_type(points_to_right);
1114 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1117 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1118 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1119 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1122 if (!types_compatible(points_to_left, points_to_right)) {
1123 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1127 } else if (is_type_integer(type_right)) {
1128 return ASSIGN_WARNING_POINTER_FROM_INT;
1130 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1131 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1132 && is_type_pointer(type_right))) {
1133 return ASSIGN_SUCCESS;
1134 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1135 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1136 type_t *const unqual_type_left = get_unqualified_type(type_left);
1137 type_t *const unqual_type_right = get_unqualified_type(type_right);
1138 if (types_compatible(unqual_type_left, unqual_type_right)) {
1139 return ASSIGN_SUCCESS;
1141 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1142 return ASSIGN_WARNING_INT_FROM_POINTER;
1145 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1146 return ASSIGN_SUCCESS;
1148 return ASSIGN_ERROR_INCOMPATIBLE;
1151 static expression_t *parse_constant_expression(void)
1153 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1155 if (!is_constant_expression(result)) {
1156 errorf(&result->base.source_position,
1157 "expression '%E' is not constant\n", result);
1163 static expression_t *parse_assignment_expression(void)
1165 return parse_sub_expression(PREC_ASSIGNMENT);
1168 static string_t parse_string_literals(void)
1170 assert(token.type == T_STRING_LITERAL);
1171 string_t result = token.v.string;
1175 while (token.type == T_STRING_LITERAL) {
1176 result = concat_strings(&result, &token.v.string);
1183 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1184 [GNU_AK_CONST] = "const",
1185 [GNU_AK_VOLATILE] = "volatile",
1186 [GNU_AK_CDECL] = "cdecl",
1187 [GNU_AK_STDCALL] = "stdcall",
1188 [GNU_AK_FASTCALL] = "fastcall",
1189 [GNU_AK_DEPRECATED] = "deprecated",
1190 [GNU_AK_NOINLINE] = "noinline",
1191 [GNU_AK_NORETURN] = "noreturn",
1192 [GNU_AK_NAKED] = "naked",
1193 [GNU_AK_PURE] = "pure",
1194 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1195 [GNU_AK_MALLOC] = "malloc",
1196 [GNU_AK_WEAK] = "weak",
1197 [GNU_AK_CONSTRUCTOR] = "constructor",
1198 [GNU_AK_DESTRUCTOR] = "destructor",
1199 [GNU_AK_NOTHROW] = "nothrow",
1200 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1201 [GNU_AK_COMMON] = "common",
1202 [GNU_AK_NOCOMMON] = "nocommon",
1203 [GNU_AK_PACKED] = "packed",
1204 [GNU_AK_SHARED] = "shared",
1205 [GNU_AK_NOTSHARED] = "notshared",
1206 [GNU_AK_USED] = "used",
1207 [GNU_AK_UNUSED] = "unused",
1208 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1209 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1210 [GNU_AK_LONGCALL] = "longcall",
1211 [GNU_AK_SHORTCALL] = "shortcall",
1212 [GNU_AK_LONG_CALL] = "long_call",
1213 [GNU_AK_SHORT_CALL] = "short_call",
1214 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1215 [GNU_AK_INTERRUPT] = "interrupt",
1216 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1217 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1218 [GNU_AK_NESTING] = "nesting",
1219 [GNU_AK_NEAR] = "near",
1220 [GNU_AK_FAR] = "far",
1221 [GNU_AK_SIGNAL] = "signal",
1222 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1223 [GNU_AK_TINY_DATA] = "tiny_data",
1224 [GNU_AK_SAVEALL] = "saveall",
1225 [GNU_AK_FLATTEN] = "flatten",
1226 [GNU_AK_SSEREGPARM] = "sseregparm",
1227 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1228 [GNU_AK_RETURN_TWICE] = "return_twice",
1229 [GNU_AK_MAY_ALIAS] = "may_alias",
1230 [GNU_AK_MS_STRUCT] = "ms_struct",
1231 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1232 [GNU_AK_DLLIMPORT] = "dllimport",
1233 [GNU_AK_DLLEXPORT] = "dllexport",
1234 [GNU_AK_ALIGNED] = "aligned",
1235 [GNU_AK_ALIAS] = "alias",
1236 [GNU_AK_SECTION] = "section",
1237 [GNU_AK_FORMAT] = "format",
1238 [GNU_AK_FORMAT_ARG] = "format_arg",
1239 [GNU_AK_WEAKREF] = "weakref",
1240 [GNU_AK_NONNULL] = "nonnull",
1241 [GNU_AK_TLS_MODEL] = "tls_model",
1242 [GNU_AK_VISIBILITY] = "visibility",
1243 [GNU_AK_REGPARM] = "regparm",
1244 [GNU_AK_MODE] = "mode",
1245 [GNU_AK_MODEL] = "model",
1246 [GNU_AK_TRAP_EXIT] = "trap_exit",
1247 [GNU_AK_SP_SWITCH] = "sp_switch",
1248 [GNU_AK_SENTINEL] = "sentinel"
1252 * compare two string, ignoring double underscores on the second.
1254 static int strcmp_underscore(const char *s1, const char *s2)
1256 if (s2[0] == '_' && s2[1] == '_') {
1257 size_t len2 = strlen(s2);
1258 size_t len1 = strlen(s1);
1259 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1260 return strncmp(s1, s2+2, len2-4);
1264 return strcmp(s1, s2);
1268 * Allocate a new gnu temporal attribute.
1270 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1272 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1273 attribute->kind = kind;
1274 attribute->next = NULL;
1275 attribute->invalid = false;
1276 attribute->have_arguments = false;
1282 * parse one constant expression argument.
1284 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1286 expression_t *expression;
1287 add_anchor_token(')');
1288 expression = parse_constant_expression();
1289 rem_anchor_token(')');
1291 attribute->u.argument = fold_constant(expression);
1294 attribute->invalid = true;
1298 * parse a list of constant expressions arguments.
1300 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1302 argument_list_t **list = &attribute->u.arguments;
1303 argument_list_t *entry;
1304 expression_t *expression;
1305 add_anchor_token(')');
1306 add_anchor_token(',');
1308 expression = parse_constant_expression();
1309 entry = obstack_alloc(&temp_obst, sizeof(entry));
1310 entry->argument = fold_constant(expression);
1313 list = &entry->next;
1314 if (token.type != ',')
1318 rem_anchor_token(',');
1319 rem_anchor_token(')');
1323 attribute->invalid = true;
1327 * parse one string literal argument.
1329 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1332 add_anchor_token('(');
1333 if (token.type != T_STRING_LITERAL) {
1334 parse_error_expected("while parsing attribute directive",
1335 T_STRING_LITERAL, NULL);
1338 *string = parse_string_literals();
1339 rem_anchor_token('(');
1343 attribute->invalid = true;
1347 * parse one tls model.
1349 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1351 static const char *const tls_models[] = {
1357 string_t string = { NULL, 0 };
1358 parse_gnu_attribute_string_arg(attribute, &string);
1359 if (string.begin != NULL) {
1360 for(size_t i = 0; i < 4; ++i) {
1361 if (strcmp(tls_models[i], string.begin) == 0) {
1362 attribute->u.value = i;
1366 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1368 attribute->invalid = true;
1372 * parse one tls model.
1374 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1376 static const char *const visibilities[] = {
1382 string_t string = { NULL, 0 };
1383 parse_gnu_attribute_string_arg(attribute, &string);
1384 if (string.begin != NULL) {
1385 for(size_t i = 0; i < 4; ++i) {
1386 if (strcmp(visibilities[i], string.begin) == 0) {
1387 attribute->u.value = i;
1391 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1393 attribute->invalid = true;
1397 * parse one (code) model.
1399 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1401 static const char *const visibilities[] = {
1406 string_t string = { NULL, 0 };
1407 parse_gnu_attribute_string_arg(attribute, &string);
1408 if (string.begin != NULL) {
1409 for(int i = 0; i < 3; ++i) {
1410 if (strcmp(visibilities[i], string.begin) == 0) {
1411 attribute->u.value = i;
1415 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1417 attribute->invalid = true;
1420 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1422 /* TODO: find out what is allowed here... */
1424 /* at least: byte, word, pointer, list of machine modes
1425 * __XXX___ is interpreted as XXX */
1426 add_anchor_token(')');
1428 if (token.type != T_IDENTIFIER) {
1429 expect(T_IDENTIFIER);
1432 /* This isn't really correct, the backend should provide a list of machine
1433 * specific modes (according to gcc philosophy that is...) */
1434 const char *symbol_str = token.v.symbol->string;
1435 if (strcmp_underscore("QI", symbol_str) == 0 ||
1436 strcmp_underscore("byte", symbol_str) == 0) {
1437 attribute->u.akind = ATOMIC_TYPE_CHAR;
1438 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1439 attribute->u.akind = ATOMIC_TYPE_SHORT;
1440 } else if (strcmp_underscore("SI", symbol_str) == 0
1441 || strcmp_underscore("word", symbol_str) == 0
1442 || strcmp_underscore("pointer", symbol_str) == 0) {
1443 attribute->u.akind = ATOMIC_TYPE_INT;
1444 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1445 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1448 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1449 attribute->invalid = true;
1453 rem_anchor_token(')');
1457 attribute->invalid = true;
1461 * parse one interrupt argument.
1463 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1465 static const char *const interrupts[] = {
1472 string_t string = { NULL, 0 };
1473 parse_gnu_attribute_string_arg(attribute, &string);
1474 if (string.begin != NULL) {
1475 for(size_t i = 0; i < 5; ++i) {
1476 if (strcmp(interrupts[i], string.begin) == 0) {
1477 attribute->u.value = i;
1481 errorf(HERE, "'%s' is not an interrupt", string.begin);
1483 attribute->invalid = true;
1487 * parse ( identifier, const expression, const expression )
1489 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1491 static const char *const format_names[] = {
1499 if (token.type != T_IDENTIFIER) {
1500 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1503 const char *name = token.v.symbol->string;
1504 for(i = 0; i < 4; ++i) {
1505 if (strcmp_underscore(format_names[i], name) == 0)
1509 if (warning.attribute)
1510 warningf(HERE, "'%s' is an unrecognized format function type", name);
1515 add_anchor_token(')');
1516 add_anchor_token(',');
1517 parse_constant_expression();
1518 rem_anchor_token(',');
1519 rem_anchor_token(')');
1522 add_anchor_token(')');
1523 parse_constant_expression();
1524 rem_anchor_token(')');
1528 attribute->u.value = true;
1531 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1533 if (!attribute->have_arguments)
1536 /* should have no arguments */
1537 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1538 eat_until_matching_token('(');
1539 /* we have already consumed '(', so we stop before ')', eat it */
1541 attribute->invalid = true;
1545 * Parse one GNU attribute.
1547 * Note that attribute names can be specified WITH or WITHOUT
1548 * double underscores, ie const or __const__.
1550 * The following attributes are parsed without arguments
1575 * no_instrument_function
1576 * warn_unused_result
1593 * externally_visible
1601 * The following attributes are parsed with arguments
1602 * aligned( const expression )
1603 * alias( string literal )
1604 * section( string literal )
1605 * format( identifier, const expression, const expression )
1606 * format_arg( const expression )
1607 * tls_model( string literal )
1608 * visibility( string literal )
1609 * regparm( const expression )
1610 * model( string leteral )
1611 * trap_exit( const expression )
1612 * sp_switch( string literal )
1614 * The following attributes might have arguments
1615 * weak_ref( string literal )
1616 * non_null( const expression // ',' )
1617 * interrupt( string literal )
1618 * sentinel( constant expression )
1620 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1622 gnu_attribute_t *head = *attributes;
1623 gnu_attribute_t *last = *attributes;
1624 decl_modifiers_t modifiers = 0;
1625 gnu_attribute_t *attribute;
1627 eat(T___attribute__);
1631 if (token.type != ')') {
1632 /* find the end of the list */
1634 while (last->next != NULL)
1638 /* non-empty attribute list */
1641 if (token.type == T_const) {
1643 } else if (token.type == T_volatile) {
1645 } else if (token.type == T_cdecl) {
1646 /* __attribute__((cdecl)), WITH ms mode */
1648 } else if (token.type == T_IDENTIFIER) {
1649 const symbol_t *sym = token.v.symbol;
1652 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1659 for(i = 0; i < GNU_AK_LAST; ++i) {
1660 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1663 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1666 if (kind == GNU_AK_LAST) {
1667 if (warning.attribute)
1668 warningf(HERE, "'%s' attribute directive ignored", name);
1670 /* skip possible arguments */
1671 if (token.type == '(') {
1672 eat_until_matching_token(')');
1675 /* check for arguments */
1676 attribute = allocate_gnu_attribute(kind);
1677 if (token.type == '(') {
1679 if (token.type == ')') {
1680 /* empty args are allowed */
1683 attribute->have_arguments = true;
1687 case GNU_AK_VOLATILE:
1692 case GNU_AK_NOCOMMON:
1694 case GNU_AK_NOTSHARED:
1695 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1696 case GNU_AK_WARN_UNUSED_RESULT:
1697 case GNU_AK_LONGCALL:
1698 case GNU_AK_SHORTCALL:
1699 case GNU_AK_LONG_CALL:
1700 case GNU_AK_SHORT_CALL:
1701 case GNU_AK_FUNCTION_VECTOR:
1702 case GNU_AK_INTERRUPT_HANDLER:
1703 case GNU_AK_NMI_HANDLER:
1704 case GNU_AK_NESTING:
1708 case GNU_AK_EIGTHBIT_DATA:
1709 case GNU_AK_TINY_DATA:
1710 case GNU_AK_SAVEALL:
1711 case GNU_AK_FLATTEN:
1712 case GNU_AK_SSEREGPARM:
1713 case GNU_AK_EXTERNALLY_VISIBLE:
1714 case GNU_AK_RETURN_TWICE:
1715 case GNU_AK_MAY_ALIAS:
1716 case GNU_AK_MS_STRUCT:
1717 case GNU_AK_GCC_STRUCT:
1720 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1721 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1722 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1723 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1724 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1725 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1726 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1727 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1728 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1729 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1730 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1731 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1732 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1733 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1734 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1735 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1736 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1737 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1739 case GNU_AK_ALIGNED:
1740 /* __align__ may be used without an argument */
1741 if (attribute->have_arguments) {
1742 parse_gnu_attribute_const_arg(attribute);
1746 case GNU_AK_FORMAT_ARG:
1747 case GNU_AK_REGPARM:
1748 case GNU_AK_TRAP_EXIT:
1749 if (!attribute->have_arguments) {
1750 /* should have arguments */
1751 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1752 attribute->invalid = true;
1754 parse_gnu_attribute_const_arg(attribute);
1757 case GNU_AK_SECTION:
1758 case GNU_AK_SP_SWITCH:
1759 if (!attribute->have_arguments) {
1760 /* should have arguments */
1761 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1762 attribute->invalid = true;
1764 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1767 if (!attribute->have_arguments) {
1768 /* should have arguments */
1769 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1770 attribute->invalid = true;
1772 parse_gnu_attribute_format_args(attribute);
1774 case GNU_AK_WEAKREF:
1775 /* may have one string argument */
1776 if (attribute->have_arguments)
1777 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1779 case GNU_AK_NONNULL:
1780 if (attribute->have_arguments)
1781 parse_gnu_attribute_const_arg_list(attribute);
1783 case GNU_AK_TLS_MODEL:
1784 if (!attribute->have_arguments) {
1785 /* should have arguments */
1786 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1788 parse_gnu_attribute_tls_model_arg(attribute);
1790 case GNU_AK_VISIBILITY:
1791 if (!attribute->have_arguments) {
1792 /* should have arguments */
1793 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1795 parse_gnu_attribute_visibility_arg(attribute);
1798 if (!attribute->have_arguments) {
1799 /* should have arguments */
1800 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1802 parse_gnu_attribute_model_arg(attribute);
1806 if (!attribute->have_arguments) {
1807 /* should have arguments */
1808 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1810 parse_gnu_attribute_mode_arg(attribute);
1813 case GNU_AK_INTERRUPT:
1814 /* may have one string argument */
1815 if (attribute->have_arguments)
1816 parse_gnu_attribute_interrupt_arg(attribute);
1818 case GNU_AK_SENTINEL:
1819 /* may have one string argument */
1820 if (attribute->have_arguments)
1821 parse_gnu_attribute_const_arg(attribute);
1824 /* already handled */
1828 check_no_argument(attribute, name);
1831 if (attribute != NULL) {
1833 last->next = attribute;
1836 head = last = attribute;
1840 if (token.type != ',')
1854 * Parse GNU attributes.
1856 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1858 decl_modifiers_t modifiers = 0;
1861 switch (token.type) {
1862 case T___attribute__:
1863 modifiers |= parse_gnu_attribute(attributes);
1869 if (token.type != T_STRING_LITERAL) {
1870 parse_error_expected("while parsing assembler attribute",
1871 T_STRING_LITERAL, NULL);
1872 eat_until_matching_token('(');
1875 parse_string_literals();
1880 case T_cdecl: modifiers |= DM_CDECL; break;
1881 case T__fastcall: modifiers |= DM_FASTCALL; break;
1882 case T__stdcall: modifiers |= DM_STDCALL; break;
1885 /* TODO record modifier */
1887 warningf(HERE, "Ignoring declaration modifier %K", &token);
1891 default: return modifiers;
1898 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1900 static variable_t *determine_lhs_var(expression_t *const expr,
1901 variable_t *lhs_var)
1903 switch (expr->kind) {
1904 case EXPR_REFERENCE: {
1905 entity_t *const entity = expr->reference.entity;
1906 /* we should only find variables as lavlues... */
1907 if (entity->base.kind != ENTITY_VARIABLE)
1910 return &entity->variable;
1913 case EXPR_ARRAY_ACCESS: {
1914 expression_t *const ref = expr->array_access.array_ref;
1915 variable_t * var = NULL;
1916 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1917 var = determine_lhs_var(ref, lhs_var);
1920 mark_vars_read(expr->select.compound, lhs_var);
1922 mark_vars_read(expr->array_access.index, lhs_var);
1927 if (is_type_compound(skip_typeref(expr->base.type))) {
1928 return determine_lhs_var(expr->select.compound, lhs_var);
1930 mark_vars_read(expr->select.compound, lhs_var);
1935 case EXPR_UNARY_DEREFERENCE: {
1936 expression_t *const val = expr->unary.value;
1937 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1939 return determine_lhs_var(val->unary.value, lhs_var);
1941 mark_vars_read(val, NULL);
1947 mark_vars_read(expr, NULL);
1952 #define VAR_ANY ((variable_t*)-1)
1955 * Mark declarations, which are read. This is used to deted variables, which
1959 * x is not marked as "read", because it is only read to calculate its own new
1963 * x and y are not detected as "not read", because multiple variables are
1966 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1968 switch (expr->kind) {
1969 case EXPR_REFERENCE: {
1970 entity_t *const entity = expr->reference.entity;
1971 if (entity->kind != ENTITY_VARIABLE)
1974 variable_t *variable = &entity->variable;
1975 if (lhs_var != variable && lhs_var != VAR_ANY) {
1976 variable->read = true;
1982 // TODO respect pure/const
1983 mark_vars_read(expr->call.function, NULL);
1984 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1985 mark_vars_read(arg->expression, NULL);
1989 case EXPR_CONDITIONAL:
1990 // TODO lhs_decl should depend on whether true/false have an effect
1991 mark_vars_read(expr->conditional.condition, NULL);
1992 if (expr->conditional.true_expression != NULL)
1993 mark_vars_read(expr->conditional.true_expression, lhs_var);
1994 mark_vars_read(expr->conditional.false_expression, lhs_var);
1998 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2000 mark_vars_read(expr->select.compound, lhs_var);
2003 case EXPR_ARRAY_ACCESS: {
2004 expression_t *const ref = expr->array_access.array_ref;
2005 mark_vars_read(ref, lhs_var);
2006 lhs_var = determine_lhs_var(ref, lhs_var);
2007 mark_vars_read(expr->array_access.index, lhs_var);
2012 mark_vars_read(expr->va_arge.ap, lhs_var);
2015 case EXPR_UNARY_CAST:
2016 /* Special case: Use void cast to mark a variable as "read" */
2017 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2022 case EXPR_UNARY_THROW:
2023 if (expr->unary.value == NULL)
2026 case EXPR_UNARY_DEREFERENCE:
2027 case EXPR_UNARY_DELETE:
2028 case EXPR_UNARY_DELETE_ARRAY:
2029 if (lhs_var == VAR_ANY)
2033 case EXPR_UNARY_NEGATE:
2034 case EXPR_UNARY_PLUS:
2035 case EXPR_UNARY_BITWISE_NEGATE:
2036 case EXPR_UNARY_NOT:
2037 case EXPR_UNARY_TAKE_ADDRESS:
2038 case EXPR_UNARY_POSTFIX_INCREMENT:
2039 case EXPR_UNARY_POSTFIX_DECREMENT:
2040 case EXPR_UNARY_PREFIX_INCREMENT:
2041 case EXPR_UNARY_PREFIX_DECREMENT:
2042 case EXPR_UNARY_CAST_IMPLICIT:
2043 case EXPR_UNARY_ASSUME:
2045 mark_vars_read(expr->unary.value, lhs_var);
2048 case EXPR_BINARY_ADD:
2049 case EXPR_BINARY_SUB:
2050 case EXPR_BINARY_MUL:
2051 case EXPR_BINARY_DIV:
2052 case EXPR_BINARY_MOD:
2053 case EXPR_BINARY_EQUAL:
2054 case EXPR_BINARY_NOTEQUAL:
2055 case EXPR_BINARY_LESS:
2056 case EXPR_BINARY_LESSEQUAL:
2057 case EXPR_BINARY_GREATER:
2058 case EXPR_BINARY_GREATEREQUAL:
2059 case EXPR_BINARY_BITWISE_AND:
2060 case EXPR_BINARY_BITWISE_OR:
2061 case EXPR_BINARY_BITWISE_XOR:
2062 case EXPR_BINARY_LOGICAL_AND:
2063 case EXPR_BINARY_LOGICAL_OR:
2064 case EXPR_BINARY_SHIFTLEFT:
2065 case EXPR_BINARY_SHIFTRIGHT:
2066 case EXPR_BINARY_COMMA:
2067 case EXPR_BINARY_ISGREATER:
2068 case EXPR_BINARY_ISGREATEREQUAL:
2069 case EXPR_BINARY_ISLESS:
2070 case EXPR_BINARY_ISLESSEQUAL:
2071 case EXPR_BINARY_ISLESSGREATER:
2072 case EXPR_BINARY_ISUNORDERED:
2073 mark_vars_read(expr->binary.left, lhs_var);
2074 mark_vars_read(expr->binary.right, lhs_var);
2077 case EXPR_BINARY_ASSIGN:
2078 case EXPR_BINARY_MUL_ASSIGN:
2079 case EXPR_BINARY_DIV_ASSIGN:
2080 case EXPR_BINARY_MOD_ASSIGN:
2081 case EXPR_BINARY_ADD_ASSIGN:
2082 case EXPR_BINARY_SUB_ASSIGN:
2083 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2084 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2085 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2086 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2087 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2088 if (lhs_var == VAR_ANY)
2090 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2091 mark_vars_read(expr->binary.right, lhs_var);
2096 determine_lhs_var(expr->va_starte.ap, lhs_var);
2102 case EXPR_CHARACTER_CONSTANT:
2103 case EXPR_WIDE_CHARACTER_CONSTANT:
2104 case EXPR_STRING_LITERAL:
2105 case EXPR_WIDE_STRING_LITERAL:
2106 case EXPR_COMPOUND_LITERAL: // TODO init?
2108 case EXPR_CLASSIFY_TYPE:
2111 case EXPR_BUILTIN_SYMBOL:
2112 case EXPR_BUILTIN_CONSTANT_P:
2113 case EXPR_BUILTIN_PREFETCH:
2115 case EXPR_STATEMENT: // TODO
2116 case EXPR_LABEL_ADDRESS:
2117 case EXPR_BINARY_BUILTIN_EXPECT:
2118 case EXPR_REFERENCE_ENUM_VALUE:
2122 panic("unhandled expression");
2125 static designator_t *parse_designation(void)
2127 designator_t *result = NULL;
2128 designator_t *last = NULL;
2131 designator_t *designator;
2132 switch (token.type) {
2134 designator = allocate_ast_zero(sizeof(designator[0]));
2135 designator->source_position = token.source_position;
2137 add_anchor_token(']');
2138 designator->array_index = parse_constant_expression();
2139 rem_anchor_token(']');
2143 designator = allocate_ast_zero(sizeof(designator[0]));
2144 designator->source_position = token.source_position;
2146 if (token.type != T_IDENTIFIER) {
2147 parse_error_expected("while parsing designator",
2148 T_IDENTIFIER, NULL);
2151 designator->symbol = token.v.symbol;
2159 assert(designator != NULL);
2161 last->next = designator;
2163 result = designator;
2171 static initializer_t *initializer_from_string(array_type_t *type,
2172 const string_t *const string)
2174 /* TODO: check len vs. size of array type */
2177 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2178 initializer->string.string = *string;
2183 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2184 wide_string_t *const string)
2186 /* TODO: check len vs. size of array type */
2189 initializer_t *const initializer =
2190 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2191 initializer->wide_string.string = *string;
2197 * Build an initializer from a given expression.
2199 static initializer_t *initializer_from_expression(type_t *orig_type,
2200 expression_t *expression)
2202 /* TODO check that expression is a constant expression */
2204 /* § 6.7.8.14/15 char array may be initialized by string literals */
2205 type_t *type = skip_typeref(orig_type);
2206 type_t *expr_type_orig = expression->base.type;
2207 type_t *expr_type = skip_typeref(expr_type_orig);
2208 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2209 array_type_t *const array_type = &type->array;
2210 type_t *const element_type = skip_typeref(array_type->element_type);
2212 if (element_type->kind == TYPE_ATOMIC) {
2213 atomic_type_kind_t akind = element_type->atomic.akind;
2214 switch (expression->kind) {
2215 case EXPR_STRING_LITERAL:
2216 if (akind == ATOMIC_TYPE_CHAR
2217 || akind == ATOMIC_TYPE_SCHAR
2218 || akind == ATOMIC_TYPE_UCHAR) {
2219 return initializer_from_string(array_type,
2220 &expression->string.value);
2223 case EXPR_WIDE_STRING_LITERAL: {
2224 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2225 if (get_unqualified_type(element_type) == bare_wchar_type) {
2226 return initializer_from_wide_string(array_type,
2227 &expression->wide_string.value);
2237 assign_error_t error = semantic_assign(type, expression);
2238 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2240 report_assign_error(error, type, expression, "initializer",
2241 &expression->base.source_position);
2243 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2245 if (type->kind == TYPE_BITFIELD) {
2246 type = type->bitfield.base_type;
2249 result->value.value = create_implicit_cast(expression, type);
2255 * Checks if a given expression can be used as an constant initializer.
2257 static bool is_initializer_constant(const expression_t *expression)
2259 return is_constant_expression(expression)
2260 || is_address_constant(expression);
2264 * Parses an scalar initializer.
2266 * § 6.7.8.11; eat {} without warning
2268 static initializer_t *parse_scalar_initializer(type_t *type,
2269 bool must_be_constant)
2271 /* there might be extra {} hierarchies */
2273 if (token.type == '{') {
2275 warningf(HERE, "extra curly braces around scalar initializer");
2279 } while (token.type == '{');
2282 expression_t *expression = parse_assignment_expression();
2283 mark_vars_read(expression, NULL);
2284 if (must_be_constant && !is_initializer_constant(expression)) {
2285 errorf(&expression->base.source_position,
2286 "Initialisation expression '%E' is not constant\n",
2290 initializer_t *initializer = initializer_from_expression(type, expression);
2292 if (initializer == NULL) {
2293 errorf(&expression->base.source_position,
2294 "expression '%E' (type '%T') doesn't match expected type '%T'",
2295 expression, expression->base.type, type);
2300 bool additional_warning_displayed = false;
2301 while (braces > 0) {
2302 if (token.type == ',') {
2305 if (token.type != '}') {
2306 if (!additional_warning_displayed && warning.other) {
2307 warningf(HERE, "additional elements in scalar initializer");
2308 additional_warning_displayed = true;
2319 * An entry in the type path.
2321 typedef struct type_path_entry_t type_path_entry_t;
2322 struct type_path_entry_t {
2323 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2325 size_t index; /**< For array types: the current index. */
2326 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2331 * A type path expression a position inside compound or array types.
2333 typedef struct type_path_t type_path_t;
2334 struct type_path_t {
2335 type_path_entry_t *path; /**< An flexible array containing the current path. */
2336 type_t *top_type; /**< type of the element the path points */
2337 size_t max_index; /**< largest index in outermost array */
2341 * Prints a type path for debugging.
2343 static __attribute__((unused)) void debug_print_type_path(
2344 const type_path_t *path)
2346 size_t len = ARR_LEN(path->path);
2348 for(size_t i = 0; i < len; ++i) {
2349 const type_path_entry_t *entry = & path->path[i];
2351 type_t *type = skip_typeref(entry->type);
2352 if (is_type_compound(type)) {
2353 /* in gcc mode structs can have no members */
2354 if (entry->v.compound_entry == NULL) {
2358 fprintf(stderr, ".%s",
2359 entry->v.compound_entry->base.symbol->string);
2360 } else if (is_type_array(type)) {
2361 fprintf(stderr, "[%zu]", entry->v.index);
2363 fprintf(stderr, "-INVALID-");
2366 if (path->top_type != NULL) {
2367 fprintf(stderr, " (");
2368 print_type(path->top_type);
2369 fprintf(stderr, ")");
2374 * Return the top type path entry, ie. in a path
2375 * (type).a.b returns the b.
2377 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2379 size_t len = ARR_LEN(path->path);
2381 return &path->path[len-1];
2385 * Enlarge the type path by an (empty) element.
2387 static type_path_entry_t *append_to_type_path(type_path_t *path)
2389 size_t len = ARR_LEN(path->path);
2390 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2392 type_path_entry_t *result = & path->path[len];
2393 memset(result, 0, sizeof(result[0]));
2398 * Descending into a sub-type. Enter the scope of the current top_type.
2400 static void descend_into_subtype(type_path_t *path)
2402 type_t *orig_top_type = path->top_type;
2403 type_t *top_type = skip_typeref(orig_top_type);
2405 type_path_entry_t *top = append_to_type_path(path);
2406 top->type = top_type;
2408 if (is_type_compound(top_type)) {
2409 compound_t *compound = top_type->compound.compound;
2410 entity_t *entry = compound->members.entities;
2412 if (entry != NULL) {
2413 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2414 top->v.compound_entry = &entry->declaration;
2415 path->top_type = entry->declaration.type;
2417 path->top_type = NULL;
2419 } else if (is_type_array(top_type)) {
2421 path->top_type = top_type->array.element_type;
2423 assert(!is_type_valid(top_type));
2428 * Pop an entry from the given type path, ie. returning from
2429 * (type).a.b to (type).a
2431 static void ascend_from_subtype(type_path_t *path)
2433 type_path_entry_t *top = get_type_path_top(path);
2435 path->top_type = top->type;
2437 size_t len = ARR_LEN(path->path);
2438 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2442 * Pop entries from the given type path until the given
2443 * path level is reached.
2445 static void ascend_to(type_path_t *path, size_t top_path_level)
2447 size_t len = ARR_LEN(path->path);
2449 while (len > top_path_level) {
2450 ascend_from_subtype(path);
2451 len = ARR_LEN(path->path);
2455 static bool walk_designator(type_path_t *path, const designator_t *designator,
2456 bool used_in_offsetof)
2458 for( ; designator != NULL; designator = designator->next) {
2459 type_path_entry_t *top = get_type_path_top(path);
2460 type_t *orig_type = top->type;
2462 type_t *type = skip_typeref(orig_type);
2464 if (designator->symbol != NULL) {
2465 symbol_t *symbol = designator->symbol;
2466 if (!is_type_compound(type)) {
2467 if (is_type_valid(type)) {
2468 errorf(&designator->source_position,
2469 "'.%Y' designator used for non-compound type '%T'",
2473 top->type = type_error_type;
2474 top->v.compound_entry = NULL;
2475 orig_type = type_error_type;
2477 compound_t *compound = type->compound.compound;
2478 entity_t *iter = compound->members.entities;
2479 for( ; iter != NULL; iter = iter->base.next) {
2480 if (iter->base.symbol == symbol) {
2485 errorf(&designator->source_position,
2486 "'%T' has no member named '%Y'", orig_type, symbol);
2489 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2490 if (used_in_offsetof) {
2491 type_t *real_type = skip_typeref(iter->declaration.type);
2492 if (real_type->kind == TYPE_BITFIELD) {
2493 errorf(&designator->source_position,
2494 "offsetof designator '%Y' may not specify bitfield",
2500 top->type = orig_type;
2501 top->v.compound_entry = &iter->declaration;
2502 orig_type = iter->declaration.type;
2505 expression_t *array_index = designator->array_index;
2506 assert(designator->array_index != NULL);
2508 if (!is_type_array(type)) {
2509 if (is_type_valid(type)) {
2510 errorf(&designator->source_position,
2511 "[%E] designator used for non-array type '%T'",
2512 array_index, orig_type);
2517 long index = fold_constant(array_index);
2518 if (!used_in_offsetof) {
2520 errorf(&designator->source_position,
2521 "array index [%E] must be positive", array_index);
2522 } else if (type->array.size_constant) {
2523 long array_size = type->array.size;
2524 if (index >= array_size) {
2525 errorf(&designator->source_position,
2526 "designator [%E] (%d) exceeds array size %d",
2527 array_index, index, array_size);
2532 top->type = orig_type;
2533 top->v.index = (size_t) index;
2534 orig_type = type->array.element_type;
2536 path->top_type = orig_type;
2538 if (designator->next != NULL) {
2539 descend_into_subtype(path);
2548 static void advance_current_object(type_path_t *path, size_t top_path_level)
2550 type_path_entry_t *top = get_type_path_top(path);
2552 type_t *type = skip_typeref(top->type);
2553 if (is_type_union(type)) {
2554 /* in unions only the first element is initialized */
2555 top->v.compound_entry = NULL;
2556 } else if (is_type_struct(type)) {
2557 declaration_t *entry = top->v.compound_entry;
2559 entity_t *next_entity = entry->base.next;
2560 if (next_entity != NULL) {
2561 assert(is_declaration(next_entity));
2562 entry = &next_entity->declaration;
2567 top->v.compound_entry = entry;
2568 if (entry != NULL) {
2569 path->top_type = entry->type;
2572 } else if (is_type_array(type)) {
2573 assert(is_type_array(type));
2577 if (!type->array.size_constant || top->v.index < type->array.size) {
2581 assert(!is_type_valid(type));
2585 /* we're past the last member of the current sub-aggregate, try if we
2586 * can ascend in the type hierarchy and continue with another subobject */
2587 size_t len = ARR_LEN(path->path);
2589 if (len > top_path_level) {
2590 ascend_from_subtype(path);
2591 advance_current_object(path, top_path_level);
2593 path->top_type = NULL;
2598 * skip until token is found.
2600 static void skip_until(int type)
2602 while (token.type != type) {
2603 if (token.type == T_EOF)
2610 * skip any {...} blocks until a closing bracket is reached.
2612 static void skip_initializers(void)
2614 if (token.type == '{')
2617 while (token.type != '}') {
2618 if (token.type == T_EOF)
2620 if (token.type == '{') {
2628 static initializer_t *create_empty_initializer(void)
2630 static initializer_t empty_initializer
2631 = { .list = { { INITIALIZER_LIST }, 0 } };
2632 return &empty_initializer;
2636 * Parse a part of an initialiser for a struct or union,
2638 static initializer_t *parse_sub_initializer(type_path_t *path,
2639 type_t *outer_type, size_t top_path_level,
2640 parse_initializer_env_t *env)
2642 if (token.type == '}') {
2643 /* empty initializer */
2644 return create_empty_initializer();
2647 type_t *orig_type = path->top_type;
2648 type_t *type = NULL;
2650 if (orig_type == NULL) {
2651 /* We are initializing an empty compound. */
2653 type = skip_typeref(orig_type);
2656 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2659 designator_t *designator = NULL;
2660 if (token.type == '.' || token.type == '[') {
2661 designator = parse_designation();
2662 goto finish_designator;
2663 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2664 /* GNU-style designator ("identifier: value") */
2665 designator = allocate_ast_zero(sizeof(designator[0]));
2666 designator->source_position = token.source_position;
2667 designator->symbol = token.v.symbol;
2672 /* reset path to toplevel, evaluate designator from there */
2673 ascend_to(path, top_path_level);
2674 if (!walk_designator(path, designator, false)) {
2675 /* can't continue after designation error */
2679 initializer_t *designator_initializer
2680 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2681 designator_initializer->designator.designator = designator;
2682 ARR_APP1(initializer_t*, initializers, designator_initializer);
2684 orig_type = path->top_type;
2685 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2690 if (token.type == '{') {
2691 if (type != NULL && is_type_scalar(type)) {
2692 sub = parse_scalar_initializer(type, env->must_be_constant);
2696 if (env->entity != NULL) {
2698 "extra brace group at end of initializer for '%Y'",
2699 env->entity->base.symbol);
2701 errorf(HERE, "extra brace group at end of initializer");
2704 descend_into_subtype(path);
2706 add_anchor_token('}');
2707 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2709 rem_anchor_token('}');
2712 ascend_from_subtype(path);
2716 goto error_parse_next;
2720 /* must be an expression */
2721 expression_t *expression = parse_assignment_expression();
2723 if (env->must_be_constant && !is_initializer_constant(expression)) {
2724 errorf(&expression->base.source_position,
2725 "Initialisation expression '%E' is not constant\n",
2730 /* we are already outside, ... */
2731 type_t *const outer_type_skip = skip_typeref(outer_type);
2732 if (is_type_compound(outer_type_skip) &&
2733 !outer_type_skip->compound.compound->complete) {
2734 goto error_parse_next;
2739 /* handle { "string" } special case */
2740 if ((expression->kind == EXPR_STRING_LITERAL
2741 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2742 && outer_type != NULL) {
2743 sub = initializer_from_expression(outer_type, expression);
2745 if (token.type == ',') {
2748 if (token.type != '}' && warning.other) {
2749 warningf(HERE, "excessive elements in initializer for type '%T'",
2752 /* TODO: eat , ... */
2757 /* descend into subtypes until expression matches type */
2759 orig_type = path->top_type;
2760 type = skip_typeref(orig_type);
2762 sub = initializer_from_expression(orig_type, expression);
2766 if (!is_type_valid(type)) {
2769 if (is_type_scalar(type)) {
2770 errorf(&expression->base.source_position,
2771 "expression '%E' doesn't match expected type '%T'",
2772 expression, orig_type);
2776 descend_into_subtype(path);
2780 /* update largest index of top array */
2781 const type_path_entry_t *first = &path->path[0];
2782 type_t *first_type = first->type;
2783 first_type = skip_typeref(first_type);
2784 if (is_type_array(first_type)) {
2785 size_t index = first->v.index;
2786 if (index > path->max_index)
2787 path->max_index = index;
2791 /* append to initializers list */
2792 ARR_APP1(initializer_t*, initializers, sub);
2795 if (warning.other) {
2796 if (env->entity != NULL) {
2797 warningf(HERE, "excess elements in struct initializer for '%Y'",
2798 env->entity->base.symbol);
2800 warningf(HERE, "excess elements in struct initializer");
2806 if (token.type == '}') {
2810 if (token.type == '}') {
2815 /* advance to the next declaration if we are not at the end */
2816 advance_current_object(path, top_path_level);
2817 orig_type = path->top_type;
2818 if (orig_type != NULL)
2819 type = skip_typeref(orig_type);
2825 size_t len = ARR_LEN(initializers);
2826 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2827 initializer_t *result = allocate_ast_zero(size);
2828 result->kind = INITIALIZER_LIST;
2829 result->list.len = len;
2830 memcpy(&result->list.initializers, initializers,
2831 len * sizeof(initializers[0]));
2833 DEL_ARR_F(initializers);
2834 ascend_to(path, top_path_level+1);
2839 skip_initializers();
2840 DEL_ARR_F(initializers);
2841 ascend_to(path, top_path_level+1);
2846 * Parses an initializer. Parsers either a compound literal
2847 * (env->declaration == NULL) or an initializer of a declaration.
2849 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2851 type_t *type = skip_typeref(env->type);
2852 initializer_t *result = NULL;
2855 if (is_type_scalar(type)) {
2856 result = parse_scalar_initializer(type, env->must_be_constant);
2857 } else if (token.type == '{') {
2861 memset(&path, 0, sizeof(path));
2862 path.top_type = env->type;
2863 path.path = NEW_ARR_F(type_path_entry_t, 0);
2865 descend_into_subtype(&path);
2867 add_anchor_token('}');
2868 result = parse_sub_initializer(&path, env->type, 1, env);
2869 rem_anchor_token('}');
2871 max_index = path.max_index;
2872 DEL_ARR_F(path.path);
2876 /* parse_scalar_initializer() also works in this case: we simply
2877 * have an expression without {} around it */
2878 result = parse_scalar_initializer(type, env->must_be_constant);
2881 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2882 * the array type size */
2883 if (is_type_array(type) && type->array.size_expression == NULL
2884 && result != NULL) {
2886 switch (result->kind) {
2887 case INITIALIZER_LIST:
2888 size = max_index + 1;
2891 case INITIALIZER_STRING:
2892 size = result->string.string.size;
2895 case INITIALIZER_WIDE_STRING:
2896 size = result->wide_string.string.size;
2899 case INITIALIZER_DESIGNATOR:
2900 case INITIALIZER_VALUE:
2901 /* can happen for parse errors */
2906 internal_errorf(HERE, "invalid initializer type");
2909 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2910 cnst->base.type = type_size_t;
2911 cnst->conste.v.int_value = size;
2913 type_t *new_type = duplicate_type(type);
2915 new_type->array.size_expression = cnst;
2916 new_type->array.size_constant = true;
2917 new_type->array.has_implicit_size = true;
2918 new_type->array.size = size;
2919 env->type = new_type;
2927 static void append_entity(scope_t *scope, entity_t *entity)
2929 if (scope->last_entity != NULL) {
2930 scope->last_entity->base.next = entity;
2932 scope->entities = entity;
2934 scope->last_entity = entity;
2938 static compound_t *parse_compound_type_specifier(bool is_struct)
2940 gnu_attribute_t *attributes = NULL;
2941 decl_modifiers_t modifiers = 0;
2948 symbol_t *symbol = NULL;
2949 compound_t *compound = NULL;
2951 if (token.type == T___attribute__) {
2952 modifiers |= parse_attributes(&attributes);
2955 if (token.type == T_IDENTIFIER) {
2956 symbol = token.v.symbol;
2959 namespace_tag_t const namespc =
2960 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2961 entity_t *entity = get_entity(symbol, namespc);
2962 if (entity != NULL) {
2963 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2964 compound = &entity->compound;
2965 if (compound->base.parent_scope != current_scope &&
2966 (token.type == '{' || token.type == ';')) {
2967 /* we're in an inner scope and have a definition. Override
2968 existing definition in outer scope */
2970 } else if (compound->complete && token.type == '{') {
2971 assert(symbol != NULL);
2972 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2973 is_struct ? "struct" : "union", symbol,
2974 &compound->base.source_position);
2975 /* clear members in the hope to avoid further errors */
2976 compound->members.entities = NULL;
2979 } else if (token.type != '{') {
2981 parse_error_expected("while parsing struct type specifier",
2982 T_IDENTIFIER, '{', NULL);
2984 parse_error_expected("while parsing union type specifier",
2985 T_IDENTIFIER, '{', NULL);
2991 if (compound == NULL) {
2992 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2993 entity_t *entity = allocate_entity_zero(kind);
2994 compound = &entity->compound;
2996 compound->base.namespc =
2997 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2998 compound->base.source_position = token.source_position;
2999 compound->base.symbol = symbol;
3000 compound->base.parent_scope = current_scope;
3001 if (symbol != NULL) {
3002 environment_push(entity);
3004 append_entity(current_scope, entity);
3007 if (token.type == '{') {
3008 compound->complete = true;
3010 parse_compound_type_entries(compound);
3011 modifiers |= parse_attributes(&attributes);
3014 compound->modifiers |= modifiers;
3018 static void parse_enum_entries(type_t *const enum_type)
3022 if (token.type == '}') {
3024 errorf(HERE, "empty enum not allowed");
3028 add_anchor_token('}');
3030 if (token.type != T_IDENTIFIER) {
3031 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3033 rem_anchor_token('}');
3037 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3038 entity->enum_value.enum_type = enum_type;
3039 entity->base.symbol = token.v.symbol;
3040 entity->base.source_position = token.source_position;
3043 if (token.type == '=') {
3045 expression_t *value = parse_constant_expression();
3047 value = create_implicit_cast(value, enum_type);
3048 entity->enum_value.value = value;
3053 record_entity(entity, false);
3055 if (token.type != ',')
3058 } while (token.type != '}');
3059 rem_anchor_token('}');
3067 static type_t *parse_enum_specifier(void)
3069 gnu_attribute_t *attributes = NULL;
3074 if (token.type == T_IDENTIFIER) {
3075 symbol = token.v.symbol;
3078 entity = get_entity(symbol, NAMESPACE_ENUM);
3079 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3080 } else if (token.type != '{') {
3081 parse_error_expected("while parsing enum type specifier",
3082 T_IDENTIFIER, '{', NULL);
3089 if (entity == NULL) {
3090 entity = allocate_entity_zero(ENTITY_ENUM);
3091 entity->base.namespc = NAMESPACE_ENUM;
3092 entity->base.source_position = token.source_position;
3093 entity->base.symbol = symbol;
3094 entity->base.parent_scope = current_scope;
3097 type_t *const type = allocate_type_zero(TYPE_ENUM);
3098 type->enumt.enume = &entity->enume;
3100 if (token.type == '{') {
3101 if (entity->enume.complete) {
3102 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3103 symbol, &entity->base.source_position);
3105 if (symbol != NULL) {
3106 environment_push(entity);
3108 append_entity(current_scope, entity);
3109 entity->enume.complete = true;
3111 parse_enum_entries(type);
3112 parse_attributes(&attributes);
3113 } else if(!entity->enume.complete && !(c_mode & _GNUC)) {
3114 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3122 * if a symbol is a typedef to another type, return true
3124 static bool is_typedef_symbol(symbol_t *symbol)
3126 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3127 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3130 static type_t *parse_typeof(void)
3137 add_anchor_token(')');
3139 expression_t *expression = NULL;
3141 bool old_type_prop = in_type_prop;
3142 bool old_gcc_extension = in_gcc_extension;
3143 in_type_prop = true;
3145 while (token.type == T___extension__) {
3146 /* This can be a prefix to a typename or an expression. */
3148 in_gcc_extension = true;
3150 switch (token.type) {
3152 if (is_typedef_symbol(token.v.symbol)) {
3153 type = parse_typename();
3155 expression = parse_expression();
3156 type = expression->base.type;
3161 type = parse_typename();
3165 expression = parse_expression();
3166 type = expression->base.type;
3169 in_type_prop = old_type_prop;
3170 in_gcc_extension = old_gcc_extension;
3172 rem_anchor_token(')');
3175 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3176 typeof_type->typeoft.expression = expression;
3177 typeof_type->typeoft.typeof_type = type;
3184 typedef enum specifiers_t {
3185 SPECIFIER_SIGNED = 1 << 0,
3186 SPECIFIER_UNSIGNED = 1 << 1,
3187 SPECIFIER_LONG = 1 << 2,
3188 SPECIFIER_INT = 1 << 3,
3189 SPECIFIER_DOUBLE = 1 << 4,
3190 SPECIFIER_CHAR = 1 << 5,
3191 SPECIFIER_SHORT = 1 << 6,
3192 SPECIFIER_LONG_LONG = 1 << 7,
3193 SPECIFIER_FLOAT = 1 << 8,
3194 SPECIFIER_BOOL = 1 << 9,
3195 SPECIFIER_VOID = 1 << 10,
3196 SPECIFIER_INT8 = 1 << 11,
3197 SPECIFIER_INT16 = 1 << 12,
3198 SPECIFIER_INT32 = 1 << 13,
3199 SPECIFIER_INT64 = 1 << 14,
3200 SPECIFIER_INT128 = 1 << 15,
3201 SPECIFIER_COMPLEX = 1 << 16,
3202 SPECIFIER_IMAGINARY = 1 << 17,
3205 static type_t *create_builtin_type(symbol_t *const symbol,
3206 type_t *const real_type)
3208 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3209 type->builtin.symbol = symbol;
3210 type->builtin.real_type = real_type;
3212 type_t *result = typehash_insert(type);
3213 if (type != result) {
3220 static type_t *get_typedef_type(symbol_t *symbol)
3222 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3223 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3226 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3227 type->typedeft.typedefe = &entity->typedefe;
3233 * check for the allowed MS alignment values.
3235 static bool check_alignment_value(long long intvalue)
3237 if (intvalue < 1 || intvalue > 8192) {
3238 errorf(HERE, "illegal alignment value");
3241 unsigned v = (unsigned)intvalue;
3242 for (unsigned i = 1; i <= 8192; i += i) {
3246 errorf(HERE, "alignment must be power of two");
3250 #define DET_MOD(name, tag) do { \
3251 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3252 *modifiers |= tag; \
3255 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3257 decl_modifiers_t *modifiers = &specifiers->modifiers;
3260 if (token.type == T_restrict) {
3262 DET_MOD(restrict, DM_RESTRICT);
3264 } else if (token.type != T_IDENTIFIER)
3266 symbol_t *symbol = token.v.symbol;
3267 if (symbol == sym_align) {
3270 if (token.type != T_INTEGER)
3272 if (check_alignment_value(token.v.intvalue)) {
3273 if (specifiers->alignment != 0 && warning.other)
3274 warningf(HERE, "align used more than once");
3275 specifiers->alignment = (unsigned char)token.v.intvalue;
3279 } else if (symbol == sym_allocate) {
3282 if (token.type != T_IDENTIFIER)
3284 (void)token.v.symbol;
3286 } else if (symbol == sym_dllimport) {
3288 DET_MOD(dllimport, DM_DLLIMPORT);
3289 } else if (symbol == sym_dllexport) {
3291 DET_MOD(dllexport, DM_DLLEXPORT);
3292 } else if (symbol == sym_thread) {
3294 DET_MOD(thread, DM_THREAD);
3295 } else if (symbol == sym_naked) {
3297 DET_MOD(naked, DM_NAKED);
3298 } else if (symbol == sym_noinline) {
3300 DET_MOD(noinline, DM_NOINLINE);
3301 } else if (symbol == sym_noreturn) {
3303 DET_MOD(noreturn, DM_NORETURN);
3304 } else if (symbol == sym_nothrow) {
3306 DET_MOD(nothrow, DM_NOTHROW);
3307 } else if (symbol == sym_novtable) {
3309 DET_MOD(novtable, DM_NOVTABLE);
3310 } else if (symbol == sym_property) {
3314 bool is_get = false;
3315 if (token.type != T_IDENTIFIER)
3317 if (token.v.symbol == sym_get) {
3319 } else if (token.v.symbol == sym_put) {
3321 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3326 if (token.type != T_IDENTIFIER)
3329 if (specifiers->get_property_sym != NULL) {
3330 errorf(HERE, "get property name already specified");
3332 specifiers->get_property_sym = token.v.symbol;
3335 if (specifiers->put_property_sym != NULL) {
3336 errorf(HERE, "put property name already specified");
3338 specifiers->put_property_sym = token.v.symbol;
3342 if (token.type == ',') {
3349 } else if (symbol == sym_selectany) {
3351 DET_MOD(selectany, DM_SELECTANY);
3352 } else if (symbol == sym_uuid) {
3355 if (token.type != T_STRING_LITERAL)
3359 } else if (symbol == sym_deprecated) {
3361 if (specifiers->deprecated != 0 && warning.other)
3362 warningf(HERE, "deprecated used more than once");
3363 specifiers->deprecated = true;
3364 if (token.type == '(') {
3366 if (token.type == T_STRING_LITERAL) {
3367 specifiers->deprecated_string = token.v.string.begin;
3370 errorf(HERE, "string literal expected");
3374 } else if (symbol == sym_noalias) {
3376 DET_MOD(noalias, DM_NOALIAS);
3379 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3381 if (token.type == '(')
3385 if (token.type == ',')
3392 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3394 entity_t *entity = allocate_entity_zero(kind);
3395 entity->base.source_position = *HERE;
3396 entity->base.symbol = symbol;
3397 if (is_declaration(entity)) {
3398 entity->declaration.type = type_error_type;
3399 entity->declaration.implicit = true;
3400 } else if (kind == ENTITY_TYPEDEF) {
3401 entity->typedefe.type = type_error_type;
3403 record_entity(entity, false);
3408 * Finish the construction of a struct type by calculating
3409 * its size, offsets, alignment.
3411 static void finish_struct_type(compound_type_t *type)
3413 assert(type->compound != NULL);
3415 compound_t *compound = type->compound;
3416 if (!compound->complete)
3421 il_alignment_t alignment = 1;
3422 bool need_pad = false;
3424 entity_t *entry = compound->members.entities;
3425 for (; entry != NULL; entry = entry->base.next) {
3426 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3429 type_t *m_type = skip_typeref(entry->declaration.type);
3430 if (! is_type_valid(m_type)) {
3431 /* simply ignore errors here */
3434 il_alignment_t m_alignment = m_type->base.alignment;
3435 if (m_alignment > alignment)
3436 alignment = m_alignment;
3438 offset = (size + m_alignment - 1) & -m_alignment;
3442 entry->compound_member.offset = offset;
3443 size = offset + m_type->base.size;
3445 if (type->base.alignment != 0) {
3446 alignment = type->base.alignment;
3449 offset = (size + alignment - 1) & -alignment;
3453 if (warning.padded && need_pad) {
3454 warningf(&compound->base.source_position,
3455 "'%#T' needs padding", type, compound->base.symbol);
3457 if (warning.packed && !need_pad) {
3458 warningf(&compound->base.source_position,
3459 "superfluous packed attribute on '%#T'",
3460 type, compound->base.symbol);
3463 type->base.size = offset;
3464 type->base.alignment = alignment;
3468 * Finish the construction of an union type by calculating
3469 * its size and alignment.
3471 static void finish_union_type(compound_type_t *type)
3473 assert(type->compound != NULL);
3475 compound_t *compound = type->compound;
3476 if (! compound->complete)
3480 il_alignment_t alignment = 1;
3482 entity_t *entry = compound->members.entities;
3483 for (; entry != NULL; entry = entry->base.next) {
3484 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3487 type_t *m_type = skip_typeref(entry->declaration.type);
3488 if (! is_type_valid(m_type))
3491 entry->compound_member.offset = 0;
3492 if (m_type->base.size > size)
3493 size = m_type->base.size;
3494 if (m_type->base.alignment > alignment)
3495 alignment = m_type->base.alignment;
3497 if (type->base.alignment != 0) {
3498 alignment = type->base.alignment;
3500 size = (size + alignment - 1) & -alignment;
3501 type->base.size = size;
3502 type->base.alignment = alignment;
3505 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3507 type_t *type = NULL;
3508 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3509 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3510 unsigned type_specifiers = 0;
3511 bool newtype = false;
3512 bool saw_error = false;
3513 bool old_gcc_extension = in_gcc_extension;
3515 specifiers->source_position = token.source_position;
3518 specifiers->modifiers
3519 |= parse_attributes(&specifiers->gnu_attributes);
3520 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3521 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3523 switch (token.type) {
3526 #define MATCH_STORAGE_CLASS(token, class) \
3528 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3529 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3531 specifiers->storage_class = class; \
3535 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3536 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3537 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3538 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3539 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3544 add_anchor_token(')');
3545 parse_microsoft_extended_decl_modifier(specifiers);
3546 rem_anchor_token(')');
3551 switch (specifiers->storage_class) {
3552 case STORAGE_CLASS_NONE:
3553 specifiers->storage_class = STORAGE_CLASS_THREAD;
3556 case STORAGE_CLASS_EXTERN:
3557 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3560 case STORAGE_CLASS_STATIC:
3561 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3565 errorf(HERE, "multiple storage classes in declaration specifiers");
3571 /* type qualifiers */
3572 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3574 qualifiers |= qualifier; \
3578 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3579 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3580 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3581 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3582 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3583 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3584 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3585 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3587 case T___extension__:
3589 in_gcc_extension = true;
3592 /* type specifiers */
3593 #define MATCH_SPECIFIER(token, specifier, name) \
3595 if (type_specifiers & specifier) { \
3596 errorf(HERE, "multiple " name " type specifiers given"); \
3598 type_specifiers |= specifier; \
3603 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3604 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3605 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3606 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3607 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3608 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3609 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3610 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3611 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3612 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3613 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3614 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3615 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3616 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3617 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3618 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3619 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3621 case T__forceinline:
3622 /* only in microsoft mode */
3623 specifiers->modifiers |= DM_FORCEINLINE;
3628 specifiers->is_inline = true;
3632 if (type_specifiers & SPECIFIER_LONG_LONG) {
3633 errorf(HERE, "multiple type specifiers given");
3634 } else if (type_specifiers & SPECIFIER_LONG) {
3635 type_specifiers |= SPECIFIER_LONG_LONG;
3637 type_specifiers |= SPECIFIER_LONG;
3643 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3645 type->compound.compound = parse_compound_type_specifier(true);
3646 finish_struct_type(&type->compound);
3650 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3651 type->compound.compound = parse_compound_type_specifier(false);
3652 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3653 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3654 finish_union_type(&type->compound);
3658 type = parse_enum_specifier();
3661 type = parse_typeof();
3663 case T___builtin_va_list:
3664 type = duplicate_type(type_valist);
3668 case T_IDENTIFIER: {
3669 /* only parse identifier if we haven't found a type yet */
3670 if (type != NULL || type_specifiers != 0) {
3671 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3672 * declaration, so it doesn't generate errors about expecting '(' or
3674 switch (look_ahead(1)->type) {
3681 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3684 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3689 goto finish_specifiers;
3693 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3694 if (typedef_type == NULL) {
3695 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3696 * declaration, so it doesn't generate 'implicit int' followed by more
3697 * errors later on. */
3698 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3703 errorf(HERE, "%K does not name a type", &token);
3706 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3708 type = allocate_type_zero(TYPE_TYPEDEF);
3709 type->typedeft.typedefe = &entity->typedefe;
3713 if (la1_type == '*')
3714 goto finish_specifiers;
3719 goto finish_specifiers;
3724 type = typedef_type;
3728 /* function specifier */
3730 goto finish_specifiers;
3735 in_gcc_extension = old_gcc_extension;
3737 if (type == NULL || (saw_error && type_specifiers != 0)) {
3738 atomic_type_kind_t atomic_type;
3740 /* match valid basic types */
3741 switch (type_specifiers) {
3742 case SPECIFIER_VOID:
3743 atomic_type = ATOMIC_TYPE_VOID;
3745 case SPECIFIER_CHAR:
3746 atomic_type = ATOMIC_TYPE_CHAR;
3748 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3749 atomic_type = ATOMIC_TYPE_SCHAR;
3751 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3752 atomic_type = ATOMIC_TYPE_UCHAR;
3754 case SPECIFIER_SHORT:
3755 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3756 case SPECIFIER_SHORT | SPECIFIER_INT:
3757 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3758 atomic_type = ATOMIC_TYPE_SHORT;
3760 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3761 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3762 atomic_type = ATOMIC_TYPE_USHORT;
3765 case SPECIFIER_SIGNED:
3766 case SPECIFIER_SIGNED | SPECIFIER_INT:
3767 atomic_type = ATOMIC_TYPE_INT;
3769 case SPECIFIER_UNSIGNED:
3770 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3771 atomic_type = ATOMIC_TYPE_UINT;
3773 case SPECIFIER_LONG:
3774 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3775 case SPECIFIER_LONG | SPECIFIER_INT:
3776 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3777 atomic_type = ATOMIC_TYPE_LONG;
3779 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3780 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3781 atomic_type = ATOMIC_TYPE_ULONG;
3784 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3785 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3786 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3787 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3789 atomic_type = ATOMIC_TYPE_LONGLONG;
3790 goto warn_about_long_long;
3792 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3793 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3795 atomic_type = ATOMIC_TYPE_ULONGLONG;
3796 warn_about_long_long:
3797 if (warning.long_long) {
3798 warningf(&specifiers->source_position,
3799 "ISO C90 does not support 'long long'");
3803 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3804 atomic_type = unsigned_int8_type_kind;
3807 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3808 atomic_type = unsigned_int16_type_kind;
3811 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3812 atomic_type = unsigned_int32_type_kind;
3815 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3816 atomic_type = unsigned_int64_type_kind;
3819 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3820 atomic_type = unsigned_int128_type_kind;
3823 case SPECIFIER_INT8:
3824 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3825 atomic_type = int8_type_kind;
3828 case SPECIFIER_INT16:
3829 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3830 atomic_type = int16_type_kind;
3833 case SPECIFIER_INT32:
3834 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3835 atomic_type = int32_type_kind;
3838 case SPECIFIER_INT64:
3839 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3840 atomic_type = int64_type_kind;
3843 case SPECIFIER_INT128:
3844 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3845 atomic_type = int128_type_kind;
3848 case SPECIFIER_FLOAT:
3849 atomic_type = ATOMIC_TYPE_FLOAT;
3851 case SPECIFIER_DOUBLE:
3852 atomic_type = ATOMIC_TYPE_DOUBLE;
3854 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3855 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3857 case SPECIFIER_BOOL:
3858 atomic_type = ATOMIC_TYPE_BOOL;
3860 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3861 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3862 atomic_type = ATOMIC_TYPE_FLOAT;
3864 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3865 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3866 atomic_type = ATOMIC_TYPE_DOUBLE;
3868 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3869 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3870 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3873 /* invalid specifier combination, give an error message */
3874 if (type_specifiers == 0) {
3878 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3879 if (!(c_mode & _CXX) && !strict_mode) {
3880 if (warning.implicit_int) {
3881 warningf(HERE, "no type specifiers in declaration, using 'int'");
3883 atomic_type = ATOMIC_TYPE_INT;
3886 errorf(HERE, "no type specifiers given in declaration");
3888 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3889 (type_specifiers & SPECIFIER_UNSIGNED)) {
3890 errorf(HERE, "signed and unsigned specifiers given");
3891 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3892 errorf(HERE, "only integer types can be signed or unsigned");
3894 errorf(HERE, "multiple datatypes in declaration");
3899 if (type_specifiers & SPECIFIER_COMPLEX) {
3900 type = allocate_type_zero(TYPE_COMPLEX);
3901 type->complex.akind = atomic_type;
3902 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3903 type = allocate_type_zero(TYPE_IMAGINARY);
3904 type->imaginary.akind = atomic_type;
3906 type = allocate_type_zero(TYPE_ATOMIC);
3907 type->atomic.akind = atomic_type;
3910 } else if (type_specifiers != 0) {
3911 errorf(HERE, "multiple datatypes in declaration");
3914 /* FIXME: check type qualifiers here */
3916 type->base.qualifiers = qualifiers;
3917 type->base.modifiers = modifiers;
3919 type_t *result = typehash_insert(type);
3920 if (newtype && result != type) {
3924 specifiers->type = result;
3928 specifiers->type = type_error_type;
3932 static type_qualifiers_t parse_type_qualifiers(void)
3934 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3937 switch (token.type) {
3938 /* type qualifiers */
3939 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3940 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3941 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3942 /* microsoft extended type modifiers */
3943 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3944 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3945 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3946 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3947 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3956 * Parses an K&R identifier list
3958 static void parse_identifier_list(scope_t *scope)
3961 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
3962 entity->base.source_position = token.source_position;
3963 entity->base.namespc = NAMESPACE_NORMAL;
3964 entity->base.symbol = token.v.symbol;
3965 /* a K&R parameter has no type, yet */
3968 append_entity(scope, entity);
3970 if (token.type != ',') {
3974 } while (token.type == T_IDENTIFIER);
3977 static type_t *automatic_type_conversion(type_t *orig_type);
3979 static void semantic_parameter(declaration_t *declaration)
3981 /* TODO: improve error messages */
3982 source_position_t const* const pos = &declaration->base.source_position;
3985 switch (declaration->declared_storage_class) {
3986 /* Allowed storage classes */
3987 case STORAGE_CLASS_NONE:
3988 case STORAGE_CLASS_REGISTER:
3992 errorf(pos, "parameter may only have none or register storage class");
3996 type_t *const orig_type = declaration->type;
3997 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3998 * sugar. Turn it into a pointer.
3999 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4000 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4002 type_t *const type = automatic_type_conversion(orig_type);
4003 declaration->type = type;
4005 if (is_type_incomplete(skip_typeref(type))) {
4006 errorf(pos, "parameter '%#T' is of incomplete type",
4007 orig_type, declaration->base.symbol);
4011 static entity_t *parse_parameter(void)
4013 declaration_specifiers_t specifiers;
4014 memset(&specifiers, 0, sizeof(specifiers));
4016 parse_declaration_specifiers(&specifiers);
4018 entity_t *entity = parse_declarator(&specifiers, true, false);
4023 * Parses function type parameters (and optionally creates variable_t entities
4024 * for them in a scope)
4026 static void parse_parameters(function_type_t *type, scope_t *scope)
4029 add_anchor_token(')');
4030 int saved_comma_state = save_and_reset_anchor_state(',');
4032 if (token.type == T_IDENTIFIER &&
4033 !is_typedef_symbol(token.v.symbol)) {
4034 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4035 if (la1_type == ',' || la1_type == ')') {
4036 type->kr_style_parameters = true;
4037 parse_identifier_list(scope);
4038 goto parameters_finished;
4042 if (token.type == ')') {
4043 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4044 if (!(c_mode & _CXX))
4045 type->unspecified_parameters = true;
4046 goto parameters_finished;
4049 function_parameter_t *parameter;
4050 function_parameter_t *last_parameter = NULL;
4053 switch (token.type) {
4056 type->variadic = true;
4057 goto parameters_finished;
4060 case T___extension__:
4063 entity_t *entity = parse_parameter();
4064 if (entity->kind == ENTITY_TYPEDEF) {
4065 errorf(&entity->base.source_position,
4066 "typedef not allowed as function parameter");
4069 assert(is_declaration(entity));
4071 /* func(void) is not a parameter */
4072 if (last_parameter == NULL
4073 && token.type == ')'
4074 && entity->base.symbol == NULL
4075 && skip_typeref(entity->declaration.type) == type_void) {
4076 goto parameters_finished;
4078 semantic_parameter(&entity->declaration);
4080 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4081 memset(parameter, 0, sizeof(parameter[0]));
4082 parameter->type = entity->declaration.type;
4084 if (scope != NULL) {
4085 append_entity(scope, entity);
4088 if (last_parameter != NULL) {
4089 last_parameter->next = parameter;
4091 type->parameters = parameter;
4093 last_parameter = parameter;
4098 goto parameters_finished;
4100 if (token.type != ',') {
4101 goto parameters_finished;
4107 parameters_finished:
4108 rem_anchor_token(')');
4112 restore_anchor_state(',', saved_comma_state);
4115 typedef enum construct_type_kind_t {
4120 } construct_type_kind_t;
4122 typedef struct construct_type_t construct_type_t;
4123 struct construct_type_t {
4124 construct_type_kind_t kind;
4125 construct_type_t *next;
4128 typedef struct parsed_pointer_t parsed_pointer_t;
4129 struct parsed_pointer_t {
4130 construct_type_t construct_type;
4131 type_qualifiers_t type_qualifiers;
4134 typedef struct construct_function_type_t construct_function_type_t;
4135 struct construct_function_type_t {
4136 construct_type_t construct_type;
4137 type_t *function_type;
4140 typedef struct parsed_array_t parsed_array_t;
4141 struct parsed_array_t {
4142 construct_type_t construct_type;
4143 type_qualifiers_t type_qualifiers;
4149 typedef struct construct_base_type_t construct_base_type_t;
4150 struct construct_base_type_t {
4151 construct_type_t construct_type;
4155 static construct_type_t *parse_pointer_declarator(void)
4159 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4160 memset(pointer, 0, sizeof(pointer[0]));
4161 pointer->construct_type.kind = CONSTRUCT_POINTER;
4162 pointer->type_qualifiers = parse_type_qualifiers();
4164 return (construct_type_t*) pointer;
4167 static construct_type_t *parse_array_declarator(void)
4170 add_anchor_token(']');
4172 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4173 memset(array, 0, sizeof(array[0]));
4174 array->construct_type.kind = CONSTRUCT_ARRAY;
4176 if (token.type == T_static) {
4177 array->is_static = true;
4181 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4182 if (type_qualifiers != 0) {
4183 if (token.type == T_static) {
4184 array->is_static = true;
4188 array->type_qualifiers = type_qualifiers;
4190 if (token.type == '*' && look_ahead(1)->type == ']') {
4191 array->is_variable = true;
4193 } else if (token.type != ']') {
4194 array->size = parse_assignment_expression();
4197 rem_anchor_token(']');
4201 return (construct_type_t*) array;
4204 static construct_type_t *parse_function_declarator(scope_t *scope)
4206 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4208 type->function.linkage = current_linkage;
4210 /* TODO: revive this... once we know exactly how to do it */
4212 decl_modifiers_t modifiers = entity->declaration.modifiers;
4214 unsigned mask = modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
4216 if (mask & (mask-1)) {
4217 const char *first = NULL, *second = NULL;
4219 /* more than one calling convention set */
4220 if (modifiers & DM_CDECL) {
4221 if (first == NULL) first = "cdecl";
4222 else if (second == NULL) second = "cdecl";
4224 if (modifiers & DM_STDCALL) {
4225 if (first == NULL) first = "stdcall";
4226 else if (second == NULL) second = "stdcall";
4228 if (modifiers & DM_FASTCALL) {
4229 if (first == NULL) first = "fastcall";
4230 else if (second == NULL) second = "fastcall";
4232 if (modifiers & DM_THISCALL) {
4233 if (first == NULL) first = "thiscall";
4234 else if (second == NULL) second = "thiscall";
4236 errorf(&entity->base.source_position,
4237 "%s and %s attributes are not compatible", first, second);
4240 if (modifiers & DM_CDECL)
4241 type->function.calling_convention = CC_CDECL;
4242 else if (modifiers & DM_STDCALL)
4243 type->function.calling_convention = CC_STDCALL;
4244 else if (modifiers & DM_FASTCALL)
4245 type->function.calling_convention = CC_FASTCALL;
4246 else if (modifiers & DM_THISCALL)
4247 type->function.calling_convention = CC_THISCALL;
4250 parse_parameters(&type->function, scope);
4252 construct_function_type_t *construct_function_type =
4253 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4254 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4255 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4256 construct_function_type->function_type = type;
4258 return &construct_function_type->construct_type;
4261 typedef struct parse_declarator_env_t {
4262 decl_modifiers_t modifiers;
4264 source_position_t source_position;
4266 } parse_declarator_env_t;
4268 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4269 bool may_be_abstract)
4271 /* construct a single linked list of construct_type_t's which describe
4272 * how to construct the final declarator type */
4273 construct_type_t *first = NULL;
4274 construct_type_t *last = NULL;
4275 gnu_attribute_t *attributes = NULL;
4277 decl_modifiers_t modifiers = parse_attributes(&attributes);
4280 while (token.type == '*') {
4281 construct_type_t *type = parse_pointer_declarator();
4291 /* TODO: find out if this is correct */
4292 modifiers |= parse_attributes(&attributes);
4296 env->modifiers |= modifiers;
4298 construct_type_t *inner_types = NULL;
4300 switch (token.type) {
4303 errorf(HERE, "no identifier expected in typename");
4305 env->symbol = token.v.symbol;
4306 env->source_position = token.source_position;
4312 add_anchor_token(')');
4313 inner_types = parse_inner_declarator(env, may_be_abstract);
4314 if (inner_types != NULL) {
4315 /* All later declarators only modify the return type */
4318 rem_anchor_token(')');
4322 if (may_be_abstract)
4324 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4329 construct_type_t *p = last;
4332 construct_type_t *type;
4333 switch (token.type) {
4335 scope_t *scope = NULL;
4337 scope = &env->parameters;
4339 type = parse_function_declarator(scope);
4343 type = parse_array_declarator();
4346 goto declarator_finished;
4349 /* insert in the middle of the list (behind p) */
4351 type->next = p->next;
4362 declarator_finished:
4363 /* append inner_types at the end of the list, we don't to set last anymore
4364 * as it's not needed anymore */
4366 assert(first == NULL);
4367 first = inner_types;
4369 last->next = inner_types;
4377 static void parse_declaration_attributes(entity_t *entity)
4379 gnu_attribute_t *attributes = NULL;
4380 decl_modifiers_t modifiers = parse_attributes(&attributes);
4386 if (entity->kind == ENTITY_TYPEDEF) {
4387 modifiers |= entity->typedefe.modifiers;
4388 type = entity->typedefe.type;
4390 assert(is_declaration(entity));
4391 modifiers |= entity->declaration.modifiers;
4392 type = entity->declaration.type;
4397 /* handle these strange/stupid mode attributes */
4398 gnu_attribute_t *attribute = attributes;
4399 for ( ; attribute != NULL; attribute = attribute->next) {
4400 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4403 atomic_type_kind_t akind = attribute->u.akind;
4404 if (!is_type_signed(type)) {
4406 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4407 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4408 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4409 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4411 panic("invalid akind in mode attribute");
4415 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4416 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4417 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4418 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4420 panic("invalid akind in mode attribute");
4424 type = make_atomic_type(akind, type->base.qualifiers);
4427 type_modifiers_t type_modifiers = type->base.modifiers;
4428 if (modifiers & DM_TRANSPARENT_UNION)
4429 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4431 if (type->base.modifiers != type_modifiers) {
4432 type_t *copy = duplicate_type(type);
4433 copy->base.modifiers = type_modifiers;
4435 type = typehash_insert(copy);
4437 obstack_free(type_obst, copy);
4441 if (entity->kind == ENTITY_TYPEDEF) {
4442 entity->typedefe.type = type;
4443 entity->typedefe.modifiers = modifiers;
4445 entity->declaration.type = type;
4446 entity->declaration.modifiers = modifiers;
4450 static type_t *construct_declarator_type(construct_type_t *construct_list,
4453 construct_type_t *iter = construct_list;
4454 for( ; iter != NULL; iter = iter->next) {
4455 switch (iter->kind) {
4456 case CONSTRUCT_INVALID:
4457 internal_errorf(HERE, "invalid type construction found");
4458 case CONSTRUCT_FUNCTION: {
4459 construct_function_type_t *construct_function_type
4460 = (construct_function_type_t*) iter;
4462 type_t *function_type = construct_function_type->function_type;
4464 function_type->function.return_type = type;
4466 type_t *skipped_return_type = skip_typeref(type);
4468 if (is_type_function(skipped_return_type)) {
4469 errorf(HERE, "function returning function is not allowed");
4470 } else if (is_type_array(skipped_return_type)) {
4471 errorf(HERE, "function returning array is not allowed");
4473 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4475 "type qualifiers in return type of function type are meaningless");
4479 type = function_type;
4483 case CONSTRUCT_POINTER: {
4484 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4485 type = make_pointer_type(type, parsed_pointer->type_qualifiers);
4489 case CONSTRUCT_ARRAY: {
4490 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4491 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4493 expression_t *size_expression = parsed_array->size;
4494 if (size_expression != NULL) {
4496 = create_implicit_cast(size_expression, type_size_t);
4499 array_type->base.qualifiers = parsed_array->type_qualifiers;
4500 array_type->array.element_type = type;
4501 array_type->array.is_static = parsed_array->is_static;
4502 array_type->array.is_variable = parsed_array->is_variable;
4503 array_type->array.size_expression = size_expression;
4505 if (size_expression != NULL) {
4506 if (is_constant_expression(size_expression)) {
4507 array_type->array.size_constant = true;
4508 array_type->array.size
4509 = fold_constant(size_expression);
4511 array_type->array.is_vla = true;
4515 type_t *skipped_type = skip_typeref(type);
4517 if (is_type_incomplete(skipped_type)) {
4518 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4519 } else if (is_type_function(skipped_type)) {
4520 errorf(HERE, "array of functions is not allowed");
4527 type_t *hashed_type = typehash_insert(type);
4528 if (hashed_type != type) {
4529 /* the function type was constructed earlier freeing it here will
4530 * destroy other types... */
4531 if (iter->kind != CONSTRUCT_FUNCTION) {
4541 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4542 bool may_be_abstract,
4543 bool create_compound_member)
4545 parse_declarator_env_t env;
4546 memset(&env, 0, sizeof(env));
4548 construct_type_t *construct_type
4549 = parse_inner_declarator(&env, may_be_abstract);
4550 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4552 if (construct_type != NULL) {
4553 obstack_free(&temp_obst, construct_type);
4557 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4558 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4559 entity->base.symbol = env.symbol;
4560 entity->base.source_position = env.source_position;
4561 entity->typedefe.type = type;
4563 if (create_compound_member) {
4564 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4565 } else if (is_type_function(skip_typeref(type))) {
4566 entity = allocate_entity_zero(ENTITY_FUNCTION);
4568 entity->function.is_inline = specifiers->is_inline;
4569 entity->function.parameters = env.parameters;
4571 entity = allocate_entity_zero(ENTITY_VARIABLE);
4573 entity->variable.get_property_sym = specifiers->get_property_sym;
4574 entity->variable.put_property_sym = specifiers->put_property_sym;
4575 if (specifiers->alignment != 0) {
4576 /* TODO: add checks here */
4577 entity->variable.alignment = specifiers->alignment;
4580 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4581 warningf(&env.source_position,
4582 "variable '%Y' declared 'inline'\n", env.symbol);
4586 entity->base.source_position = env.source_position;
4587 entity->base.symbol = env.symbol;
4588 entity->base.namespc = NAMESPACE_NORMAL;
4589 entity->declaration.type = type;
4590 entity->declaration.modifiers = env.modifiers | specifiers->modifiers;
4591 entity->declaration.deprecated_string = specifiers->deprecated_string;
4593 storage_class_t storage_class = specifiers->storage_class;
4594 entity->declaration.declared_storage_class = storage_class;
4596 if (storage_class == STORAGE_CLASS_NONE
4597 && current_scope != file_scope) {
4598 storage_class = STORAGE_CLASS_AUTO;
4600 entity->declaration.storage_class = storage_class;
4603 parse_declaration_attributes(entity);
4608 static type_t *parse_abstract_declarator(type_t *base_type)
4610 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4612 type_t *result = construct_declarator_type(construct_type, base_type);
4613 if (construct_type != NULL) {
4614 obstack_free(&temp_obst, construct_type);
4621 * Check if the declaration of main is suspicious. main should be a
4622 * function with external linkage, returning int, taking either zero
4623 * arguments, two, or three arguments of appropriate types, ie.
4625 * int main([ int argc, char **argv [, char **env ] ]).
4627 * @param decl the declaration to check
4628 * @param type the function type of the declaration
4630 static void check_type_of_main(const entity_t *entity)
4632 const source_position_t *pos = &entity->base.source_position;
4633 if (entity->kind != ENTITY_FUNCTION) {
4634 warningf(pos, "'main' is not a function");
4638 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4639 warningf(pos, "'main' is normally a non-static function");
4642 type_t *type = skip_typeref(entity->declaration.type);
4643 assert(is_type_function(type));
4645 function_type_t *func_type = &type->function;
4646 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4647 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4648 func_type->return_type);
4650 const function_parameter_t *parm = func_type->parameters;
4652 type_t *const first_type = parm->type;
4653 if (!types_compatible(skip_typeref(first_type), type_int)) {
4655 "first argument of 'main' should be 'int', but is '%T'",
4660 type_t *const second_type = parm->type;
4661 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4662 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4666 type_t *const third_type = parm->type;
4667 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4668 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4672 goto warn_arg_count;
4676 warningf(pos, "'main' takes only zero, two or three arguments");
4682 * Check if a symbol is the equal to "main".
4684 static bool is_sym_main(const symbol_t *const sym)
4686 return strcmp(sym->string, "main") == 0;
4689 static const char *get_entity_kind_name(entity_kind_t kind)
4691 switch ((entity_kind_tag_t) kind) {
4692 case ENTITY_FUNCTION: return "function";
4693 case ENTITY_VARIABLE: return "variable";
4694 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4695 case ENTITY_STRUCT: return "struct";
4696 case ENTITY_UNION: return "union";
4697 case ENTITY_ENUM: return "enum";
4698 case ENTITY_ENUM_VALUE: return "enum value";
4699 case ENTITY_LABEL: return "label";
4700 case ENTITY_LOCAL_LABEL: return "local label";
4701 case ENTITY_TYPEDEF: return "typedef";
4702 case ENTITY_NAMESPACE: return "namespace";
4703 case ENTITY_INVALID: break;
4706 panic("Invalid entity kind encountered in get_entity_kind_name");
4709 static void error_redefined_as_different_kind(const source_position_t *pos,
4710 const entity_t *old, entity_kind_t new_kind)
4712 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4713 get_entity_kind_name(old->kind), old->base.symbol,
4714 get_entity_kind_name(new_kind), &old->base.source_position);
4718 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4719 * for various problems that occur for multiple definitions
4721 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4723 const symbol_t *const symbol = entity->base.symbol;
4724 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4725 const source_position_t *pos = &entity->base.source_position;
4727 assert(symbol != NULL);
4728 entity_t *previous_entity = get_entity(symbol, namespc);
4729 /* pushing the same entity twice will break the stack structure */
4730 assert(previous_entity != entity);
4732 if (entity->kind == ENTITY_FUNCTION) {
4733 type_t *const orig_type = entity->declaration.type;
4734 type_t *const type = skip_typeref(orig_type);
4736 assert(is_type_function(type));
4737 if (type->function.unspecified_parameters &&
4738 warning.strict_prototypes &&
4739 previous_entity == NULL) {
4740 warningf(pos, "function declaration '%#T' is not a prototype",
4744 if (warning.main && current_scope == file_scope
4745 && is_sym_main(symbol)) {
4746 check_type_of_main(entity);
4750 if (is_declaration(entity)) {
4751 if (warning.nested_externs
4752 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4753 && current_scope != file_scope) {
4754 warningf(pos, "nested extern declaration of '%#T'",
4755 entity->declaration.type, symbol);
4759 if (previous_entity != NULL
4760 && previous_entity->base.parent_scope == ¤t_function->parameters
4761 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4763 assert(previous_entity->kind == ENTITY_VARIABLE);
4765 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4766 entity->declaration.type, symbol,
4767 previous_entity->declaration.type, symbol,
4768 &previous_entity->base.source_position);
4772 if (previous_entity != NULL
4773 && previous_entity->base.parent_scope == current_scope) {
4775 if (previous_entity->kind != entity->kind) {
4776 error_redefined_as_different_kind(pos, previous_entity,
4780 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4782 "redeclaration of enum entry '%Y' (declared %P)",
4783 symbol, &previous_entity->base.source_position);
4786 if (previous_entity->kind == ENTITY_TYPEDEF) {
4787 /* TODO: C++ allows this for exactly the same type */
4789 "redefinition of typedef '%Y' (declared %P)",
4790 symbol, &previous_entity->base.source_position);
4794 /* at this point we should have only VARIABLES or FUNCTIONS */
4795 assert(is_declaration(previous_entity) && is_declaration(entity));
4797 /* can happen for K&R style declarations */
4798 if (previous_entity->kind == ENTITY_VARIABLE
4799 && previous_entity->declaration.type == NULL
4800 && entity->kind == ENTITY_VARIABLE) {
4801 previous_entity->declaration.type = entity->declaration.type;
4802 previous_entity->declaration.storage_class
4803 = entity->declaration.storage_class;
4804 previous_entity->declaration.declared_storage_class
4805 = entity->declaration.declared_storage_class;
4806 previous_entity->declaration.modifiers
4807 = entity->declaration.modifiers;
4808 previous_entity->declaration.deprecated_string
4809 = entity->declaration.deprecated_string;
4811 assert(entity->declaration.type != NULL);
4813 declaration_t *const previous_declaration
4814 = &previous_entity->declaration;
4815 declaration_t *const declaration = &entity->declaration;
4816 type_t *const orig_type = entity->declaration.type;
4817 type_t *const type = skip_typeref(orig_type);
4819 type_t *prev_type = skip_typeref(previous_declaration->type);
4821 if (!types_compatible(type, prev_type)) {
4823 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4824 orig_type, symbol, previous_declaration->type, symbol,
4825 &previous_entity->base.source_position);
4827 unsigned old_storage_class = previous_declaration->storage_class;
4828 if (warning.redundant_decls && is_definition
4829 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4830 && !(previous_declaration->modifiers & DM_USED)
4831 && !previous_declaration->used) {
4832 warningf(&previous_entity->base.source_position,
4833 "unnecessary static forward declaration for '%#T'",
4834 previous_declaration->type, symbol);
4837 unsigned new_storage_class = declaration->storage_class;
4838 if (is_type_incomplete(prev_type)) {
4839 previous_declaration->type = type;
4843 /* pretend no storage class means extern for function
4844 * declarations (except if the previous declaration is neither
4845 * none nor extern) */
4846 if (entity->kind == ENTITY_FUNCTION) {
4847 if (prev_type->function.unspecified_parameters) {
4848 previous_declaration->type = type;
4852 switch (old_storage_class) {
4853 case STORAGE_CLASS_NONE:
4854 old_storage_class = STORAGE_CLASS_EXTERN;
4857 case STORAGE_CLASS_EXTERN:
4858 if (is_definition) {
4859 if (warning.missing_prototypes &&
4860 prev_type->function.unspecified_parameters &&
4861 !is_sym_main(symbol)) {
4862 warningf(pos, "no previous prototype for '%#T'",
4865 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4866 new_storage_class = STORAGE_CLASS_EXTERN;
4875 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4876 new_storage_class == STORAGE_CLASS_EXTERN) {
4877 warn_redundant_declaration:
4878 if (!is_definition &&
4879 warning.redundant_decls &&
4880 is_type_valid(prev_type) &&
4881 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4883 "redundant declaration for '%Y' (declared %P)",
4884 symbol, &previous_entity->base.source_position);
4886 } else if (current_function == NULL) {
4887 if (old_storage_class != STORAGE_CLASS_STATIC &&
4888 new_storage_class == STORAGE_CLASS_STATIC) {
4890 "static declaration of '%Y' follows non-static declaration (declared %P)",
4891 symbol, &previous_entity->base.source_position);
4892 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4893 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4894 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4896 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4898 goto error_redeclaration;
4899 goto warn_redundant_declaration;
4901 } else if (is_type_valid(prev_type)) {
4902 if (old_storage_class == new_storage_class) {
4903 error_redeclaration:
4904 errorf(pos, "redeclaration of '%Y' (declared %P)",
4905 symbol, &previous_entity->base.source_position);
4908 "redeclaration of '%Y' with different linkage (declared %P)",
4909 symbol, &previous_entity->base.source_position);
4914 previous_declaration->modifiers |= declaration->modifiers;
4915 if (entity->kind == ENTITY_FUNCTION) {
4916 previous_entity->function.is_inline |= entity->function.is_inline;
4918 return previous_entity;
4921 if (entity->kind == ENTITY_FUNCTION) {
4922 if (is_definition &&
4923 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4924 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4925 warningf(pos, "no previous prototype for '%#T'",
4926 entity->declaration.type, symbol);
4927 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4928 warningf(pos, "no previous declaration for '%#T'",
4929 entity->declaration.type, symbol);
4932 } else if (warning.missing_declarations
4933 && entity->kind == ENTITY_VARIABLE
4934 && current_scope == file_scope) {
4935 declaration_t *declaration = &entity->declaration;
4936 if (declaration->storage_class == STORAGE_CLASS_NONE ||
4937 declaration->storage_class == STORAGE_CLASS_THREAD) {
4938 warningf(pos, "no previous declaration for '%#T'",
4939 declaration->type, symbol);
4944 assert(entity->base.parent_scope == NULL);
4945 assert(current_scope != NULL);
4947 entity->base.parent_scope = current_scope;
4948 entity->base.namespc = NAMESPACE_NORMAL;
4949 environment_push(entity);
4950 append_entity(current_scope, entity);
4955 static void parser_error_multiple_definition(entity_t *entity,
4956 const source_position_t *source_position)
4958 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4959 entity->base.symbol, &entity->base.source_position);
4962 static bool is_declaration_specifier(const token_t *token,
4963 bool only_specifiers_qualifiers)
4965 switch (token->type) {
4970 return is_typedef_symbol(token->v.symbol);
4972 case T___extension__:
4974 return !only_specifiers_qualifiers;
4981 static void parse_init_declarator_rest(entity_t *entity)
4983 assert(is_declaration(entity));
4984 declaration_t *const declaration = &entity->declaration;
4988 type_t *orig_type = declaration->type;
4989 type_t *type = skip_typeref(orig_type);
4991 if (entity->kind == ENTITY_VARIABLE
4992 && entity->variable.initializer != NULL) {
4993 parser_error_multiple_definition(entity, HERE);
4996 bool must_be_constant = false;
4997 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4998 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
4999 entity->base.parent_scope == file_scope) {
5000 must_be_constant = true;
5003 if (is_type_function(type)) {
5004 errorf(&entity->base.source_position,
5005 "function '%#T' is initialized like a variable",
5006 orig_type, entity->base.symbol);
5007 orig_type = type_error_type;
5010 parse_initializer_env_t env;
5011 env.type = orig_type;
5012 env.must_be_constant = must_be_constant;
5013 env.entity = entity;
5014 current_init_decl = entity;
5016 initializer_t *initializer = parse_initializer(&env);
5017 current_init_decl = NULL;
5019 if (entity->kind == ENTITY_VARIABLE) {
5020 /* § 6.7.5 (22) array initializers for arrays with unknown size
5021 * determine the array type size */
5022 declaration->type = env.type;
5023 entity->variable.initializer = initializer;
5027 /* parse rest of a declaration without any declarator */
5028 static void parse_anonymous_declaration_rest(
5029 const declaration_specifiers_t *specifiers)
5033 if (warning.other) {
5034 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5035 warningf(&specifiers->source_position,
5036 "useless storage class in empty declaration");
5039 type_t *type = specifiers->type;
5040 switch (type->kind) {
5041 case TYPE_COMPOUND_STRUCT:
5042 case TYPE_COMPOUND_UNION: {
5043 if (type->compound.compound->base.symbol == NULL) {
5044 warningf(&specifiers->source_position,
5045 "unnamed struct/union that defines no instances");
5054 warningf(&specifiers->source_position, "empty declaration");
5060 static void parse_declaration_rest(entity_t *ndeclaration,
5061 const declaration_specifiers_t *specifiers,
5062 parsed_declaration_func finished_declaration)
5064 add_anchor_token(';');
5065 add_anchor_token(',');
5067 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5069 if (token.type == '=') {
5070 parse_init_declarator_rest(entity);
5073 if (token.type != ',')
5077 add_anchor_token('=');
5078 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5079 rem_anchor_token('=');
5084 rem_anchor_token(';');
5085 rem_anchor_token(',');
5088 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5090 symbol_t *symbol = entity->base.symbol;
5091 if (symbol == NULL) {
5092 errorf(HERE, "anonymous declaration not valid as function parameter");
5096 assert(entity->base.namespc == NAMESPACE_NORMAL);
5097 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5098 if (previous_entity == NULL
5099 || previous_entity->base.parent_scope != current_scope) {
5100 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5105 if (is_definition) {
5106 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5109 return record_entity(entity, false);
5112 static void parse_declaration(parsed_declaration_func finished_declaration)
5114 declaration_specifiers_t specifiers;
5115 memset(&specifiers, 0, sizeof(specifiers));
5117 add_anchor_token(';');
5118 parse_declaration_specifiers(&specifiers);
5119 rem_anchor_token(';');
5121 if (token.type == ';') {
5122 parse_anonymous_declaration_rest(&specifiers);
5124 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5125 parse_declaration_rest(entity, &specifiers, finished_declaration);
5129 static type_t *get_default_promoted_type(type_t *orig_type)
5131 type_t *result = orig_type;
5133 type_t *type = skip_typeref(orig_type);
5134 if (is_type_integer(type)) {
5135 result = promote_integer(type);
5136 } else if (type == type_float) {
5137 result = type_double;
5143 static void parse_kr_declaration_list(entity_t *entity)
5145 if (entity->kind != ENTITY_FUNCTION)
5148 type_t *type = skip_typeref(entity->declaration.type);
5149 assert(is_type_function(type));
5150 if (!type->function.kr_style_parameters)
5154 add_anchor_token('{');
5156 /* push function parameters */
5157 size_t const top = environment_top();
5158 scope_push(&entity->function.parameters);
5160 entity_t *parameter = entity->function.parameters.entities;
5161 for ( ; parameter != NULL; parameter = parameter->base.next) {
5162 assert(parameter->base.parent_scope == NULL);
5163 parameter->base.parent_scope = current_scope;
5164 environment_push(parameter);
5167 /* parse declaration list */
5168 while (is_declaration_specifier(&token, false)) {
5169 parse_declaration(finished_kr_declaration);
5172 /* pop function parameters */
5173 assert(current_scope == &entity->function.parameters);
5175 environment_pop_to(top);
5177 /* update function type */
5178 type_t *new_type = duplicate_type(type);
5180 function_parameter_t *parameters = NULL;
5181 function_parameter_t *last_parameter = NULL;
5183 entity_t *parameter_declaration = entity->function.parameters.entities;
5184 for( ; parameter_declaration != NULL;
5185 parameter_declaration = parameter_declaration->base.next) {
5186 type_t *parameter_type = parameter_declaration->declaration.type;
5187 if (parameter_type == NULL) {
5189 errorf(HERE, "no type specified for function parameter '%Y'",
5190 parameter_declaration->base.symbol);
5192 if (warning.implicit_int) {
5193 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5194 parameter_declaration->base.symbol);
5196 parameter_type = type_int;
5197 parameter_declaration->declaration.type = parameter_type;
5201 semantic_parameter(¶meter_declaration->declaration);
5202 parameter_type = parameter_declaration->declaration.type;
5205 * we need the default promoted types for the function type
5207 parameter_type = get_default_promoted_type(parameter_type);
5209 function_parameter_t *function_parameter
5210 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5211 memset(function_parameter, 0, sizeof(function_parameter[0]));
5213 function_parameter->type = parameter_type;
5214 if (last_parameter != NULL) {
5215 last_parameter->next = function_parameter;
5217 parameters = function_parameter;
5219 last_parameter = function_parameter;
5222 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5224 new_type->function.parameters = parameters;
5225 new_type->function.unspecified_parameters = true;
5227 type = typehash_insert(new_type);
5228 if (type != new_type) {
5229 obstack_free(type_obst, new_type);
5232 entity->declaration.type = type;
5234 rem_anchor_token('{');
5237 static bool first_err = true;
5240 * When called with first_err set, prints the name of the current function,
5243 static void print_in_function(void)
5247 diagnosticf("%s: In function '%Y':\n",
5248 current_function->base.base.source_position.input_name,
5249 current_function->base.base.symbol);
5254 * Check if all labels are defined in the current function.
5255 * Check if all labels are used in the current function.
5257 static void check_labels(void)
5259 for (const goto_statement_t *goto_statement = goto_first;
5260 goto_statement != NULL;
5261 goto_statement = goto_statement->next) {
5262 /* skip computed gotos */
5263 if (goto_statement->expression != NULL)
5266 label_t *label = goto_statement->label;
5269 if (label->base.source_position.input_name == NULL) {
5270 print_in_function();
5271 errorf(&goto_statement->base.source_position,
5272 "label '%Y' used but not defined", label->base.symbol);
5278 if (warning.unused_label) {
5279 for (const label_statement_t *label_statement = label_first;
5280 label_statement != NULL;
5281 label_statement = label_statement->next) {
5282 label_t *label = label_statement->label;
5284 if (! label->used) {
5285 print_in_function();
5286 warningf(&label_statement->base.source_position,
5287 "label '%Y' defined but not used", label->base.symbol);
5291 label_first = label_last = NULL;
5294 static void warn_unused_decl(entity_t *entity, entity_t *end,
5295 char const *const what)
5297 for (; entity != NULL; entity = entity->base.next) {
5298 if (!is_declaration(entity))
5301 declaration_t *declaration = &entity->declaration;
5302 if (declaration->implicit)
5305 if (!declaration->used) {
5306 print_in_function();
5307 warningf(&entity->base.source_position, "%s '%Y' is unused",
5308 what, entity->base.symbol);
5309 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5310 print_in_function();
5311 warningf(&entity->base.source_position, "%s '%Y' is never read",
5312 what, entity->base.symbol);
5320 static void check_unused_variables(statement_t *const stmt, void *const env)
5324 switch (stmt->kind) {
5325 case STATEMENT_DECLARATION: {
5326 declaration_statement_t const *const decls = &stmt->declaration;
5327 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5333 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5342 * Check declarations of current_function for unused entities.
5344 static void check_declarations(void)
5346 if (warning.unused_parameter) {
5347 const scope_t *scope = ¤t_function->parameters;
5349 /* do not issue unused warnings for main */
5350 if (!is_sym_main(current_function->base.base.symbol)) {
5351 warn_unused_decl(scope->entities, NULL, "parameter");
5354 if (warning.unused_variable) {
5355 walk_statements(current_function->statement, check_unused_variables,
5360 static int determine_truth(expression_t const* const cond)
5363 !is_constant_expression(cond) ? 0 :
5364 fold_constant(cond) != 0 ? 1 :
5368 static bool expression_returns(expression_t const *const expr)
5370 switch (expr->kind) {
5372 expression_t const *const func = expr->call.function;
5373 if (func->kind == EXPR_REFERENCE) {
5374 entity_t *entity = func->reference.entity;
5375 if (entity->kind == ENTITY_FUNCTION
5376 && entity->declaration.modifiers & DM_NORETURN)
5380 if (!expression_returns(func))
5383 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5384 if (!expression_returns(arg->expression))
5391 case EXPR_REFERENCE:
5392 case EXPR_REFERENCE_ENUM_VALUE:
5394 case EXPR_CHARACTER_CONSTANT:
5395 case EXPR_WIDE_CHARACTER_CONSTANT:
5396 case EXPR_STRING_LITERAL:
5397 case EXPR_WIDE_STRING_LITERAL:
5398 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5399 case EXPR_LABEL_ADDRESS:
5400 case EXPR_CLASSIFY_TYPE:
5401 case EXPR_SIZEOF: // TODO handle obscure VLA case
5404 case EXPR_BUILTIN_SYMBOL:
5405 case EXPR_BUILTIN_CONSTANT_P:
5406 case EXPR_BUILTIN_PREFETCH:
5409 case EXPR_STATEMENT: // TODO implement
5412 case EXPR_CONDITIONAL:
5413 // TODO handle constant expression
5415 expression_returns(expr->conditional.condition) && (
5416 expression_returns(expr->conditional.true_expression) ||
5417 expression_returns(expr->conditional.false_expression)
5421 return expression_returns(expr->select.compound);
5423 case EXPR_ARRAY_ACCESS:
5425 expression_returns(expr->array_access.array_ref) &&
5426 expression_returns(expr->array_access.index);
5429 return expression_returns(expr->va_starte.ap);
5432 return expression_returns(expr->va_arge.ap);
5434 EXPR_UNARY_CASES_MANDATORY
5435 return expression_returns(expr->unary.value);
5437 case EXPR_UNARY_THROW:
5441 // TODO handle constant lhs of && and ||
5443 expression_returns(expr->binary.left) &&
5444 expression_returns(expr->binary.right);
5450 panic("unhandled expression");
5453 static bool noreturn_candidate;
5455 static void check_reachable(statement_t *const stmt)
5457 if (stmt->base.reachable)
5459 if (stmt->kind != STATEMENT_DO_WHILE)
5460 stmt->base.reachable = true;
5462 statement_t *last = stmt;
5464 switch (stmt->kind) {
5465 case STATEMENT_INVALID:
5466 case STATEMENT_EMPTY:
5467 case STATEMENT_DECLARATION:
5468 case STATEMENT_LOCAL_LABEL:
5470 next = stmt->base.next;
5473 case STATEMENT_COMPOUND:
5474 next = stmt->compound.statements;
5477 case STATEMENT_RETURN:
5478 noreturn_candidate = false;
5481 case STATEMENT_IF: {
5482 if_statement_t const* const ifs = &stmt->ifs;
5483 int const val = determine_truth(ifs->condition);
5486 check_reachable(ifs->true_statement);
5491 if (ifs->false_statement != NULL) {
5492 check_reachable(ifs->false_statement);
5496 next = stmt->base.next;
5500 case STATEMENT_SWITCH: {
5501 switch_statement_t const *const switchs = &stmt->switchs;
5502 expression_t const *const expr = switchs->expression;
5504 if (is_constant_expression(expr)) {
5505 long const val = fold_constant(expr);
5506 case_label_statement_t * defaults = NULL;
5507 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5508 if (i->expression == NULL) {
5513 if (i->first_case <= val && val <= i->last_case) {
5514 check_reachable((statement_t*)i);
5519 if (defaults != NULL) {
5520 check_reachable((statement_t*)defaults);
5524 bool has_default = false;
5525 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5526 if (i->expression == NULL)
5529 check_reachable((statement_t*)i);
5536 next = stmt->base.next;
5540 case STATEMENT_EXPRESSION: {
5541 /* Check for noreturn function call */
5542 expression_t const *const expr = stmt->expression.expression;
5543 if (!expression_returns(expr))
5546 next = stmt->base.next;
5550 case STATEMENT_CONTINUE: {
5551 statement_t *parent = stmt;
5553 parent = parent->base.parent;
5554 if (parent == NULL) /* continue not within loop */
5558 switch (parent->kind) {
5559 case STATEMENT_WHILE: goto continue_while;
5560 case STATEMENT_DO_WHILE: goto continue_do_while;
5561 case STATEMENT_FOR: goto continue_for;
5568 case STATEMENT_BREAK: {
5569 statement_t *parent = stmt;
5571 parent = parent->base.parent;
5572 if (parent == NULL) /* break not within loop/switch */
5575 switch (parent->kind) {
5576 case STATEMENT_SWITCH:
5577 case STATEMENT_WHILE:
5578 case STATEMENT_DO_WHILE:
5581 next = parent->base.next;
5582 goto found_break_parent;
5591 case STATEMENT_GOTO:
5592 if (stmt->gotos.expression) {
5593 statement_t *parent = stmt->base.parent;
5594 if (parent == NULL) /* top level goto */
5598 next = stmt->gotos.label->statement;
5599 if (next == NULL) /* missing label */
5604 case STATEMENT_LABEL:
5605 next = stmt->label.statement;
5608 case STATEMENT_CASE_LABEL:
5609 next = stmt->case_label.statement;
5612 case STATEMENT_WHILE: {
5613 while_statement_t const *const whiles = &stmt->whiles;
5614 int const val = determine_truth(whiles->condition);
5617 check_reachable(whiles->body);
5622 next = stmt->base.next;
5626 case STATEMENT_DO_WHILE:
5627 next = stmt->do_while.body;
5630 case STATEMENT_FOR: {
5631 for_statement_t *const fors = &stmt->fors;
5633 if (fors->condition_reachable)
5635 fors->condition_reachable = true;
5637 expression_t const *const cond = fors->condition;
5639 cond == NULL ? 1 : determine_truth(cond);
5642 check_reachable(fors->body);
5647 next = stmt->base.next;
5651 case STATEMENT_MS_TRY: {
5652 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5653 check_reachable(ms_try->try_statement);
5654 next = ms_try->final_statement;
5658 case STATEMENT_LEAVE: {
5659 statement_t *parent = stmt;
5661 parent = parent->base.parent;
5662 if (parent == NULL) /* __leave not within __try */
5665 if (parent->kind == STATEMENT_MS_TRY) {
5667 next = parent->ms_try.final_statement;
5675 while (next == NULL) {
5676 next = last->base.parent;
5678 noreturn_candidate = false;
5680 type_t *const type = current_function->base.type;
5681 assert(is_type_function(type));
5682 type_t *const ret = skip_typeref(type->function.return_type);
5683 if (warning.return_type &&
5684 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5685 is_type_valid(ret) &&
5686 !is_sym_main(current_function->base.base.symbol)) {
5687 warningf(&stmt->base.source_position,
5688 "control reaches end of non-void function");
5693 switch (next->kind) {
5694 case STATEMENT_INVALID:
5695 case STATEMENT_EMPTY:
5696 case STATEMENT_DECLARATION:
5697 case STATEMENT_LOCAL_LABEL:
5698 case STATEMENT_EXPRESSION:
5700 case STATEMENT_RETURN:
5701 case STATEMENT_CONTINUE:
5702 case STATEMENT_BREAK:
5703 case STATEMENT_GOTO:
5704 case STATEMENT_LEAVE:
5705 panic("invalid control flow in function");
5707 case STATEMENT_COMPOUND:
5709 case STATEMENT_SWITCH:
5710 case STATEMENT_LABEL:
5711 case STATEMENT_CASE_LABEL:
5713 next = next->base.next;
5716 case STATEMENT_WHILE: {
5718 if (next->base.reachable)
5720 next->base.reachable = true;
5722 while_statement_t const *const whiles = &next->whiles;
5723 int const val = determine_truth(whiles->condition);
5726 check_reachable(whiles->body);
5732 next = next->base.next;
5736 case STATEMENT_DO_WHILE: {
5738 if (next->base.reachable)
5740 next->base.reachable = true;
5742 do_while_statement_t const *const dw = &next->do_while;
5743 int const val = determine_truth(dw->condition);
5746 check_reachable(dw->body);
5752 next = next->base.next;
5756 case STATEMENT_FOR: {
5758 for_statement_t *const fors = &next->fors;
5760 fors->step_reachable = true;
5762 if (fors->condition_reachable)
5764 fors->condition_reachable = true;
5766 expression_t const *const cond = fors->condition;
5768 cond == NULL ? 1 : determine_truth(cond);
5771 check_reachable(fors->body);
5777 next = next->base.next;
5781 case STATEMENT_MS_TRY:
5783 next = next->ms_try.final_statement;
5788 check_reachable(next);
5791 static void check_unreachable(statement_t* const stmt, void *const env)
5795 switch (stmt->kind) {
5796 case STATEMENT_DO_WHILE:
5797 if (!stmt->base.reachable) {
5798 expression_t const *const cond = stmt->do_while.condition;
5799 if (determine_truth(cond) >= 0) {
5800 warningf(&cond->base.source_position,
5801 "condition of do-while-loop is unreachable");
5806 case STATEMENT_FOR: {
5807 for_statement_t const* const fors = &stmt->fors;
5809 // if init and step are unreachable, cond is unreachable, too
5810 if (!stmt->base.reachable && !fors->step_reachable) {
5811 warningf(&stmt->base.source_position, "statement is unreachable");
5813 if (!stmt->base.reachable && fors->initialisation != NULL) {
5814 warningf(&fors->initialisation->base.source_position,
5815 "initialisation of for-statement is unreachable");
5818 if (!fors->condition_reachable && fors->condition != NULL) {
5819 warningf(&fors->condition->base.source_position,
5820 "condition of for-statement is unreachable");
5823 if (!fors->step_reachable && fors->step != NULL) {
5824 warningf(&fors->step->base.source_position,
5825 "step of for-statement is unreachable");
5831 case STATEMENT_COMPOUND:
5832 if (stmt->compound.statements != NULL)
5837 if (!stmt->base.reachable)
5838 warningf(&stmt->base.source_position, "statement is unreachable");
5843 static void parse_external_declaration(void)
5845 /* function-definitions and declarations both start with declaration
5847 declaration_specifiers_t specifiers;
5848 memset(&specifiers, 0, sizeof(specifiers));
5850 add_anchor_token(';');
5851 parse_declaration_specifiers(&specifiers);
5852 rem_anchor_token(';');
5854 /* must be a declaration */
5855 if (token.type == ';') {
5856 parse_anonymous_declaration_rest(&specifiers);
5860 add_anchor_token(',');
5861 add_anchor_token('=');
5862 add_anchor_token(';');
5863 add_anchor_token('{');
5865 /* declarator is common to both function-definitions and declarations */
5866 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5868 rem_anchor_token('{');
5869 rem_anchor_token(';');
5870 rem_anchor_token('=');
5871 rem_anchor_token(',');
5873 /* must be a declaration */
5874 switch (token.type) {
5878 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
5882 /* must be a function definition */
5883 parse_kr_declaration_list(ndeclaration);
5885 if (token.type != '{') {
5886 parse_error_expected("while parsing function definition", '{', NULL);
5887 eat_until_matching_token(';');
5891 assert(is_declaration(ndeclaration));
5892 type_t *type = skip_typeref(ndeclaration->declaration.type);
5894 if (!is_type_function(type)) {
5895 if (is_type_valid(type)) {
5896 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5897 type, ndeclaration->base.symbol);
5903 if (warning.aggregate_return &&
5904 is_type_compound(skip_typeref(type->function.return_type))) {
5905 warningf(HERE, "function '%Y' returns an aggregate",
5906 ndeclaration->base.symbol);
5908 if (warning.traditional && !type->function.unspecified_parameters) {
5909 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5910 ndeclaration->base.symbol);
5912 if (warning.old_style_definition && type->function.unspecified_parameters) {
5913 warningf(HERE, "old-style function definition '%Y'",
5914 ndeclaration->base.symbol);
5917 /* § 6.7.5.3 (14) a function definition with () means no
5918 * parameters (and not unspecified parameters) */
5919 if (type->function.unspecified_parameters
5920 && type->function.parameters == NULL
5921 && !type->function.kr_style_parameters) {
5922 type_t *duplicate = duplicate_type(type);
5923 duplicate->function.unspecified_parameters = false;
5925 type = typehash_insert(duplicate);
5926 if (type != duplicate) {
5927 obstack_free(type_obst, duplicate);
5929 ndeclaration->declaration.type = type;
5932 entity_t *const entity = record_entity(ndeclaration, true);
5933 assert(entity->kind == ENTITY_FUNCTION);
5934 assert(ndeclaration->kind == ENTITY_FUNCTION);
5936 function_t *function = &entity->function;
5937 if (ndeclaration != entity) {
5938 function->parameters = ndeclaration->function.parameters;
5940 assert(is_declaration(entity));
5941 type = skip_typeref(entity->declaration.type);
5943 /* push function parameters and switch scope */
5944 size_t const top = environment_top();
5945 scope_push(&function->parameters);
5947 entity_t *parameter = function->parameters.entities;
5948 for( ; parameter != NULL; parameter = parameter->base.next) {
5949 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5950 parameter->base.parent_scope = current_scope;
5952 assert(parameter->base.parent_scope == NULL
5953 || parameter->base.parent_scope == current_scope);
5954 parameter->base.parent_scope = current_scope;
5955 if (parameter->base.symbol == NULL) {
5956 errorf(¶meter->base.source_position, "parameter name omitted");
5959 environment_push(parameter);
5962 if (function->statement != NULL) {
5963 parser_error_multiple_definition(entity, HERE);
5966 /* parse function body */
5967 int label_stack_top = label_top();
5968 function_t *old_current_function = current_function;
5969 current_function = function;
5970 current_parent = NULL;
5972 statement_t *const body = parse_compound_statement(false);
5973 function->statement = body;
5976 check_declarations();
5977 if (warning.return_type ||
5978 warning.unreachable_code ||
5979 (warning.missing_noreturn
5980 && !(function->base.modifiers & DM_NORETURN))) {
5981 noreturn_candidate = true;
5982 check_reachable(body);
5983 if (warning.unreachable_code)
5984 walk_statements(body, check_unreachable, NULL);
5985 if (warning.missing_noreturn &&
5986 noreturn_candidate &&
5987 !(function->base.modifiers & DM_NORETURN)) {
5988 warningf(&body->base.source_position,
5989 "function '%#T' is candidate for attribute 'noreturn'",
5990 type, entity->base.symbol);
5994 assert(current_parent == NULL);
5995 assert(current_function == function);
5996 current_function = old_current_function;
5997 label_pop_to(label_stack_top);
6000 assert(current_scope == &function->parameters);
6002 environment_pop_to(top);
6005 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6006 source_position_t *source_position,
6007 const symbol_t *symbol)
6009 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6011 type->bitfield.base_type = base_type;
6012 type->bitfield.size_expression = size;
6015 type_t *skipped_type = skip_typeref(base_type);
6016 if (!is_type_integer(skipped_type)) {
6017 errorf(HERE, "bitfield base type '%T' is not an integer type",
6021 bit_size = skipped_type->base.size * 8;
6024 if (is_constant_expression(size)) {
6025 long v = fold_constant(size);
6028 errorf(source_position, "negative width in bit-field '%Y'",
6030 } else if (v == 0) {
6031 errorf(source_position, "zero width for bit-field '%Y'",
6033 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6034 errorf(source_position, "width of '%Y' exceeds its type",
6037 type->bitfield.bit_size = v;
6044 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6046 entity_t *iter = compound->members.entities;
6047 for( ; iter != NULL; iter = iter->base.next) {
6048 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6051 if (iter->base.symbol == NULL) {
6052 type_t *type = skip_typeref(iter->declaration.type);
6053 if (is_type_compound(type)) {
6055 = find_compound_entry(type->compound.compound, symbol);
6062 if (iter->base.symbol == symbol) {
6070 static void parse_compound_declarators(compound_t *compound,
6071 const declaration_specifiers_t *specifiers)
6076 if (token.type == ':') {
6077 source_position_t source_position = *HERE;
6080 type_t *base_type = specifiers->type;
6081 expression_t *size = parse_constant_expression();
6083 type_t *type = make_bitfield_type(base_type, size,
6084 &source_position, sym_anonymous);
6086 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6087 entity->base.namespc = NAMESPACE_NORMAL;
6088 entity->base.source_position = source_position;
6089 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6090 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6091 entity->declaration.modifiers = specifiers->modifiers;
6092 entity->declaration.type = type;
6094 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6095 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6097 if (token.type == ':') {
6098 source_position_t source_position = *HERE;
6100 expression_t *size = parse_constant_expression();
6102 type_t *type = entity->declaration.type;
6103 type_t *bitfield_type = make_bitfield_type(type, size,
6104 &source_position, entity->base.symbol);
6105 entity->declaration.type = bitfield_type;
6109 /* make sure we don't define a symbol multiple times */
6110 symbol_t *symbol = entity->base.symbol;
6111 if (symbol != NULL) {
6112 entity_t *prev = find_compound_entry(compound, symbol);
6115 assert(prev->base.symbol == symbol);
6116 errorf(&entity->base.source_position,
6117 "multiple declarations of symbol '%Y' (declared %P)",
6118 symbol, &prev->base.source_position);
6122 append_entity(&compound->members, entity);
6124 if (token.type != ',')
6134 static void semantic_compound(compound_t *compound)
6136 entity_t *entity = compound->members.entities;
6137 for ( ; entity != NULL; entity = entity->base.next) {
6138 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6140 type_t *orig_type = entity->declaration.type;
6141 type_t *type = skip_typeref(orig_type);
6143 if (is_type_function(type)) {
6145 "compound member '%Y' must not have function type '%T'",
6146 entity->base.symbol, orig_type);
6147 } else if (is_type_incomplete(type)) {
6148 /* §6.7.2.1 (16) flexible array member */
6149 if (is_type_array(type) && entity->base.next == NULL) {
6150 compound->has_flexible_member = true;
6153 "compound member '%Y' has incomplete type '%T'",
6154 entity->base.symbol, orig_type);
6160 static void parse_compound_type_entries(compound_t *compound)
6163 add_anchor_token('}');
6165 while (token.type != '}') {
6166 if (token.type == T_EOF) {
6167 errorf(HERE, "EOF while parsing struct");
6170 declaration_specifiers_t specifiers;
6171 memset(&specifiers, 0, sizeof(specifiers));
6172 parse_declaration_specifiers(&specifiers);
6174 parse_compound_declarators(compound, &specifiers);
6176 semantic_compound(compound);
6177 rem_anchor_token('}');
6181 static type_t *parse_typename(void)
6183 declaration_specifiers_t specifiers;
6184 memset(&specifiers, 0, sizeof(specifiers));
6185 parse_declaration_specifiers(&specifiers);
6186 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6187 /* TODO: improve error message, user does probably not know what a
6188 * storage class is...
6190 errorf(HERE, "typename may not have a storage class");
6193 type_t *result = parse_abstract_declarator(specifiers.type);
6201 typedef expression_t* (*parse_expression_function)(void);
6202 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6204 typedef struct expression_parser_function_t expression_parser_function_t;
6205 struct expression_parser_function_t {
6206 parse_expression_function parser;
6207 unsigned infix_precedence;
6208 parse_expression_infix_function infix_parser;
6211 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6214 * Prints an error message if an expression was expected but not read
6216 static expression_t *expected_expression_error(void)
6218 /* skip the error message if the error token was read */
6219 if (token.type != T_ERROR) {
6220 errorf(HERE, "expected expression, got token '%K'", &token);
6224 return create_invalid_expression();
6228 * Parse a string constant.
6230 static expression_t *parse_string_const(void)
6233 if (token.type == T_STRING_LITERAL) {
6234 string_t res = token.v.string;
6236 while (token.type == T_STRING_LITERAL) {
6237 res = concat_strings(&res, &token.v.string);
6240 if (token.type != T_WIDE_STRING_LITERAL) {
6241 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6242 /* note: that we use type_char_ptr here, which is already the
6243 * automatic converted type. revert_automatic_type_conversion
6244 * will construct the array type */
6245 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6246 cnst->string.value = res;
6250 wres = concat_string_wide_string(&res, &token.v.wide_string);
6252 wres = token.v.wide_string;
6257 switch (token.type) {
6258 case T_WIDE_STRING_LITERAL:
6259 wres = concat_wide_strings(&wres, &token.v.wide_string);
6262 case T_STRING_LITERAL:
6263 wres = concat_wide_string_string(&wres, &token.v.string);
6267 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6268 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6269 cnst->wide_string.value = wres;
6278 * Parse a boolean constant.
6280 static expression_t *parse_bool_const(bool value)
6282 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6283 cnst->base.type = type_bool;
6284 cnst->conste.v.int_value = value;
6292 * Parse an integer constant.
6294 static expression_t *parse_int_const(void)
6296 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6297 cnst->base.type = token.datatype;
6298 cnst->conste.v.int_value = token.v.intvalue;
6306 * Parse a character constant.
6308 static expression_t *parse_character_constant(void)
6310 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6311 cnst->base.type = token.datatype;
6312 cnst->conste.v.character = token.v.string;
6314 if (cnst->conste.v.character.size != 1) {
6315 if (warning.multichar && GNU_MODE) {
6316 warningf(HERE, "multi-character character constant");
6318 errorf(HERE, "more than 1 characters in character constant");
6327 * Parse a wide character constant.
6329 static expression_t *parse_wide_character_constant(void)
6331 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6332 cnst->base.type = token.datatype;
6333 cnst->conste.v.wide_character = token.v.wide_string;
6335 if (cnst->conste.v.wide_character.size != 1) {
6336 if (warning.multichar && GNU_MODE) {
6337 warningf(HERE, "multi-character character constant");
6339 errorf(HERE, "more than 1 characters in character constant");
6348 * Parse a float constant.
6350 static expression_t *parse_float_const(void)
6352 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6353 cnst->base.type = token.datatype;
6354 cnst->conste.v.float_value = token.v.floatvalue;
6361 static entity_t *create_implicit_function(symbol_t *symbol,
6362 const source_position_t *source_position)
6364 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6365 ntype->function.return_type = type_int;
6366 ntype->function.unspecified_parameters = true;
6368 type_t *type = typehash_insert(ntype);
6369 if (type != ntype) {
6373 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6374 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6375 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6376 entity->declaration.type = type;
6377 entity->declaration.implicit = true;
6378 entity->base.symbol = symbol;
6379 entity->base.source_position = *source_position;
6381 bool strict_prototypes_old = warning.strict_prototypes;
6382 warning.strict_prototypes = false;
6383 record_entity(entity, false);
6384 warning.strict_prototypes = strict_prototypes_old;
6390 * Creates a return_type (func)(argument_type) function type if not
6393 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6394 type_t *argument_type2)
6396 function_parameter_t *parameter2
6397 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6398 memset(parameter2, 0, sizeof(parameter2[0]));
6399 parameter2->type = argument_type2;
6401 function_parameter_t *parameter1
6402 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6403 memset(parameter1, 0, sizeof(parameter1[0]));
6404 parameter1->type = argument_type1;
6405 parameter1->next = parameter2;
6407 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6408 type->function.return_type = return_type;
6409 type->function.parameters = parameter1;
6411 type_t *result = typehash_insert(type);
6412 if (result != type) {
6420 * Creates a return_type (func)(argument_type) function type if not
6423 * @param return_type the return type
6424 * @param argument_type the argument type
6426 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6428 function_parameter_t *parameter
6429 = obstack_alloc(type_obst, sizeof(parameter[0]));
6430 memset(parameter, 0, sizeof(parameter[0]));
6431 parameter->type = argument_type;
6433 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6434 type->function.return_type = return_type;
6435 type->function.parameters = parameter;
6437 type_t *result = typehash_insert(type);
6438 if (result != type) {
6445 static type_t *make_function_0_type(type_t *return_type)
6447 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6448 type->function.return_type = return_type;
6449 type->function.parameters = NULL;
6451 type_t *result = typehash_insert(type);
6452 if (result != type) {
6460 * Creates a function type for some function like builtins.
6462 * @param symbol the symbol describing the builtin
6464 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6466 switch (symbol->ID) {
6467 case T___builtin_alloca:
6468 return make_function_1_type(type_void_ptr, type_size_t);
6469 case T___builtin_huge_val:
6470 return make_function_0_type(type_double);
6471 case T___builtin_inf:
6472 return make_function_0_type(type_double);
6473 case T___builtin_inff:
6474 return make_function_0_type(type_float);
6475 case T___builtin_infl:
6476 return make_function_0_type(type_long_double);
6477 case T___builtin_nan:
6478 return make_function_1_type(type_double, type_char_ptr);
6479 case T___builtin_nanf:
6480 return make_function_1_type(type_float, type_char_ptr);
6481 case T___builtin_nanl:
6482 return make_function_1_type(type_long_double, type_char_ptr);
6483 case T___builtin_va_end:
6484 return make_function_1_type(type_void, type_valist);
6485 case T___builtin_expect:
6486 return make_function_2_type(type_long, type_long, type_long);
6488 internal_errorf(HERE, "not implemented builtin symbol found");
6493 * Performs automatic type cast as described in § 6.3.2.1.
6495 * @param orig_type the original type
6497 static type_t *automatic_type_conversion(type_t *orig_type)
6499 type_t *type = skip_typeref(orig_type);
6500 if (is_type_array(type)) {
6501 array_type_t *array_type = &type->array;
6502 type_t *element_type = array_type->element_type;
6503 unsigned qualifiers = array_type->base.qualifiers;
6505 return make_pointer_type(element_type, qualifiers);
6508 if (is_type_function(type)) {
6509 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6516 * reverts the automatic casts of array to pointer types and function
6517 * to function-pointer types as defined § 6.3.2.1
6519 type_t *revert_automatic_type_conversion(const expression_t *expression)
6521 switch (expression->kind) {
6522 case EXPR_REFERENCE: {
6523 entity_t *entity = expression->reference.entity;
6524 if (is_declaration(entity)) {
6525 return entity->declaration.type;
6526 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6527 return entity->enum_value.enum_type;
6529 panic("no declaration or enum in reference");
6534 entity_t *entity = expression->select.compound_entry;
6535 assert(is_declaration(entity));
6536 type_t *type = entity->declaration.type;
6537 return get_qualified_type(type,
6538 expression->base.type->base.qualifiers);
6541 case EXPR_UNARY_DEREFERENCE: {
6542 const expression_t *const value = expression->unary.value;
6543 type_t *const type = skip_typeref(value->base.type);
6544 assert(is_type_pointer(type));
6545 return type->pointer.points_to;
6548 case EXPR_BUILTIN_SYMBOL:
6549 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6551 case EXPR_ARRAY_ACCESS: {
6552 const expression_t *array_ref = expression->array_access.array_ref;
6553 type_t *type_left = skip_typeref(array_ref->base.type);
6554 if (!is_type_valid(type_left))
6556 assert(is_type_pointer(type_left));
6557 return type_left->pointer.points_to;
6560 case EXPR_STRING_LITERAL: {
6561 size_t size = expression->string.value.size;
6562 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6565 case EXPR_WIDE_STRING_LITERAL: {
6566 size_t size = expression->wide_string.value.size;
6567 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6570 case EXPR_COMPOUND_LITERAL:
6571 return expression->compound_literal.type;
6576 return expression->base.type;
6579 static expression_t *parse_reference(void)
6581 symbol_t *const symbol = token.v.symbol;
6583 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6585 if (entity == NULL) {
6586 if (!strict_mode && look_ahead(1)->type == '(') {
6587 /* an implicitly declared function */
6588 if (warning.implicit_function_declaration) {
6589 warningf(HERE, "implicit declaration of function '%Y'",
6593 entity = create_implicit_function(symbol, HERE);
6595 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6596 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6602 if (is_declaration(entity)) {
6603 orig_type = entity->declaration.type;
6604 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6605 orig_type = entity->enum_value.enum_type;
6606 } else if (entity->kind == ENTITY_TYPEDEF) {
6607 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6610 return create_invalid_expression();
6612 panic("expected declaration or enum value in reference");
6615 /* we always do the auto-type conversions; the & and sizeof parser contains
6616 * code to revert this! */
6617 type_t *type = automatic_type_conversion(orig_type);
6619 expression_kind_t kind = EXPR_REFERENCE;
6620 if (entity->kind == ENTITY_ENUM_VALUE)
6621 kind = EXPR_REFERENCE_ENUM_VALUE;
6623 expression_t *expression = allocate_expression_zero(kind);
6624 expression->reference.entity = entity;
6625 expression->base.type = type;
6627 /* this declaration is used */
6628 if (is_declaration(entity)) {
6629 entity->declaration.used = true;
6632 if (entity->base.parent_scope != file_scope
6633 && entity->base.parent_scope->depth < current_function->parameters.depth
6634 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6635 if (entity->kind == ENTITY_VARIABLE) {
6636 /* access of a variable from an outer function */
6637 entity->variable.address_taken = true;
6639 current_function->need_closure = true;
6642 /* check for deprecated functions */
6643 if (warning.deprecated_declarations
6644 && is_declaration(entity)
6645 && entity->declaration.modifiers & DM_DEPRECATED) {
6646 declaration_t *declaration = &entity->declaration;
6648 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6649 "function" : "variable";
6651 if (declaration->deprecated_string != NULL) {
6652 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6653 prefix, entity->base.symbol, &entity->base.source_position,
6654 declaration->deprecated_string);
6656 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6657 entity->base.symbol, &entity->base.source_position);
6661 if (warning.init_self && entity == current_init_decl && !in_type_prop
6662 && entity->kind == ENTITY_VARIABLE) {
6663 current_init_decl = NULL;
6664 warningf(HERE, "variable '%#T' is initialized by itself",
6665 entity->declaration.type, entity->base.symbol);
6672 static bool semantic_cast(expression_t *cast)
6674 expression_t *expression = cast->unary.value;
6675 type_t *orig_dest_type = cast->base.type;
6676 type_t *orig_type_right = expression->base.type;
6677 type_t const *dst_type = skip_typeref(orig_dest_type);
6678 type_t const *src_type = skip_typeref(orig_type_right);
6679 source_position_t const *pos = &cast->base.source_position;
6681 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6682 if (dst_type == type_void)
6685 /* only integer and pointer can be casted to pointer */
6686 if (is_type_pointer(dst_type) &&
6687 !is_type_pointer(src_type) &&
6688 !is_type_integer(src_type) &&
6689 is_type_valid(src_type)) {
6690 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6694 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6695 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6699 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6700 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6704 if (warning.cast_qual &&
6705 is_type_pointer(src_type) &&
6706 is_type_pointer(dst_type)) {
6707 type_t *src = skip_typeref(src_type->pointer.points_to);
6708 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6709 unsigned missing_qualifiers =
6710 src->base.qualifiers & ~dst->base.qualifiers;
6711 if (missing_qualifiers != 0) {
6713 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6714 missing_qualifiers, orig_type_right);
6720 static expression_t *parse_compound_literal(type_t *type)
6722 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6724 parse_initializer_env_t env;
6727 env.must_be_constant = false;
6728 initializer_t *initializer = parse_initializer(&env);
6731 expression->compound_literal.initializer = initializer;
6732 expression->compound_literal.type = type;
6733 expression->base.type = automatic_type_conversion(type);
6739 * Parse a cast expression.
6741 static expression_t *parse_cast(void)
6743 add_anchor_token(')');
6745 source_position_t source_position = token.source_position;
6747 type_t *type = parse_typename();
6749 rem_anchor_token(')');
6752 if (token.type == '{') {
6753 return parse_compound_literal(type);
6756 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6757 cast->base.source_position = source_position;
6759 expression_t *value = parse_sub_expression(PREC_CAST);
6760 cast->base.type = type;
6761 cast->unary.value = value;
6763 if (! semantic_cast(cast)) {
6764 /* TODO: record the error in the AST. else it is impossible to detect it */
6769 return create_invalid_expression();
6773 * Parse a statement expression.
6775 static expression_t *parse_statement_expression(void)
6777 add_anchor_token(')');
6779 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6781 statement_t *statement = parse_compound_statement(true);
6782 expression->statement.statement = statement;
6784 /* find last statement and use its type */
6785 type_t *type = type_void;
6786 const statement_t *stmt = statement->compound.statements;
6788 while (stmt->base.next != NULL)
6789 stmt = stmt->base.next;
6791 if (stmt->kind == STATEMENT_EXPRESSION) {
6792 type = stmt->expression.expression->base.type;
6794 } else if (warning.other) {
6795 warningf(&expression->base.source_position, "empty statement expression ({})");
6797 expression->base.type = type;
6799 rem_anchor_token(')');
6807 * Parse a parenthesized expression.
6809 static expression_t *parse_parenthesized_expression(void)
6813 switch (token.type) {
6815 /* gcc extension: a statement expression */
6816 return parse_statement_expression();
6820 return parse_cast();
6822 if (is_typedef_symbol(token.v.symbol)) {
6823 return parse_cast();
6827 add_anchor_token(')');
6828 expression_t *result = parse_expression();
6829 rem_anchor_token(')');
6836 static expression_t *parse_function_keyword(void)
6840 if (current_function == NULL) {
6841 errorf(HERE, "'__func__' used outside of a function");
6844 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6845 expression->base.type = type_char_ptr;
6846 expression->funcname.kind = FUNCNAME_FUNCTION;
6853 static expression_t *parse_pretty_function_keyword(void)
6855 if (current_function == NULL) {
6856 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6859 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6860 expression->base.type = type_char_ptr;
6861 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6863 eat(T___PRETTY_FUNCTION__);
6868 static expression_t *parse_funcsig_keyword(void)
6870 if (current_function == NULL) {
6871 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6874 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6875 expression->base.type = type_char_ptr;
6876 expression->funcname.kind = FUNCNAME_FUNCSIG;
6883 static expression_t *parse_funcdname_keyword(void)
6885 if (current_function == NULL) {
6886 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6889 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6890 expression->base.type = type_char_ptr;
6891 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6893 eat(T___FUNCDNAME__);
6898 static designator_t *parse_designator(void)
6900 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6901 result->source_position = *HERE;
6903 if (token.type != T_IDENTIFIER) {
6904 parse_error_expected("while parsing member designator",
6905 T_IDENTIFIER, NULL);
6908 result->symbol = token.v.symbol;
6911 designator_t *last_designator = result;
6913 if (token.type == '.') {
6915 if (token.type != T_IDENTIFIER) {
6916 parse_error_expected("while parsing member designator",
6917 T_IDENTIFIER, NULL);
6920 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6921 designator->source_position = *HERE;
6922 designator->symbol = token.v.symbol;
6925 last_designator->next = designator;
6926 last_designator = designator;
6929 if (token.type == '[') {
6931 add_anchor_token(']');
6932 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6933 designator->source_position = *HERE;
6934 designator->array_index = parse_expression();
6935 rem_anchor_token(']');
6937 if (designator->array_index == NULL) {
6941 last_designator->next = designator;
6942 last_designator = designator;
6954 * Parse the __builtin_offsetof() expression.
6956 static expression_t *parse_offsetof(void)
6958 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6959 expression->base.type = type_size_t;
6961 eat(T___builtin_offsetof);
6964 add_anchor_token(',');
6965 type_t *type = parse_typename();
6966 rem_anchor_token(',');
6968 add_anchor_token(')');
6969 designator_t *designator = parse_designator();
6970 rem_anchor_token(')');
6973 expression->offsetofe.type = type;
6974 expression->offsetofe.designator = designator;
6977 memset(&path, 0, sizeof(path));
6978 path.top_type = type;
6979 path.path = NEW_ARR_F(type_path_entry_t, 0);
6981 descend_into_subtype(&path);
6983 if (!walk_designator(&path, designator, true)) {
6984 return create_invalid_expression();
6987 DEL_ARR_F(path.path);
6991 return create_invalid_expression();
6995 * Parses a _builtin_va_start() expression.
6997 static expression_t *parse_va_start(void)
6999 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7001 eat(T___builtin_va_start);
7004 add_anchor_token(',');
7005 expression->va_starte.ap = parse_assignment_expression();
7006 rem_anchor_token(',');
7008 expression_t *const expr = parse_assignment_expression();
7009 if (expr->kind == EXPR_REFERENCE) {
7010 entity_t *const entity = expr->reference.entity;
7011 if (entity->base.parent_scope != ¤t_function->parameters
7012 || entity->base.next != NULL
7013 || entity->kind != ENTITY_VARIABLE) {
7014 errorf(&expr->base.source_position,
7015 "second argument of 'va_start' must be last parameter of the current function");
7017 expression->va_starte.parameter = &entity->variable;
7024 return create_invalid_expression();
7028 * Parses a _builtin_va_arg() expression.
7030 static expression_t *parse_va_arg(void)
7032 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7034 eat(T___builtin_va_arg);
7037 expression->va_arge.ap = parse_assignment_expression();
7039 expression->base.type = parse_typename();
7044 return create_invalid_expression();
7047 static expression_t *parse_builtin_symbol(void)
7049 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7051 symbol_t *symbol = token.v.symbol;
7053 expression->builtin_symbol.symbol = symbol;
7056 type_t *type = get_builtin_symbol_type(symbol);
7057 type = automatic_type_conversion(type);
7059 expression->base.type = type;
7064 * Parses a __builtin_constant() expression.
7066 static expression_t *parse_builtin_constant(void)
7068 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7070 eat(T___builtin_constant_p);
7073 add_anchor_token(')');
7074 expression->builtin_constant.value = parse_assignment_expression();
7075 rem_anchor_token(')');
7077 expression->base.type = type_int;
7081 return create_invalid_expression();
7085 * Parses a __builtin_prefetch() expression.
7087 static expression_t *parse_builtin_prefetch(void)
7089 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7091 eat(T___builtin_prefetch);
7094 add_anchor_token(')');
7095 expression->builtin_prefetch.adr = parse_assignment_expression();
7096 if (token.type == ',') {
7098 expression->builtin_prefetch.rw = parse_assignment_expression();
7100 if (token.type == ',') {
7102 expression->builtin_prefetch.locality = parse_assignment_expression();
7104 rem_anchor_token(')');
7106 expression->base.type = type_void;
7110 return create_invalid_expression();
7114 * Parses a __builtin_is_*() compare expression.
7116 static expression_t *parse_compare_builtin(void)
7118 expression_t *expression;
7120 switch (token.type) {
7121 case T___builtin_isgreater:
7122 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7124 case T___builtin_isgreaterequal:
7125 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7127 case T___builtin_isless:
7128 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7130 case T___builtin_islessequal:
7131 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7133 case T___builtin_islessgreater:
7134 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7136 case T___builtin_isunordered:
7137 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7140 internal_errorf(HERE, "invalid compare builtin found");
7142 expression->base.source_position = *HERE;
7146 expression->binary.left = parse_assignment_expression();
7148 expression->binary.right = parse_assignment_expression();
7151 type_t *const orig_type_left = expression->binary.left->base.type;
7152 type_t *const orig_type_right = expression->binary.right->base.type;
7154 type_t *const type_left = skip_typeref(orig_type_left);
7155 type_t *const type_right = skip_typeref(orig_type_right);
7156 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7157 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7158 type_error_incompatible("invalid operands in comparison",
7159 &expression->base.source_position, orig_type_left, orig_type_right);
7162 semantic_comparison(&expression->binary);
7167 return create_invalid_expression();
7172 * Parses a __builtin_expect() expression.
7174 static expression_t *parse_builtin_expect(void)
7176 expression_t *expression
7177 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7179 eat(T___builtin_expect);
7182 expression->binary.left = parse_assignment_expression();
7184 expression->binary.right = parse_constant_expression();
7187 expression->base.type = expression->binary.left->base.type;
7191 return create_invalid_expression();
7196 * Parses a MS assume() expression.
7198 static expression_t *parse_assume(void)
7200 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7205 add_anchor_token(')');
7206 expression->unary.value = parse_assignment_expression();
7207 rem_anchor_token(')');
7210 expression->base.type = type_void;
7213 return create_invalid_expression();
7217 * Return the declaration for a given label symbol or create a new one.
7219 * @param symbol the symbol of the label
7221 static label_t *get_label(symbol_t *symbol)
7224 assert(current_function != NULL);
7226 label = get_entity(symbol, NAMESPACE_LABEL);
7227 /* if we found a local label, we already created the declaration */
7228 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7229 if (label->base.parent_scope != current_scope) {
7230 assert(label->base.parent_scope->depth < current_scope->depth);
7231 current_function->goto_to_outer = true;
7233 return &label->label;
7236 label = get_entity(symbol, NAMESPACE_LABEL);
7237 /* if we found a label in the same function, then we already created the
7240 && label->base.parent_scope == ¤t_function->parameters) {
7241 return &label->label;
7244 /* otherwise we need to create a new one */
7245 label = allocate_entity_zero(ENTITY_LABEL);
7246 label->base.namespc = NAMESPACE_LABEL;
7247 label->base.symbol = symbol;
7251 return &label->label;
7255 * Parses a GNU && label address expression.
7257 static expression_t *parse_label_address(void)
7259 source_position_t source_position = token.source_position;
7261 if (token.type != T_IDENTIFIER) {
7262 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7265 symbol_t *symbol = token.v.symbol;
7268 label_t *label = get_label(symbol);
7270 label->address_taken = true;
7272 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7273 expression->base.source_position = source_position;
7275 /* label address is threaten as a void pointer */
7276 expression->base.type = type_void_ptr;
7277 expression->label_address.label = label;
7280 return create_invalid_expression();
7284 * Parse a microsoft __noop expression.
7286 static expression_t *parse_noop_expression(void)
7288 /* the result is a (int)0 */
7289 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7290 cnst->base.type = type_int;
7291 cnst->conste.v.int_value = 0;
7292 cnst->conste.is_ms_noop = true;
7296 if (token.type == '(') {
7297 /* parse arguments */
7299 add_anchor_token(')');
7300 add_anchor_token(',');
7302 if (token.type != ')') {
7304 (void)parse_assignment_expression();
7305 if (token.type != ',')
7311 rem_anchor_token(',');
7312 rem_anchor_token(')');
7320 * Parses a primary expression.
7322 static expression_t *parse_primary_expression(void)
7324 switch (token.type) {
7325 case T_false: return parse_bool_const(false);
7326 case T_true: return parse_bool_const(true);
7327 case T_INTEGER: return parse_int_const();
7328 case T_CHARACTER_CONSTANT: return parse_character_constant();
7329 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7330 case T_FLOATINGPOINT: return parse_float_const();
7331 case T_STRING_LITERAL:
7332 case T_WIDE_STRING_LITERAL: return parse_string_const();
7333 case T_IDENTIFIER: return parse_reference();
7334 case T___FUNCTION__:
7335 case T___func__: return parse_function_keyword();
7336 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7337 case T___FUNCSIG__: return parse_funcsig_keyword();
7338 case T___FUNCDNAME__: return parse_funcdname_keyword();
7339 case T___builtin_offsetof: return parse_offsetof();
7340 case T___builtin_va_start: return parse_va_start();
7341 case T___builtin_va_arg: return parse_va_arg();
7342 case T___builtin_expect:
7343 case T___builtin_alloca:
7344 case T___builtin_inf:
7345 case T___builtin_inff:
7346 case T___builtin_infl:
7347 case T___builtin_nan:
7348 case T___builtin_nanf:
7349 case T___builtin_nanl:
7350 case T___builtin_huge_val:
7351 case T___builtin_va_end: return parse_builtin_symbol();
7352 case T___builtin_isgreater:
7353 case T___builtin_isgreaterequal:
7354 case T___builtin_isless:
7355 case T___builtin_islessequal:
7356 case T___builtin_islessgreater:
7357 case T___builtin_isunordered: return parse_compare_builtin();
7358 case T___builtin_constant_p: return parse_builtin_constant();
7359 case T___builtin_prefetch: return parse_builtin_prefetch();
7360 case T__assume: return parse_assume();
7363 return parse_label_address();
7366 case '(': return parse_parenthesized_expression();
7367 case T___noop: return parse_noop_expression();
7370 errorf(HERE, "unexpected token %K, expected an expression", &token);
7371 return create_invalid_expression();
7375 * Check if the expression has the character type and issue a warning then.
7377 static void check_for_char_index_type(const expression_t *expression)
7379 type_t *const type = expression->base.type;
7380 const type_t *const base_type = skip_typeref(type);
7382 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7383 warning.char_subscripts) {
7384 warningf(&expression->base.source_position,
7385 "array subscript has type '%T'", type);
7389 static expression_t *parse_array_expression(expression_t *left)
7391 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7394 add_anchor_token(']');
7396 expression_t *inside = parse_expression();
7398 type_t *const orig_type_left = left->base.type;
7399 type_t *const orig_type_inside = inside->base.type;
7401 type_t *const type_left = skip_typeref(orig_type_left);
7402 type_t *const type_inside = skip_typeref(orig_type_inside);
7404 type_t *return_type;
7405 array_access_expression_t *array_access = &expression->array_access;
7406 if (is_type_pointer(type_left)) {
7407 return_type = type_left->pointer.points_to;
7408 array_access->array_ref = left;
7409 array_access->index = inside;
7410 check_for_char_index_type(inside);
7411 } else if (is_type_pointer(type_inside)) {
7412 return_type = type_inside->pointer.points_to;
7413 array_access->array_ref = inside;
7414 array_access->index = left;
7415 array_access->flipped = true;
7416 check_for_char_index_type(left);
7418 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7420 "array access on object with non-pointer types '%T', '%T'",
7421 orig_type_left, orig_type_inside);
7423 return_type = type_error_type;
7424 array_access->array_ref = left;
7425 array_access->index = inside;
7428 expression->base.type = automatic_type_conversion(return_type);
7430 rem_anchor_token(']');
7436 static expression_t *parse_typeprop(expression_kind_t const kind)
7438 expression_t *tp_expression = allocate_expression_zero(kind);
7439 tp_expression->base.type = type_size_t;
7441 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7443 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7445 /* we only refer to a type property, mark this case */
7446 bool old = in_type_prop;
7447 in_type_prop = true;
7450 expression_t *expression;
7451 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7453 add_anchor_token(')');
7454 orig_type = parse_typename();
7455 rem_anchor_token(')');
7458 if (token.type == '{') {
7459 /* It was not sizeof(type) after all. It is sizeof of an expression
7460 * starting with a compound literal */
7461 expression = parse_compound_literal(orig_type);
7462 goto typeprop_expression;
7465 expression = parse_sub_expression(PREC_UNARY);
7467 typeprop_expression:
7468 tp_expression->typeprop.tp_expression = expression;
7470 orig_type = revert_automatic_type_conversion(expression);
7471 expression->base.type = orig_type;
7474 tp_expression->typeprop.type = orig_type;
7475 type_t const* const type = skip_typeref(orig_type);
7476 char const* const wrong_type =
7477 is_type_incomplete(type) ? "incomplete" :
7478 type->kind == TYPE_FUNCTION ? "function designator" :
7479 type->kind == TYPE_BITFIELD ? "bitfield" :
7481 if (wrong_type != NULL) {
7482 errorf(&tp_expression->base.source_position,
7483 "operand of %s expression must not be of %s type '%T'",
7484 what, wrong_type, orig_type);
7489 return tp_expression;
7492 static expression_t *parse_sizeof(void)
7494 return parse_typeprop(EXPR_SIZEOF);
7497 static expression_t *parse_alignof(void)
7499 return parse_typeprop(EXPR_ALIGNOF);
7502 static expression_t *parse_select_expression(expression_t *compound)
7504 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7505 select->select.compound = compound;
7507 assert(token.type == '.' || token.type == T_MINUSGREATER);
7508 bool is_pointer = (token.type == T_MINUSGREATER);
7511 if (token.type != T_IDENTIFIER) {
7512 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7515 symbol_t *symbol = token.v.symbol;
7518 type_t *const orig_type = compound->base.type;
7519 type_t *const type = skip_typeref(orig_type);
7522 bool saw_error = false;
7523 if (is_type_pointer(type)) {
7526 "request for member '%Y' in something not a struct or union, but '%T'",
7530 type_left = skip_typeref(type->pointer.points_to);
7532 if (is_pointer && is_type_valid(type)) {
7533 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7540 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7541 type_left->kind == TYPE_COMPOUND_UNION) {
7542 compound_t *compound = type_left->compound.compound;
7544 if (!compound->complete) {
7545 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7547 goto create_error_entry;
7550 entry = find_compound_entry(compound, symbol);
7551 if (entry == NULL) {
7552 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7553 goto create_error_entry;
7556 if (is_type_valid(type_left) && !saw_error) {
7558 "request for member '%Y' in something not a struct or union, but '%T'",
7562 return create_invalid_expression();
7565 assert(is_declaration(entry));
7566 select->select.compound_entry = entry;
7568 type_t *entry_type = entry->declaration.type;
7570 = get_qualified_type(entry_type, type_left->base.qualifiers);
7572 /* we always do the auto-type conversions; the & and sizeof parser contains
7573 * code to revert this! */
7574 select->base.type = automatic_type_conversion(res_type);
7576 type_t *skipped = skip_typeref(res_type);
7577 if (skipped->kind == TYPE_BITFIELD) {
7578 select->base.type = skipped->bitfield.base_type;
7584 static void check_call_argument(const function_parameter_t *parameter,
7585 call_argument_t *argument, unsigned pos)
7587 type_t *expected_type = parameter->type;
7588 type_t *expected_type_skip = skip_typeref(expected_type);
7589 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7590 expression_t *arg_expr = argument->expression;
7591 type_t *arg_type = skip_typeref(arg_expr->base.type);
7593 /* handle transparent union gnu extension */
7594 if (is_type_union(expected_type_skip)
7595 && (expected_type_skip->base.modifiers
7596 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7597 compound_t *union_decl = expected_type_skip->compound.compound;
7598 type_t *best_type = NULL;
7599 entity_t *entry = union_decl->members.entities;
7600 for ( ; entry != NULL; entry = entry->base.next) {
7601 assert(is_declaration(entry));
7602 type_t *decl_type = entry->declaration.type;
7603 error = semantic_assign(decl_type, arg_expr);
7604 if (error == ASSIGN_ERROR_INCOMPATIBLE
7605 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7608 if (error == ASSIGN_SUCCESS) {
7609 best_type = decl_type;
7610 } else if (best_type == NULL) {
7611 best_type = decl_type;
7615 if (best_type != NULL) {
7616 expected_type = best_type;
7620 error = semantic_assign(expected_type, arg_expr);
7621 argument->expression = create_implicit_cast(argument->expression,
7624 if (error != ASSIGN_SUCCESS) {
7625 /* report exact scope in error messages (like "in argument 3") */
7627 snprintf(buf, sizeof(buf), "call argument %u", pos);
7628 report_assign_error(error, expected_type, arg_expr, buf,
7629 &arg_expr->base.source_position);
7630 } else if (warning.traditional || warning.conversion) {
7631 type_t *const promoted_type = get_default_promoted_type(arg_type);
7632 if (!types_compatible(expected_type_skip, promoted_type) &&
7633 !types_compatible(expected_type_skip, type_void_ptr) &&
7634 !types_compatible(type_void_ptr, promoted_type)) {
7635 /* Deliberately show the skipped types in this warning */
7636 warningf(&arg_expr->base.source_position,
7637 "passing call argument %u as '%T' rather than '%T' due to prototype",
7638 pos, expected_type_skip, promoted_type);
7644 * Parse a call expression, ie. expression '( ... )'.
7646 * @param expression the function address
7648 static expression_t *parse_call_expression(expression_t *expression)
7650 expression_t *result = allocate_expression_zero(EXPR_CALL);
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->condition = expression;
7762 add_anchor_token(':');
7765 type_t *const condition_type_orig = expression->base.type;
7766 type_t *const condition_type = skip_typeref(condition_type_orig);
7767 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7768 type_error("expected a scalar type in conditional condition",
7769 &expression->base.source_position, condition_type_orig);
7772 expression_t *true_expression = expression;
7773 bool gnu_cond = false;
7774 if (GNU_MODE && token.type == ':') {
7777 true_expression = parse_expression();
7779 rem_anchor_token(':');
7781 expression_t *false_expression =
7782 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7784 type_t *const orig_true_type = true_expression->base.type;
7785 type_t *const orig_false_type = false_expression->base.type;
7786 type_t *const true_type = skip_typeref(orig_true_type);
7787 type_t *const false_type = skip_typeref(orig_false_type);
7790 type_t *result_type;
7791 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7792 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7793 /* ISO/IEC 14882:1998(E) §5.16:2 */
7794 if (true_expression->kind == EXPR_UNARY_THROW) {
7795 result_type = false_type;
7796 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7797 result_type = true_type;
7799 if (warning.other && (
7800 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7801 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7803 warningf(&conditional->base.source_position,
7804 "ISO C forbids conditional expression with only one void side");
7806 result_type = type_void;
7808 } else if (is_type_arithmetic(true_type)
7809 && is_type_arithmetic(false_type)) {
7810 result_type = semantic_arithmetic(true_type, false_type);
7812 true_expression = create_implicit_cast(true_expression, result_type);
7813 false_expression = create_implicit_cast(false_expression, result_type);
7815 conditional->true_expression = true_expression;
7816 conditional->false_expression = false_expression;
7817 conditional->base.type = result_type;
7818 } else if (same_compound_type(true_type, false_type)) {
7819 /* just take 1 of the 2 types */
7820 result_type = true_type;
7821 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7822 type_t *pointer_type;
7824 expression_t *other_expression;
7825 if (is_type_pointer(true_type) &&
7826 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7827 pointer_type = true_type;
7828 other_type = false_type;
7829 other_expression = false_expression;
7831 pointer_type = false_type;
7832 other_type = true_type;
7833 other_expression = true_expression;
7836 if (is_null_pointer_constant(other_expression)) {
7837 result_type = pointer_type;
7838 } else if (is_type_pointer(other_type)) {
7839 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7840 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7843 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7844 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7846 } else if (types_compatible(get_unqualified_type(to1),
7847 get_unqualified_type(to2))) {
7850 if (warning.other) {
7851 warningf(&conditional->base.source_position,
7852 "pointer types '%T' and '%T' in conditional expression are incompatible",
7853 true_type, false_type);
7858 type_t *const type =
7859 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7860 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7861 } else if (is_type_integer(other_type)) {
7862 if (warning.other) {
7863 warningf(&conditional->base.source_position,
7864 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7866 result_type = pointer_type;
7868 if (is_type_valid(other_type)) {
7869 type_error_incompatible("while parsing conditional",
7870 &expression->base.source_position, true_type, false_type);
7872 result_type = type_error_type;
7875 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7876 type_error_incompatible("while parsing conditional",
7877 &conditional->base.source_position, true_type,
7880 result_type = type_error_type;
7883 conditional->true_expression
7884 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7885 conditional->false_expression
7886 = create_implicit_cast(false_expression, result_type);
7887 conditional->base.type = result_type;
7890 return create_invalid_expression();
7894 * Parse an extension expression.
7896 static expression_t *parse_extension(void)
7898 eat(T___extension__);
7900 bool old_gcc_extension = in_gcc_extension;
7901 in_gcc_extension = true;
7902 expression_t *expression = parse_sub_expression(PREC_UNARY);
7903 in_gcc_extension = old_gcc_extension;
7908 * Parse a __builtin_classify_type() expression.
7910 static expression_t *parse_builtin_classify_type(void)
7912 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7913 result->base.type = type_int;
7915 eat(T___builtin_classify_type);
7918 add_anchor_token(')');
7919 expression_t *expression = parse_expression();
7920 rem_anchor_token(')');
7922 result->classify_type.type_expression = expression;
7926 return create_invalid_expression();
7930 * Parse a delete expression
7931 * ISO/IEC 14882:1998(E) §5.3.5
7933 static expression_t *parse_delete(void)
7935 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7936 result->base.type = type_void;
7940 if (token.type == '[') {
7942 result->kind = EXPR_UNARY_DELETE_ARRAY;
7947 expression_t *const value = parse_sub_expression(PREC_CAST);
7948 result->unary.value = value;
7950 type_t *const type = skip_typeref(value->base.type);
7951 if (!is_type_pointer(type)) {
7952 errorf(&value->base.source_position,
7953 "operand of delete must have pointer type");
7954 } else if (warning.other &&
7955 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7956 warningf(&value->base.source_position,
7957 "deleting 'void*' is undefined");
7964 * Parse a throw expression
7965 * ISO/IEC 14882:1998(E) §15:1
7967 static expression_t *parse_throw(void)
7969 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7970 result->base.type = type_void;
7974 expression_t *value = NULL;
7975 switch (token.type) {
7977 value = parse_assignment_expression();
7978 /* ISO/IEC 14882:1998(E) §15.1:3 */
7979 type_t *const orig_type = value->base.type;
7980 type_t *const type = skip_typeref(orig_type);
7981 if (is_type_incomplete(type)) {
7982 errorf(&value->base.source_position,
7983 "cannot throw object of incomplete type '%T'", orig_type);
7984 } else if (is_type_pointer(type)) {
7985 type_t *const points_to = skip_typeref(type->pointer.points_to);
7986 if (is_type_incomplete(points_to) &&
7987 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7988 errorf(&value->base.source_position,
7989 "cannot throw pointer to incomplete type '%T'", orig_type);
7997 result->unary.value = value;
8002 static bool check_pointer_arithmetic(const source_position_t *source_position,
8003 type_t *pointer_type,
8004 type_t *orig_pointer_type)
8006 type_t *points_to = pointer_type->pointer.points_to;
8007 points_to = skip_typeref(points_to);
8009 if (is_type_incomplete(points_to)) {
8010 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8011 errorf(source_position,
8012 "arithmetic with pointer to incomplete type '%T' not allowed",
8015 } else if (warning.pointer_arith) {
8016 warningf(source_position,
8017 "pointer of type '%T' used in arithmetic",
8020 } else if (is_type_function(points_to)) {
8022 errorf(source_position,
8023 "arithmetic with pointer to function type '%T' not allowed",
8026 } else if (warning.pointer_arith) {
8027 warningf(source_position,
8028 "pointer to a function '%T' used in arithmetic",
8035 static bool is_lvalue(const expression_t *expression)
8037 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8038 switch (expression->kind) {
8039 case EXPR_REFERENCE:
8040 case EXPR_ARRAY_ACCESS:
8042 case EXPR_UNARY_DEREFERENCE:
8046 /* Claim it is an lvalue, if the type is invalid. There was a parse
8047 * error before, which maybe prevented properly recognizing it as
8049 return !is_type_valid(skip_typeref(expression->base.type));
8053 static void semantic_incdec(unary_expression_t *expression)
8055 type_t *const orig_type = expression->value->base.type;
8056 type_t *const type = skip_typeref(orig_type);
8057 if (is_type_pointer(type)) {
8058 if (!check_pointer_arithmetic(&expression->base.source_position,
8062 } else if (!is_type_real(type) && is_type_valid(type)) {
8063 /* TODO: improve error message */
8064 errorf(&expression->base.source_position,
8065 "operation needs an arithmetic or pointer type");
8068 if (!is_lvalue(expression->value)) {
8069 /* TODO: improve error message */
8070 errorf(&expression->base.source_position, "lvalue required as operand");
8072 expression->base.type = orig_type;
8075 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8077 type_t *const orig_type = expression->value->base.type;
8078 type_t *const type = skip_typeref(orig_type);
8079 if (!is_type_arithmetic(type)) {
8080 if (is_type_valid(type)) {
8081 /* TODO: improve error message */
8082 errorf(&expression->base.source_position,
8083 "operation needs an arithmetic type");
8088 expression->base.type = orig_type;
8091 static void semantic_unexpr_plus(unary_expression_t *expression)
8093 semantic_unexpr_arithmetic(expression);
8094 if (warning.traditional)
8095 warningf(&expression->base.source_position,
8096 "traditional C rejects the unary plus operator");
8099 static expression_t const *get_reference_address(expression_t const *expr)
8101 bool regular_take_address = true;
8103 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8104 expr = expr->unary.value;
8106 regular_take_address = false;
8109 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8112 expr = expr->unary.value;
8115 if (expr->kind != EXPR_REFERENCE)
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 &&
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 = c_mode & _CXX ? type_bool : 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); \
8250 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8252 sfunc(&unary_expression->unary); \
8254 return unary_expression; \
8257 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8258 semantic_unexpr_arithmetic)
8259 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8260 semantic_unexpr_plus)
8261 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8263 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8264 semantic_dereference)
8265 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8267 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8268 semantic_unexpr_integer)
8269 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8271 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8274 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8276 static expression_t *parse_##unexpression_type(expression_t *left) \
8278 expression_t *unary_expression \
8279 = allocate_expression_zero(unexpression_type); \
8281 unary_expression->unary.value = left; \
8283 sfunc(&unary_expression->unary); \
8285 return unary_expression; \
8288 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8289 EXPR_UNARY_POSTFIX_INCREMENT,
8291 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8292 EXPR_UNARY_POSTFIX_DECREMENT,
8295 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8297 /* TODO: handle complex + imaginary types */
8299 type_left = get_unqualified_type(type_left);
8300 type_right = get_unqualified_type(type_right);
8302 /* § 6.3.1.8 Usual arithmetic conversions */
8303 if (type_left == type_long_double || type_right == type_long_double) {
8304 return type_long_double;
8305 } else if (type_left == type_double || type_right == type_double) {
8307 } else if (type_left == type_float || type_right == type_float) {
8311 type_left = promote_integer(type_left);
8312 type_right = promote_integer(type_right);
8314 if (type_left == type_right)
8317 bool const signed_left = is_type_signed(type_left);
8318 bool const signed_right = is_type_signed(type_right);
8319 int const rank_left = get_rank(type_left);
8320 int const rank_right = get_rank(type_right);
8322 if (signed_left == signed_right)
8323 return rank_left >= rank_right ? type_left : type_right;
8332 u_rank = rank_right;
8333 u_type = type_right;
8335 s_rank = rank_right;
8336 s_type = type_right;
8341 if (u_rank >= s_rank)
8344 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8346 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8347 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8351 case ATOMIC_TYPE_INT: return type_unsigned_int;
8352 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8353 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8355 default: panic("invalid atomic type");
8360 * Check the semantic restrictions for a binary expression.
8362 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8364 expression_t *const left = expression->left;
8365 expression_t *const right = expression->right;
8366 type_t *const orig_type_left = left->base.type;
8367 type_t *const orig_type_right = right->base.type;
8368 type_t *const type_left = skip_typeref(orig_type_left);
8369 type_t *const type_right = skip_typeref(orig_type_right);
8371 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8372 /* TODO: improve error message */
8373 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8374 errorf(&expression->base.source_position,
8375 "operation needs arithmetic types");
8380 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8381 expression->left = create_implicit_cast(left, arithmetic_type);
8382 expression->right = create_implicit_cast(right, arithmetic_type);
8383 expression->base.type = arithmetic_type;
8386 static void warn_div_by_zero(binary_expression_t const *const expression)
8388 if (!warning.div_by_zero ||
8389 !is_type_integer(expression->base.type))
8392 expression_t const *const right = expression->right;
8393 /* The type of the right operand can be different for /= */
8394 if (is_type_integer(right->base.type) &&
8395 is_constant_expression(right) &&
8396 fold_constant(right) == 0) {
8397 warningf(&expression->base.source_position, "division by zero");
8402 * Check the semantic restrictions for a div/mod expression.
8404 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8405 semantic_binexpr_arithmetic(expression);
8406 warn_div_by_zero(expression);
8409 static void semantic_shift_op(binary_expression_t *expression)
8411 expression_t *const left = expression->left;
8412 expression_t *const right = expression->right;
8413 type_t *const orig_type_left = left->base.type;
8414 type_t *const orig_type_right = right->base.type;
8415 type_t * type_left = skip_typeref(orig_type_left);
8416 type_t * type_right = skip_typeref(orig_type_right);
8418 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8419 /* TODO: improve error message */
8420 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8421 errorf(&expression->base.source_position,
8422 "operands of shift operation must have integer types");
8427 type_left = promote_integer(type_left);
8428 type_right = promote_integer(type_right);
8430 expression->left = create_implicit_cast(left, type_left);
8431 expression->right = create_implicit_cast(right, type_right);
8432 expression->base.type = type_left;
8435 static void semantic_add(binary_expression_t *expression)
8437 expression_t *const left = expression->left;
8438 expression_t *const right = expression->right;
8439 type_t *const orig_type_left = left->base.type;
8440 type_t *const orig_type_right = right->base.type;
8441 type_t *const type_left = skip_typeref(orig_type_left);
8442 type_t *const type_right = skip_typeref(orig_type_right);
8445 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8446 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8447 expression->left = create_implicit_cast(left, arithmetic_type);
8448 expression->right = create_implicit_cast(right, arithmetic_type);
8449 expression->base.type = arithmetic_type;
8451 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8452 check_pointer_arithmetic(&expression->base.source_position,
8453 type_left, orig_type_left);
8454 expression->base.type = type_left;
8455 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8456 check_pointer_arithmetic(&expression->base.source_position,
8457 type_right, orig_type_right);
8458 expression->base.type = type_right;
8459 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8460 errorf(&expression->base.source_position,
8461 "invalid operands to binary + ('%T', '%T')",
8462 orig_type_left, orig_type_right);
8466 static void semantic_sub(binary_expression_t *expression)
8468 expression_t *const left = expression->left;
8469 expression_t *const right = expression->right;
8470 type_t *const orig_type_left = left->base.type;
8471 type_t *const orig_type_right = right->base.type;
8472 type_t *const type_left = skip_typeref(orig_type_left);
8473 type_t *const type_right = skip_typeref(orig_type_right);
8474 source_position_t const *const pos = &expression->base.source_position;
8477 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8478 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8479 expression->left = create_implicit_cast(left, arithmetic_type);
8480 expression->right = create_implicit_cast(right, arithmetic_type);
8481 expression->base.type = arithmetic_type;
8483 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8484 check_pointer_arithmetic(&expression->base.source_position,
8485 type_left, orig_type_left);
8486 expression->base.type = type_left;
8487 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8488 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8489 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8490 if (!types_compatible(unqual_left, unqual_right)) {
8492 "subtracting pointers to incompatible types '%T' and '%T'",
8493 orig_type_left, orig_type_right);
8494 } else if (!is_type_object(unqual_left)) {
8495 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8496 errorf(pos, "subtracting pointers to non-object types '%T'",
8498 } else if (warning.other) {
8499 warningf(pos, "subtracting pointers to void");
8502 expression->base.type = type_ptrdiff_t;
8503 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8504 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8505 orig_type_left, orig_type_right);
8509 static void warn_string_literal_address(expression_t const* expr)
8511 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8512 expr = expr->unary.value;
8513 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8515 expr = expr->unary.value;
8518 if (expr->kind == EXPR_STRING_LITERAL ||
8519 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8520 warningf(&expr->base.source_position,
8521 "comparison with string literal results in unspecified behaviour");
8526 * Check the semantics of comparison expressions.
8528 * @param expression The expression to check.
8530 static void semantic_comparison(binary_expression_t *expression)
8532 expression_t *left = expression->left;
8533 expression_t *right = expression->right;
8535 if (warning.address) {
8536 warn_string_literal_address(left);
8537 warn_string_literal_address(right);
8539 expression_t const* const func_left = get_reference_address(left);
8540 if (func_left != NULL && is_null_pointer_constant(right)) {
8541 warningf(&expression->base.source_position,
8542 "the address of '%Y' will never be NULL",
8543 func_left->reference.entity->base.symbol);
8546 expression_t const* const func_right = get_reference_address(right);
8547 if (func_right != NULL && is_null_pointer_constant(right)) {
8548 warningf(&expression->base.source_position,
8549 "the address of '%Y' will never be NULL",
8550 func_right->reference.entity->base.symbol);
8554 type_t *orig_type_left = left->base.type;
8555 type_t *orig_type_right = right->base.type;
8556 type_t *type_left = skip_typeref(orig_type_left);
8557 type_t *type_right = skip_typeref(orig_type_right);
8559 /* TODO non-arithmetic types */
8560 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8561 /* test for signed vs unsigned compares */
8562 if (warning.sign_compare &&
8563 (expression->base.kind != EXPR_BINARY_EQUAL &&
8564 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8565 (is_type_signed(type_left) != is_type_signed(type_right))) {
8567 /* check if 1 of the operands is a constant, in this case we just
8568 * check wether we can safely represent the resulting constant in
8569 * the type of the other operand. */
8570 expression_t *const_expr = NULL;
8571 expression_t *other_expr = NULL;
8573 if (is_constant_expression(left)) {
8576 } else if (is_constant_expression(right)) {
8581 if (const_expr != NULL) {
8582 type_t *other_type = skip_typeref(other_expr->base.type);
8583 long val = fold_constant(const_expr);
8584 /* TODO: check if val can be represented by other_type */
8588 warningf(&expression->base.source_position,
8589 "comparison between signed and unsigned");
8591 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8592 expression->left = create_implicit_cast(left, arithmetic_type);
8593 expression->right = create_implicit_cast(right, arithmetic_type);
8594 expression->base.type = arithmetic_type;
8595 if (warning.float_equal &&
8596 (expression->base.kind == EXPR_BINARY_EQUAL ||
8597 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8598 is_type_float(arithmetic_type)) {
8599 warningf(&expression->base.source_position,
8600 "comparing floating point with == or != is unsafe");
8602 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8603 /* TODO check compatibility */
8604 } else if (is_type_pointer(type_left)) {
8605 expression->right = create_implicit_cast(right, type_left);
8606 } else if (is_type_pointer(type_right)) {
8607 expression->left = create_implicit_cast(left, type_right);
8608 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8609 type_error_incompatible("invalid operands in comparison",
8610 &expression->base.source_position,
8611 type_left, type_right);
8613 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8617 * Checks if a compound type has constant fields.
8619 static bool has_const_fields(const compound_type_t *type)
8621 compound_t *compound = type->compound;
8622 entity_t *entry = compound->members.entities;
8624 for (; entry != NULL; entry = entry->base.next) {
8625 if (!is_declaration(entry))
8628 const type_t *decl_type = skip_typeref(entry->declaration.type);
8629 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8636 static bool is_valid_assignment_lhs(expression_t const* const left)
8638 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8639 type_t *const type_left = skip_typeref(orig_type_left);
8641 if (!is_lvalue(left)) {
8642 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8647 if (is_type_array(type_left)) {
8648 errorf(HERE, "cannot assign to arrays ('%E')", left);
8651 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8652 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8656 if (is_type_incomplete(type_left)) {
8657 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8658 left, orig_type_left);
8661 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8662 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8663 left, orig_type_left);
8670 static void semantic_arithmetic_assign(binary_expression_t *expression)
8672 expression_t *left = expression->left;
8673 expression_t *right = expression->right;
8674 type_t *orig_type_left = left->base.type;
8675 type_t *orig_type_right = right->base.type;
8677 if (!is_valid_assignment_lhs(left))
8680 type_t *type_left = skip_typeref(orig_type_left);
8681 type_t *type_right = skip_typeref(orig_type_right);
8683 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8684 /* TODO: improve error message */
8685 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8686 errorf(&expression->base.source_position,
8687 "operation needs arithmetic types");
8692 /* combined instructions are tricky. We can't create an implicit cast on
8693 * the left side, because we need the uncasted form for the store.
8694 * The ast2firm pass has to know that left_type must be right_type
8695 * for the arithmetic operation and create a cast by itself */
8696 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8697 expression->right = create_implicit_cast(right, arithmetic_type);
8698 expression->base.type = type_left;
8701 static void semantic_divmod_assign(binary_expression_t *expression)
8703 semantic_arithmetic_assign(expression);
8704 warn_div_by_zero(expression);
8707 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8709 expression_t *const left = expression->left;
8710 expression_t *const right = expression->right;
8711 type_t *const orig_type_left = left->base.type;
8712 type_t *const orig_type_right = right->base.type;
8713 type_t *const type_left = skip_typeref(orig_type_left);
8714 type_t *const type_right = skip_typeref(orig_type_right);
8716 if (!is_valid_assignment_lhs(left))
8719 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8720 /* combined instructions are tricky. We can't create an implicit cast on
8721 * the left side, because we need the uncasted form for the store.
8722 * The ast2firm pass has to know that left_type must be right_type
8723 * for the arithmetic operation and create a cast by itself */
8724 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8725 expression->right = create_implicit_cast(right, arithmetic_type);
8726 expression->base.type = type_left;
8727 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8728 check_pointer_arithmetic(&expression->base.source_position,
8729 type_left, orig_type_left);
8730 expression->base.type = type_left;
8731 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8732 errorf(&expression->base.source_position,
8733 "incompatible types '%T' and '%T' in assignment",
8734 orig_type_left, orig_type_right);
8739 * Check the semantic restrictions of a logical expression.
8741 static void semantic_logical_op(binary_expression_t *expression)
8743 expression_t *const left = expression->left;
8744 expression_t *const right = expression->right;
8745 type_t *const orig_type_left = left->base.type;
8746 type_t *const orig_type_right = right->base.type;
8747 type_t *const type_left = skip_typeref(orig_type_left);
8748 type_t *const type_right = skip_typeref(orig_type_right);
8750 warn_function_address_as_bool(left);
8751 warn_function_address_as_bool(right);
8753 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8754 /* TODO: improve error message */
8755 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8756 errorf(&expression->base.source_position,
8757 "operation needs scalar types");
8762 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8766 * Check the semantic restrictions of a binary assign expression.
8768 static void semantic_binexpr_assign(binary_expression_t *expression)
8770 expression_t *left = expression->left;
8771 type_t *orig_type_left = left->base.type;
8773 if (!is_valid_assignment_lhs(left))
8776 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8777 report_assign_error(error, orig_type_left, expression->right,
8778 "assignment", &left->base.source_position);
8779 expression->right = create_implicit_cast(expression->right, orig_type_left);
8780 expression->base.type = orig_type_left;
8784 * Determine if the outermost operation (or parts thereof) of the given
8785 * expression has no effect in order to generate a warning about this fact.
8786 * Therefore in some cases this only examines some of the operands of the
8787 * expression (see comments in the function and examples below).
8789 * f() + 23; // warning, because + has no effect
8790 * x || f(); // no warning, because x controls execution of f()
8791 * x ? y : f(); // warning, because y has no effect
8792 * (void)x; // no warning to be able to suppress the warning
8793 * This function can NOT be used for an "expression has definitely no effect"-
8795 static bool expression_has_effect(const expression_t *const expr)
8797 switch (expr->kind) {
8798 case EXPR_UNKNOWN: break;
8799 case EXPR_INVALID: return true; /* do NOT warn */
8800 case EXPR_REFERENCE: return false;
8801 case EXPR_REFERENCE_ENUM_VALUE: return false;
8802 /* suppress the warning for microsoft __noop operations */
8803 case EXPR_CONST: return expr->conste.is_ms_noop;
8804 case EXPR_CHARACTER_CONSTANT: return false;
8805 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8806 case EXPR_STRING_LITERAL: return false;
8807 case EXPR_WIDE_STRING_LITERAL: return false;
8808 case EXPR_LABEL_ADDRESS: return false;
8811 const call_expression_t *const call = &expr->call;
8812 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8815 switch (call->function->builtin_symbol.symbol->ID) {
8816 case T___builtin_va_end: return true;
8817 default: return false;
8821 /* Generate the warning if either the left or right hand side of a
8822 * conditional expression has no effect */
8823 case EXPR_CONDITIONAL: {
8824 const conditional_expression_t *const cond = &expr->conditional;
8826 expression_has_effect(cond->true_expression) &&
8827 expression_has_effect(cond->false_expression);
8830 case EXPR_SELECT: return false;
8831 case EXPR_ARRAY_ACCESS: return false;
8832 case EXPR_SIZEOF: return false;
8833 case EXPR_CLASSIFY_TYPE: return false;
8834 case EXPR_ALIGNOF: return false;
8836 case EXPR_FUNCNAME: return false;
8837 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8838 case EXPR_BUILTIN_CONSTANT_P: return false;
8839 case EXPR_BUILTIN_PREFETCH: return true;
8840 case EXPR_OFFSETOF: return false;
8841 case EXPR_VA_START: return true;
8842 case EXPR_VA_ARG: return true;
8843 case EXPR_STATEMENT: return true; // TODO
8844 case EXPR_COMPOUND_LITERAL: return false;
8846 case EXPR_UNARY_NEGATE: return false;
8847 case EXPR_UNARY_PLUS: return false;
8848 case EXPR_UNARY_BITWISE_NEGATE: return false;
8849 case EXPR_UNARY_NOT: return false;
8850 case EXPR_UNARY_DEREFERENCE: return false;
8851 case EXPR_UNARY_TAKE_ADDRESS: return false;
8852 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8853 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8854 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8855 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8857 /* Treat void casts as if they have an effect in order to being able to
8858 * suppress the warning */
8859 case EXPR_UNARY_CAST: {
8860 type_t *const type = skip_typeref(expr->base.type);
8861 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8864 case EXPR_UNARY_CAST_IMPLICIT: return true;
8865 case EXPR_UNARY_ASSUME: return true;
8866 case EXPR_UNARY_DELETE: return true;
8867 case EXPR_UNARY_DELETE_ARRAY: return true;
8868 case EXPR_UNARY_THROW: return true;
8870 case EXPR_BINARY_ADD: return false;
8871 case EXPR_BINARY_SUB: return false;
8872 case EXPR_BINARY_MUL: return false;
8873 case EXPR_BINARY_DIV: return false;
8874 case EXPR_BINARY_MOD: return false;
8875 case EXPR_BINARY_EQUAL: return false;
8876 case EXPR_BINARY_NOTEQUAL: return false;
8877 case EXPR_BINARY_LESS: return false;
8878 case EXPR_BINARY_LESSEQUAL: return false;
8879 case EXPR_BINARY_GREATER: return false;
8880 case EXPR_BINARY_GREATEREQUAL: return false;
8881 case EXPR_BINARY_BITWISE_AND: return false;
8882 case EXPR_BINARY_BITWISE_OR: return false;
8883 case EXPR_BINARY_BITWISE_XOR: return false;
8884 case EXPR_BINARY_SHIFTLEFT: return false;
8885 case EXPR_BINARY_SHIFTRIGHT: return false;
8886 case EXPR_BINARY_ASSIGN: return true;
8887 case EXPR_BINARY_MUL_ASSIGN: return true;
8888 case EXPR_BINARY_DIV_ASSIGN: return true;
8889 case EXPR_BINARY_MOD_ASSIGN: return true;
8890 case EXPR_BINARY_ADD_ASSIGN: return true;
8891 case EXPR_BINARY_SUB_ASSIGN: return true;
8892 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8893 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8894 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8895 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8896 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8898 /* Only examine the right hand side of && and ||, because the left hand
8899 * side already has the effect of controlling the execution of the right
8901 case EXPR_BINARY_LOGICAL_AND:
8902 case EXPR_BINARY_LOGICAL_OR:
8903 /* Only examine the right hand side of a comma expression, because the left
8904 * hand side has a separate warning */
8905 case EXPR_BINARY_COMMA:
8906 return expression_has_effect(expr->binary.right);
8908 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8909 case EXPR_BINARY_ISGREATER: return false;
8910 case EXPR_BINARY_ISGREATEREQUAL: return false;
8911 case EXPR_BINARY_ISLESS: return false;
8912 case EXPR_BINARY_ISLESSEQUAL: return false;
8913 case EXPR_BINARY_ISLESSGREATER: return false;
8914 case EXPR_BINARY_ISUNORDERED: return false;
8917 internal_errorf(HERE, "unexpected expression");
8920 static void semantic_comma(binary_expression_t *expression)
8922 if (warning.unused_value) {
8923 const expression_t *const left = expression->left;
8924 if (!expression_has_effect(left)) {
8925 warningf(&left->base.source_position,
8926 "left-hand operand of comma expression has no effect");
8929 expression->base.type = expression->right->base.type;
8933 * @param prec_r precedence of the right operand
8935 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8936 static expression_t *parse_##binexpression_type(expression_t *left) \
8938 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8939 binexpr->binary.left = left; \
8942 expression_t *right = parse_sub_expression(prec_r); \
8944 binexpr->binary.right = right; \
8945 sfunc(&binexpr->binary); \
8950 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8951 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8952 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8953 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8954 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8955 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8956 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8957 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8958 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8959 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8960 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8961 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8962 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8963 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8964 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8965 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8966 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8967 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8968 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8969 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8970 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8971 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8972 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8973 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8974 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8975 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8976 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8977 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8978 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8979 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8982 static expression_t *parse_sub_expression(precedence_t precedence)
8984 if (token.type < 0) {
8985 return expected_expression_error();
8988 expression_parser_function_t *parser
8989 = &expression_parsers[token.type];
8990 source_position_t source_position = token.source_position;
8993 if (parser->parser != NULL) {
8994 left = parser->parser();
8996 left = parse_primary_expression();
8998 assert(left != NULL);
8999 left->base.source_position = source_position;
9002 if (token.type < 0) {
9003 return expected_expression_error();
9006 parser = &expression_parsers[token.type];
9007 if (parser->infix_parser == NULL)
9009 if (parser->infix_precedence < precedence)
9012 left = parser->infix_parser(left);
9014 assert(left != NULL);
9015 assert(left->kind != EXPR_UNKNOWN);
9016 left->base.source_position = source_position;
9023 * Parse an expression.
9025 static expression_t *parse_expression(void)
9027 return parse_sub_expression(PREC_EXPRESSION);
9031 * Register a parser for a prefix-like operator.
9033 * @param parser the parser function
9034 * @param token_type the token type of the prefix token
9036 static void register_expression_parser(parse_expression_function parser,
9039 expression_parser_function_t *entry = &expression_parsers[token_type];
9041 if (entry->parser != NULL) {
9042 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9043 panic("trying to register multiple expression parsers for a token");
9045 entry->parser = parser;
9049 * Register a parser for an infix operator with given precedence.
9051 * @param parser the parser function
9052 * @param token_type the token type of the infix operator
9053 * @param precedence the precedence of the operator
9055 static void register_infix_parser(parse_expression_infix_function parser,
9056 int token_type, unsigned precedence)
9058 expression_parser_function_t *entry = &expression_parsers[token_type];
9060 if (entry->infix_parser != NULL) {
9061 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9062 panic("trying to register multiple infix expression parsers for a "
9065 entry->infix_parser = parser;
9066 entry->infix_precedence = precedence;
9070 * Initialize the expression parsers.
9072 static void init_expression_parsers(void)
9074 memset(&expression_parsers, 0, sizeof(expression_parsers));
9076 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9077 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9078 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9079 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9080 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9081 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9082 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9083 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9084 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9085 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9086 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9087 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9088 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9089 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9090 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9091 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9092 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9093 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9094 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9095 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9096 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9097 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9098 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9099 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9100 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9101 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9102 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9103 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9104 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9105 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9106 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9107 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9108 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9109 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9110 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9111 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9112 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9114 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9115 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9116 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9117 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9118 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9119 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9120 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9121 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9122 register_expression_parser(parse_sizeof, T_sizeof);
9123 register_expression_parser(parse_alignof, T___alignof__);
9124 register_expression_parser(parse_extension, T___extension__);
9125 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9126 register_expression_parser(parse_delete, T_delete);
9127 register_expression_parser(parse_throw, T_throw);
9131 * Parse a asm statement arguments specification.
9133 static asm_argument_t *parse_asm_arguments(bool is_out)
9135 asm_argument_t *result = NULL;
9136 asm_argument_t *last = NULL;
9138 while (token.type == T_STRING_LITERAL || token.type == '[') {
9139 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9140 memset(argument, 0, sizeof(argument[0]));
9142 if (token.type == '[') {
9144 if (token.type != T_IDENTIFIER) {
9145 parse_error_expected("while parsing asm argument",
9146 T_IDENTIFIER, NULL);
9149 argument->symbol = token.v.symbol;
9154 argument->constraints = parse_string_literals();
9156 add_anchor_token(')');
9157 expression_t *expression = parse_expression();
9158 rem_anchor_token(')');
9160 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9161 * change size or type representation (e.g. int -> long is ok, but
9162 * int -> float is not) */
9163 if (expression->kind == EXPR_UNARY_CAST) {
9164 type_t *const type = expression->base.type;
9165 type_kind_t const kind = type->kind;
9166 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9169 if (kind == TYPE_ATOMIC) {
9170 atomic_type_kind_t const akind = type->atomic.akind;
9171 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9172 size = get_atomic_type_size(akind);
9174 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9175 size = get_atomic_type_size(get_intptr_kind());
9179 expression_t *const value = expression->unary.value;
9180 type_t *const value_type = value->base.type;
9181 type_kind_t const value_kind = value_type->kind;
9183 unsigned value_flags;
9184 unsigned value_size;
9185 if (value_kind == TYPE_ATOMIC) {
9186 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9187 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9188 value_size = get_atomic_type_size(value_akind);
9189 } else if (value_kind == TYPE_POINTER) {
9190 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9191 value_size = get_atomic_type_size(get_intptr_kind());
9196 if (value_flags != flags || value_size != size)
9200 } while (expression->kind == EXPR_UNARY_CAST);
9204 if (!is_lvalue(expression)) {
9205 errorf(&expression->base.source_position,
9206 "asm output argument is not an lvalue");
9209 if (argument->constraints.begin[0] == '+')
9210 mark_vars_read(expression, NULL);
9212 mark_vars_read(expression, NULL);
9214 argument->expression = expression;
9217 set_address_taken(expression, true);
9220 last->next = argument;
9226 if (token.type != ',')
9237 * Parse a asm statement clobber specification.
9239 static asm_clobber_t *parse_asm_clobbers(void)
9241 asm_clobber_t *result = NULL;
9242 asm_clobber_t *last = NULL;
9244 while(token.type == T_STRING_LITERAL) {
9245 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9246 clobber->clobber = parse_string_literals();
9249 last->next = clobber;
9255 if (token.type != ',')
9264 * Parse an asm statement.
9266 static statement_t *parse_asm_statement(void)
9268 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9269 asm_statement_t *asm_statement = &statement->asms;
9273 if (token.type == T_volatile) {
9275 asm_statement->is_volatile = true;
9279 add_anchor_token(')');
9280 add_anchor_token(':');
9281 asm_statement->asm_text = parse_string_literals();
9283 if (token.type != ':') {
9284 rem_anchor_token(':');
9289 asm_statement->outputs = parse_asm_arguments(true);
9290 if (token.type != ':') {
9291 rem_anchor_token(':');
9296 asm_statement->inputs = parse_asm_arguments(false);
9297 if (token.type != ':') {
9298 rem_anchor_token(':');
9301 rem_anchor_token(':');
9304 asm_statement->clobbers = parse_asm_clobbers();
9307 rem_anchor_token(')');
9311 if (asm_statement->outputs == NULL) {
9312 /* GCC: An 'asm' instruction without any output operands will be treated
9313 * identically to a volatile 'asm' instruction. */
9314 asm_statement->is_volatile = true;
9319 return create_invalid_statement();
9323 * Parse a case statement.
9325 static statement_t *parse_case_statement(void)
9327 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9328 source_position_t *const pos = &statement->base.source_position;
9332 expression_t *const expression = parse_expression();
9333 statement->case_label.expression = expression;
9334 if (!is_constant_expression(expression)) {
9335 /* This check does not prevent the error message in all cases of an
9336 * prior error while parsing the expression. At least it catches the
9337 * common case of a mistyped enum entry. */
9338 if (is_type_valid(skip_typeref(expression->base.type))) {
9339 errorf(pos, "case label does not reduce to an integer constant");
9341 statement->case_label.is_bad = true;
9343 long const val = fold_constant(expression);
9344 statement->case_label.first_case = val;
9345 statement->case_label.last_case = val;
9349 if (token.type == T_DOTDOTDOT) {
9351 expression_t *const end_range = parse_expression();
9352 statement->case_label.end_range = end_range;
9353 if (!is_constant_expression(end_range)) {
9354 /* This check does not prevent the error message in all cases of an
9355 * prior error while parsing the expression. At least it catches the
9356 * common case of a mistyped enum entry. */
9357 if (is_type_valid(skip_typeref(end_range->base.type))) {
9358 errorf(pos, "case range does not reduce to an integer constant");
9360 statement->case_label.is_bad = true;
9362 long const val = fold_constant(end_range);
9363 statement->case_label.last_case = val;
9365 if (warning.other && val < statement->case_label.first_case) {
9366 statement->case_label.is_empty_range = true;
9367 warningf(pos, "empty range specified");
9373 PUSH_PARENT(statement);
9377 if (current_switch != NULL) {
9378 if (! statement->case_label.is_bad) {
9379 /* Check for duplicate case values */
9380 case_label_statement_t *c = &statement->case_label;
9381 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9382 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9385 if (c->last_case < l->first_case || c->first_case > l->last_case)
9388 errorf(pos, "duplicate case value (previously used %P)",
9389 &l->base.source_position);
9393 /* link all cases into the switch statement */
9394 if (current_switch->last_case == NULL) {
9395 current_switch->first_case = &statement->case_label;
9397 current_switch->last_case->next = &statement->case_label;
9399 current_switch->last_case = &statement->case_label;
9401 errorf(pos, "case label not within a switch statement");
9404 statement_t *const inner_stmt = parse_statement();
9405 statement->case_label.statement = inner_stmt;
9406 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9407 errorf(&inner_stmt->base.source_position, "declaration after case label");
9414 return create_invalid_statement();
9418 * Parse a default statement.
9420 static statement_t *parse_default_statement(void)
9422 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9426 PUSH_PARENT(statement);
9429 if (current_switch != NULL) {
9430 const case_label_statement_t *def_label = current_switch->default_label;
9431 if (def_label != NULL) {
9432 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9433 &def_label->base.source_position);
9435 current_switch->default_label = &statement->case_label;
9437 /* link all cases into the switch statement */
9438 if (current_switch->last_case == NULL) {
9439 current_switch->first_case = &statement->case_label;
9441 current_switch->last_case->next = &statement->case_label;
9443 current_switch->last_case = &statement->case_label;
9446 errorf(&statement->base.source_position,
9447 "'default' label not within a switch statement");
9450 statement_t *const inner_stmt = parse_statement();
9451 statement->case_label.statement = inner_stmt;
9452 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9453 errorf(&inner_stmt->base.source_position, "declaration after default label");
9460 return create_invalid_statement();
9464 * Parse a label statement.
9466 static statement_t *parse_label_statement(void)
9468 assert(token.type == T_IDENTIFIER);
9469 symbol_t *symbol = token.v.symbol;
9470 label_t *label = get_label(symbol);
9472 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9473 statement->label.label = label;
9477 PUSH_PARENT(statement);
9479 /* if statement is already set then the label is defined twice,
9480 * otherwise it was just mentioned in a goto/local label declaration so far
9482 if (label->statement != NULL) {
9483 errorf(HERE, "duplicate label '%Y' (declared %P)",
9484 symbol, &label->base.source_position);
9486 label->base.source_position = token.source_position;
9487 label->statement = statement;
9492 if (token.type == '}') {
9493 /* TODO only warn? */
9494 if (warning.other && false) {
9495 warningf(HERE, "label at end of compound statement");
9496 statement->label.statement = create_empty_statement();
9498 errorf(HERE, "label at end of compound statement");
9499 statement->label.statement = create_invalid_statement();
9501 } else if (token.type == ';') {
9502 /* Eat an empty statement here, to avoid the warning about an empty
9503 * statement after a label. label:; is commonly used to have a label
9504 * before a closing brace. */
9505 statement->label.statement = create_empty_statement();
9508 statement_t *const inner_stmt = parse_statement();
9509 statement->label.statement = inner_stmt;
9510 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9511 errorf(&inner_stmt->base.source_position, "declaration after label");
9515 /* remember the labels in a list for later checking */
9516 if (label_last == NULL) {
9517 label_first = &statement->label;
9519 label_last->next = &statement->label;
9521 label_last = &statement->label;
9528 * Parse an if statement.
9530 static statement_t *parse_if(void)
9532 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9536 PUSH_PARENT(statement);
9538 add_anchor_token('{');
9541 add_anchor_token(')');
9542 expression_t *const expr = parse_expression();
9543 statement->ifs.condition = expr;
9544 mark_vars_read(expr, NULL);
9545 rem_anchor_token(')');
9549 rem_anchor_token('{');
9551 add_anchor_token(T_else);
9552 statement->ifs.true_statement = parse_statement();
9553 rem_anchor_token(T_else);
9555 if (token.type == T_else) {
9557 statement->ifs.false_statement = parse_statement();
9565 * Check that all enums are handled in a switch.
9567 * @param statement the switch statement to check
9569 static void check_enum_cases(const switch_statement_t *statement) {
9570 const type_t *type = skip_typeref(statement->expression->base.type);
9571 if (! is_type_enum(type))
9573 const enum_type_t *enumt = &type->enumt;
9575 /* if we have a default, no warnings */
9576 if (statement->default_label != NULL)
9579 /* FIXME: calculation of value should be done while parsing */
9580 /* TODO: quadratic algorithm here. Change to an n log n one */
9581 long last_value = -1;
9582 const entity_t *entry = enumt->enume->base.next;
9583 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9584 entry = entry->base.next) {
9585 const expression_t *expression = entry->enum_value.value;
9586 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9588 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9589 if (l->expression == NULL)
9591 if (l->first_case <= value && value <= l->last_case) {
9597 warningf(&statement->base.source_position,
9598 "enumeration value '%Y' not handled in switch",
9599 entry->base.symbol);
9606 * Parse a switch statement.
9608 static statement_t *parse_switch(void)
9610 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9614 PUSH_PARENT(statement);
9617 add_anchor_token(')');
9618 expression_t *const expr = parse_expression();
9619 mark_vars_read(expr, NULL);
9620 type_t * type = skip_typeref(expr->base.type);
9621 if (is_type_integer(type)) {
9622 type = promote_integer(type);
9623 if (warning.traditional) {
9624 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9625 warningf(&expr->base.source_position,
9626 "'%T' switch expression not converted to '%T' in ISO C",
9630 } else if (is_type_valid(type)) {
9631 errorf(&expr->base.source_position,
9632 "switch quantity is not an integer, but '%T'", type);
9633 type = type_error_type;
9635 statement->switchs.expression = create_implicit_cast(expr, type);
9637 rem_anchor_token(')');
9639 switch_statement_t *rem = current_switch;
9640 current_switch = &statement->switchs;
9641 statement->switchs.body = parse_statement();
9642 current_switch = rem;
9644 if (warning.switch_default &&
9645 statement->switchs.default_label == NULL) {
9646 warningf(&statement->base.source_position, "switch has no default case");
9648 if (warning.switch_enum)
9649 check_enum_cases(&statement->switchs);
9655 return create_invalid_statement();
9658 static statement_t *parse_loop_body(statement_t *const loop)
9660 statement_t *const rem = current_loop;
9661 current_loop = loop;
9663 statement_t *const body = parse_statement();
9670 * Parse a while statement.
9672 static statement_t *parse_while(void)
9674 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9678 PUSH_PARENT(statement);
9681 add_anchor_token(')');
9682 expression_t *const cond = parse_expression();
9683 statement->whiles.condition = cond;
9684 mark_vars_read(cond, NULL);
9685 rem_anchor_token(')');
9688 statement->whiles.body = parse_loop_body(statement);
9694 return create_invalid_statement();
9698 * Parse a do statement.
9700 static statement_t *parse_do(void)
9702 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9706 PUSH_PARENT(statement);
9708 add_anchor_token(T_while);
9709 statement->do_while.body = parse_loop_body(statement);
9710 rem_anchor_token(T_while);
9714 add_anchor_token(')');
9715 expression_t *const cond = parse_expression();
9716 statement->do_while.condition = cond;
9717 mark_vars_read(cond, NULL);
9718 rem_anchor_token(')');
9726 return create_invalid_statement();
9730 * Parse a for statement.
9732 static statement_t *parse_for(void)
9734 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9738 PUSH_PARENT(statement);
9740 size_t const top = environment_top();
9741 scope_push(&statement->fors.scope);
9744 add_anchor_token(')');
9746 if (token.type != ';') {
9747 if (is_declaration_specifier(&token, false)) {
9748 parse_declaration(record_entity);
9750 add_anchor_token(';');
9751 expression_t *const init = parse_expression();
9752 statement->fors.initialisation = init;
9753 mark_vars_read(init, VAR_ANY);
9754 if (warning.unused_value && !expression_has_effect(init)) {
9755 warningf(&init->base.source_position,
9756 "initialisation of 'for'-statement has no effect");
9758 rem_anchor_token(';');
9765 if (token.type != ';') {
9766 add_anchor_token(';');
9767 expression_t *const cond = parse_expression();
9768 statement->fors.condition = cond;
9769 mark_vars_read(cond, NULL);
9770 rem_anchor_token(';');
9773 if (token.type != ')') {
9774 expression_t *const step = parse_expression();
9775 statement->fors.step = step;
9776 mark_vars_read(step, VAR_ANY);
9777 if (warning.unused_value && !expression_has_effect(step)) {
9778 warningf(&step->base.source_position,
9779 "step of 'for'-statement has no effect");
9783 rem_anchor_token(')');
9784 statement->fors.body = parse_loop_body(statement);
9786 assert(current_scope == &statement->fors.scope);
9788 environment_pop_to(top);
9795 rem_anchor_token(')');
9796 assert(current_scope == &statement->fors.scope);
9798 environment_pop_to(top);
9800 return create_invalid_statement();
9804 * Parse a goto statement.
9806 static statement_t *parse_goto(void)
9808 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9811 if (GNU_MODE && token.type == '*') {
9813 expression_t *expression = parse_expression();
9814 mark_vars_read(expression, NULL);
9816 /* Argh: although documentation say the expression must be of type void *,
9817 * gcc excepts anything that can be casted into void * without error */
9818 type_t *type = expression->base.type;
9820 if (type != type_error_type) {
9821 if (!is_type_pointer(type) && !is_type_integer(type)) {
9822 errorf(&expression->base.source_position,
9823 "cannot convert to a pointer type");
9824 } else if (warning.other && type != type_void_ptr) {
9825 warningf(&expression->base.source_position,
9826 "type of computed goto expression should be 'void*' not '%T'", type);
9828 expression = create_implicit_cast(expression, type_void_ptr);
9831 statement->gotos.expression = expression;
9833 if (token.type != T_IDENTIFIER) {
9835 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9837 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9841 symbol_t *symbol = token.v.symbol;
9844 statement->gotos.label = get_label(symbol);
9847 /* remember the goto's in a list for later checking */
9848 if (goto_last == NULL) {
9849 goto_first = &statement->gotos;
9851 goto_last->next = &statement->gotos;
9853 goto_last = &statement->gotos;
9859 return create_invalid_statement();
9863 * Parse a continue statement.
9865 static statement_t *parse_continue(void)
9867 if (current_loop == NULL) {
9868 errorf(HERE, "continue statement not within loop");
9871 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9881 * Parse a break statement.
9883 static statement_t *parse_break(void)
9885 if (current_switch == NULL && current_loop == NULL) {
9886 errorf(HERE, "break statement not within loop or switch");
9889 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9899 * Parse a __leave statement.
9901 static statement_t *parse_leave_statement(void)
9903 if (current_try == NULL) {
9904 errorf(HERE, "__leave statement not within __try");
9907 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9917 * Check if a given entity represents a local variable.
9919 static bool is_local_variable(const entity_t *entity)
9921 if (entity->kind != ENTITY_VARIABLE)
9924 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9925 case STORAGE_CLASS_AUTO:
9926 case STORAGE_CLASS_REGISTER: {
9927 const type_t *type = skip_typeref(entity->declaration.type);
9928 if (is_type_function(type)) {
9940 * Check if a given expression represents a local variable.
9942 static bool expression_is_local_variable(const expression_t *expression)
9944 if (expression->base.kind != EXPR_REFERENCE) {
9947 const entity_t *entity = expression->reference.entity;
9948 return is_local_variable(entity);
9952 * Check if a given expression represents a local variable and
9953 * return its declaration then, else return NULL.
9955 entity_t *expression_is_variable(const expression_t *expression)
9957 if (expression->base.kind != EXPR_REFERENCE) {
9960 entity_t *entity = expression->reference.entity;
9961 if (entity->kind != ENTITY_VARIABLE)
9968 * Parse a return statement.
9970 static statement_t *parse_return(void)
9974 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9976 expression_t *return_value = NULL;
9977 if (token.type != ';') {
9978 return_value = parse_expression();
9979 mark_vars_read(return_value, NULL);
9982 const type_t *const func_type = skip_typeref(current_function->base.type);
9983 assert(is_type_function(func_type));
9984 type_t *const return_type = skip_typeref(func_type->function.return_type);
9986 if (return_value != NULL) {
9987 type_t *return_value_type = skip_typeref(return_value->base.type);
9989 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
9990 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9991 if (warning.other) {
9992 warningf(&statement->base.source_position,
9993 "'return' with a value, in function returning void");
9995 return_value = NULL;
9997 assign_error_t error = semantic_assign(return_type, return_value);
9998 report_assign_error(error, return_type, return_value, "'return'",
9999 &statement->base.source_position);
10000 return_value = create_implicit_cast(return_value, return_type);
10002 /* check for returning address of a local var */
10003 if (warning.other && return_value != NULL
10004 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10005 const expression_t *expression = return_value->unary.value;
10006 if (expression_is_local_variable(expression)) {
10007 warningf(&statement->base.source_position,
10008 "function returns address of local variable");
10011 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10012 warningf(&statement->base.source_position,
10013 "'return' without value, in function returning non-void");
10015 statement->returns.value = return_value;
10024 * Parse a declaration statement.
10026 static statement_t *parse_declaration_statement(void)
10028 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10030 entity_t *before = current_scope->last_entity;
10032 parse_external_declaration();
10034 parse_declaration(record_entity);
10036 if (before == NULL) {
10037 statement->declaration.declarations_begin = current_scope->entities;
10039 statement->declaration.declarations_begin = before->base.next;
10041 statement->declaration.declarations_end = current_scope->last_entity;
10047 * Parse an expression statement, ie. expr ';'.
10049 static statement_t *parse_expression_statement(void)
10051 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10053 expression_t *const expr = parse_expression();
10054 statement->expression.expression = expr;
10055 mark_vars_read(expr, VAR_ANY);
10064 * Parse a microsoft __try { } __finally { } or
10065 * __try{ } __except() { }
10067 static statement_t *parse_ms_try_statment(void)
10069 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10072 PUSH_PARENT(statement);
10074 ms_try_statement_t *rem = current_try;
10075 current_try = &statement->ms_try;
10076 statement->ms_try.try_statement = parse_compound_statement(false);
10081 if (token.type == T___except) {
10084 add_anchor_token(')');
10085 expression_t *const expr = parse_expression();
10086 mark_vars_read(expr, NULL);
10087 type_t * type = skip_typeref(expr->base.type);
10088 if (is_type_integer(type)) {
10089 type = promote_integer(type);
10090 } else if (is_type_valid(type)) {
10091 errorf(&expr->base.source_position,
10092 "__expect expression is not an integer, but '%T'", type);
10093 type = type_error_type;
10095 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10096 rem_anchor_token(')');
10098 statement->ms_try.final_statement = parse_compound_statement(false);
10099 } else if (token.type == T__finally) {
10101 statement->ms_try.final_statement = parse_compound_statement(false);
10103 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10104 return create_invalid_statement();
10108 return create_invalid_statement();
10111 static statement_t *parse_empty_statement(void)
10113 if (warning.empty_statement) {
10114 warningf(HERE, "statement is empty");
10116 statement_t *const statement = create_empty_statement();
10121 static statement_t *parse_local_label_declaration(void)
10123 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10127 entity_t *begin = NULL, *end = NULL;
10130 if (token.type != T_IDENTIFIER) {
10131 parse_error_expected("while parsing local label declaration",
10132 T_IDENTIFIER, NULL);
10135 symbol_t *symbol = token.v.symbol;
10136 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10137 if (entity != NULL && entity->base.parent_scope == current_scope) {
10138 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10139 symbol, &entity->base.source_position);
10141 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10143 entity->base.parent_scope = current_scope;
10144 entity->base.namespc = NAMESPACE_LABEL;
10145 entity->base.source_position = token.source_position;
10146 entity->base.symbol = symbol;
10149 end->base.next = entity;
10154 environment_push(entity);
10158 if (token.type != ',')
10164 statement->declaration.declarations_begin = begin;
10165 statement->declaration.declarations_end = end;
10169 static void parse_namespace_definition(void)
10173 entity_t *entity = NULL;
10174 symbol_t *symbol = NULL;
10176 if (token.type == T_IDENTIFIER) {
10177 symbol = token.v.symbol;
10180 entity = get_entity(symbol, NAMESPACE_NORMAL);
10181 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10182 && entity->base.parent_scope == current_scope) {
10183 error_redefined_as_different_kind(&token.source_position,
10184 entity, ENTITY_NAMESPACE);
10189 if (entity == NULL) {
10190 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10191 entity->base.symbol = symbol;
10192 entity->base.source_position = token.source_position;
10193 entity->base.namespc = NAMESPACE_NORMAL;
10194 entity->base.parent_scope = current_scope;
10197 if (token.type == '=') {
10198 /* TODO: parse namespace alias */
10199 panic("namespace alias definition not supported yet");
10202 environment_push(entity);
10203 append_entity(current_scope, entity);
10205 size_t const top = environment_top();
10206 scope_push(&entity->namespacee.members);
10213 assert(current_scope == &entity->namespacee.members);
10215 environment_pop_to(top);
10219 * Parse a statement.
10220 * There's also parse_statement() which additionally checks for
10221 * "statement has no effect" warnings
10223 static statement_t *intern_parse_statement(void)
10225 statement_t *statement = NULL;
10227 /* declaration or statement */
10228 add_anchor_token(';');
10229 switch (token.type) {
10230 case T_IDENTIFIER: {
10231 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10232 if (la1_type == ':') {
10233 statement = parse_label_statement();
10234 } else if (is_typedef_symbol(token.v.symbol)) {
10235 statement = parse_declaration_statement();
10237 /* it's an identifier, the grammar says this must be an
10238 * expression statement. However it is common that users mistype
10239 * declaration types, so we guess a bit here to improve robustness
10240 * for incorrect programs */
10241 switch (la1_type) {
10243 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10244 goto expression_statment;
10249 statement = parse_declaration_statement();
10253 expression_statment:
10254 statement = parse_expression_statement();
10261 case T___extension__:
10262 /* This can be a prefix to a declaration or an expression statement.
10263 * We simply eat it now and parse the rest with tail recursion. */
10266 } while (token.type == T___extension__);
10267 bool old_gcc_extension = in_gcc_extension;
10268 in_gcc_extension = true;
10269 statement = parse_statement();
10270 in_gcc_extension = old_gcc_extension;
10274 statement = parse_declaration_statement();
10278 statement = parse_local_label_declaration();
10281 case ';': statement = parse_empty_statement(); break;
10282 case '{': statement = parse_compound_statement(false); break;
10283 case T___leave: statement = parse_leave_statement(); break;
10284 case T___try: statement = parse_ms_try_statment(); break;
10285 case T_asm: statement = parse_asm_statement(); break;
10286 case T_break: statement = parse_break(); break;
10287 case T_case: statement = parse_case_statement(); break;
10288 case T_continue: statement = parse_continue(); break;
10289 case T_default: statement = parse_default_statement(); break;
10290 case T_do: statement = parse_do(); break;
10291 case T_for: statement = parse_for(); break;
10292 case T_goto: statement = parse_goto(); break;
10293 case T_if: statement = parse_if(); break;
10294 case T_return: statement = parse_return(); break;
10295 case T_switch: statement = parse_switch(); break;
10296 case T_while: statement = parse_while(); break;
10299 statement = parse_expression_statement();
10303 errorf(HERE, "unexpected token %K while parsing statement", &token);
10304 statement = create_invalid_statement();
10309 rem_anchor_token(';');
10311 assert(statement != NULL
10312 && statement->base.source_position.input_name != NULL);
10318 * parse a statement and emits "statement has no effect" warning if needed
10319 * (This is really a wrapper around intern_parse_statement with check for 1
10320 * single warning. It is needed, because for statement expressions we have
10321 * to avoid the warning on the last statement)
10323 static statement_t *parse_statement(void)
10325 statement_t *statement = intern_parse_statement();
10327 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10328 expression_t *expression = statement->expression.expression;
10329 if (!expression_has_effect(expression)) {
10330 warningf(&expression->base.source_position,
10331 "statement has no effect");
10339 * Parse a compound statement.
10341 static statement_t *parse_compound_statement(bool inside_expression_statement)
10343 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10345 PUSH_PARENT(statement);
10348 add_anchor_token('}');
10350 size_t const top = environment_top();
10351 scope_push(&statement->compound.scope);
10353 statement_t **anchor = &statement->compound.statements;
10354 bool only_decls_so_far = true;
10355 while (token.type != '}') {
10356 if (token.type == T_EOF) {
10357 errorf(&statement->base.source_position,
10358 "EOF while parsing compound statement");
10361 statement_t *sub_statement = intern_parse_statement();
10362 if (is_invalid_statement(sub_statement)) {
10363 /* an error occurred. if we are at an anchor, return */
10369 if (warning.declaration_after_statement) {
10370 if (sub_statement->kind != STATEMENT_DECLARATION) {
10371 only_decls_so_far = false;
10372 } else if (!only_decls_so_far) {
10373 warningf(&sub_statement->base.source_position,
10374 "ISO C90 forbids mixed declarations and code");
10378 *anchor = sub_statement;
10380 while (sub_statement->base.next != NULL)
10381 sub_statement = sub_statement->base.next;
10383 anchor = &sub_statement->base.next;
10387 /* look over all statements again to produce no effect warnings */
10388 if (warning.unused_value) {
10389 statement_t *sub_statement = statement->compound.statements;
10390 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10391 if (sub_statement->kind != STATEMENT_EXPRESSION)
10393 /* don't emit a warning for the last expression in an expression
10394 * statement as it has always an effect */
10395 if (inside_expression_statement && sub_statement->base.next == NULL)
10398 expression_t *expression = sub_statement->expression.expression;
10399 if (!expression_has_effect(expression)) {
10400 warningf(&expression->base.source_position,
10401 "statement has no effect");
10407 rem_anchor_token('}');
10408 assert(current_scope == &statement->compound.scope);
10410 environment_pop_to(top);
10417 * Check for unused global static functions and variables
10419 static void check_unused_globals(void)
10421 if (!warning.unused_function && !warning.unused_variable)
10424 for (const entity_t *entity = file_scope->entities; entity != NULL;
10425 entity = entity->base.next) {
10426 if (!is_declaration(entity))
10429 const declaration_t *declaration = &entity->declaration;
10430 if (declaration->used ||
10431 declaration->modifiers & DM_UNUSED ||
10432 declaration->modifiers & DM_USED ||
10433 declaration->storage_class != STORAGE_CLASS_STATIC)
10436 type_t *const type = declaration->type;
10438 if (entity->kind == ENTITY_FUNCTION) {
10439 /* inhibit warning for static inline functions */
10440 if (entity->function.is_inline)
10443 s = entity->function.statement != NULL ? "defined" : "declared";
10448 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10449 type, declaration->base.symbol, s);
10453 static void parse_global_asm(void)
10455 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10460 statement->asms.asm_text = parse_string_literals();
10461 statement->base.next = unit->global_asm;
10462 unit->global_asm = statement;
10470 static void parse_linkage_specification(void)
10473 assert(token.type == T_STRING_LITERAL);
10475 const char *linkage = parse_string_literals().begin;
10477 linkage_kind_t old_linkage = current_linkage;
10478 linkage_kind_t new_linkage;
10479 if (strcmp(linkage, "C") == 0) {
10480 new_linkage = LINKAGE_C;
10481 } else if (strcmp(linkage, "C++") == 0) {
10482 new_linkage = LINKAGE_CXX;
10484 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10485 new_linkage = LINKAGE_INVALID;
10487 current_linkage = new_linkage;
10489 if (token.type == '{') {
10498 assert(current_linkage == new_linkage);
10499 current_linkage = old_linkage;
10502 static void parse_external(void)
10504 switch (token.type) {
10505 DECLARATION_START_NO_EXTERN
10507 case T___extension__:
10508 case '(': /* for function declarations with implicit return type and
10509 * parenthesized declarator, i.e. (f)(void); */
10510 parse_external_declaration();
10514 if (look_ahead(1)->type == T_STRING_LITERAL) {
10515 parse_linkage_specification();
10517 parse_external_declaration();
10522 parse_global_asm();
10526 parse_namespace_definition();
10530 if (!strict_mode) {
10532 warningf(HERE, "stray ';' outside of function");
10539 errorf(HERE, "stray %K outside of function", &token);
10540 if (token.type == '(' || token.type == '{' || token.type == '[')
10541 eat_until_matching_token(token.type);
10547 static void parse_externals(void)
10549 add_anchor_token('}');
10550 add_anchor_token(T_EOF);
10553 unsigned char token_anchor_copy[T_LAST_TOKEN];
10554 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10557 while (token.type != T_EOF && token.type != '}') {
10559 bool anchor_leak = false;
10560 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10561 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10563 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10564 anchor_leak = true;
10567 if (in_gcc_extension) {
10568 errorf(HERE, "Leaked __extension__");
10569 anchor_leak = true;
10579 rem_anchor_token(T_EOF);
10580 rem_anchor_token('}');
10584 * Parse a translation unit.
10586 static void parse_translation_unit(void)
10588 add_anchor_token(T_EOF);
10593 if (token.type == T_EOF)
10596 errorf(HERE, "stray %K outside of function", &token);
10597 if (token.type == '(' || token.type == '{' || token.type == '[')
10598 eat_until_matching_token(token.type);
10606 * @return the translation unit or NULL if errors occurred.
10608 void start_parsing(void)
10610 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10611 label_stack = NEW_ARR_F(stack_entry_t, 0);
10612 diagnostic_count = 0;
10616 type_set_output(stderr);
10617 ast_set_output(stderr);
10619 assert(unit == NULL);
10620 unit = allocate_ast_zero(sizeof(unit[0]));
10622 assert(file_scope == NULL);
10623 file_scope = &unit->scope;
10625 assert(current_scope == NULL);
10626 scope_push(&unit->scope);
10629 translation_unit_t *finish_parsing(void)
10631 /* do NOT use scope_pop() here, this will crash, will it by hand */
10632 assert(current_scope == &unit->scope);
10633 current_scope = NULL;
10635 assert(file_scope == &unit->scope);
10636 check_unused_globals();
10639 DEL_ARR_F(environment_stack);
10640 DEL_ARR_F(label_stack);
10642 translation_unit_t *result = unit;
10649 lookahead_bufpos = 0;
10650 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10653 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10654 parse_translation_unit();
10658 * Initialize the parser.
10660 void init_parser(void)
10662 sym_anonymous = symbol_table_insert("<anonymous>");
10664 if (c_mode & _MS) {
10665 /* add predefined symbols for extended-decl-modifier */
10666 sym_align = symbol_table_insert("align");
10667 sym_allocate = symbol_table_insert("allocate");
10668 sym_dllimport = symbol_table_insert("dllimport");
10669 sym_dllexport = symbol_table_insert("dllexport");
10670 sym_naked = symbol_table_insert("naked");
10671 sym_noinline = symbol_table_insert("noinline");
10672 sym_noreturn = symbol_table_insert("noreturn");
10673 sym_nothrow = symbol_table_insert("nothrow");
10674 sym_novtable = symbol_table_insert("novtable");
10675 sym_property = symbol_table_insert("property");
10676 sym_get = symbol_table_insert("get");
10677 sym_put = symbol_table_insert("put");
10678 sym_selectany = symbol_table_insert("selectany");
10679 sym_thread = symbol_table_insert("thread");
10680 sym_uuid = symbol_table_insert("uuid");
10681 sym_deprecated = symbol_table_insert("deprecated");
10682 sym_restrict = symbol_table_insert("restrict");
10683 sym_noalias = symbol_table_insert("noalias");
10685 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10687 init_expression_parsers();
10688 obstack_init(&temp_obst);
10690 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10691 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10695 * Terminate the parser.
10697 void exit_parser(void)
10699 obstack_free(&temp_obst, NULL);