2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 /** if wchar_t is equal to unsigned short. */
45 bool opt_short_wchar_t =
52 //#define PRINT_TOKENS
53 #define MAX_LOOKAHEAD 2
61 typedef struct argument_list_t argument_list_t;
62 struct argument_list_t {
64 argument_list_t *next;
67 typedef struct gnu_attribute_t gnu_attribute_t;
68 struct gnu_attribute_t {
69 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
70 gnu_attribute_t *next;
71 bool invalid; /**< Set if this attribute had argument errors, */
72 bool have_arguments; /**< True, if this attribute has arguments. */
76 atomic_type_kind_t akind;
77 long argument; /**< Single argument. */
78 argument_list_t *arguments; /**< List of argument expressions. */
82 typedef struct declaration_specifiers_t declaration_specifiers_t;
83 struct declaration_specifiers_t {
84 source_position_t source_position;
85 storage_class_t storage_class;
86 unsigned char alignment; /**< Alignment, 0 if not set. */
89 decl_modifiers_t modifiers; /**< declaration modifiers */
90 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
91 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
92 symbol_t *get_property_sym; /**< the name of the get property if set. */
93 symbol_t *put_property_sym; /**< the name of the put property if set. */
98 * An environment for parsing initializers (and compound literals).
100 typedef struct parse_initializer_env_t {
101 type_t *type; /**< the type of the initializer. In case of an
102 array type with unspecified size this gets
103 adjusted to the actual size. */
104 entity_t *entity; /**< the variable that is initialized if any */
105 bool must_be_constant;
106 } parse_initializer_env_t;
108 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
110 /** The current token. */
111 static token_t token;
112 /** The lookahead ring-buffer. */
113 static token_t lookahead_buffer[MAX_LOOKAHEAD];
114 /** Position of the next token in the lookahead buffer. */
115 static int lookahead_bufpos;
116 static stack_entry_t *environment_stack = NULL;
117 static stack_entry_t *label_stack = NULL;
118 static stack_entry_t *local_label_stack = NULL;
119 /** The global file scope. */
120 static scope_t *file_scope = NULL;
121 /** The current scope. */
122 static scope_t *scope = NULL;
123 /** Point to the current function declaration if inside a function. */
124 static function_t *current_function = NULL;
125 static entity_t *current_init_decl = NULL;
126 static switch_statement_t *current_switch = NULL;
127 static statement_t *current_loop = NULL;
128 static statement_t *current_parent = NULL;
129 static ms_try_statement_t *current_try = NULL;
130 static goto_statement_t *goto_first = NULL;
131 static goto_statement_t *goto_last = NULL;
132 static label_statement_t *label_first = NULL;
133 static label_statement_t *label_last = NULL;
134 /** current translation unit. */
135 static translation_unit_t *unit = NULL;
136 /** true if we are in a type property context (evaluation only for type. */
137 static bool in_type_prop = false;
138 /** true in we are in a __extension__ context. */
139 static bool in_gcc_extension = false;
140 static struct obstack temp_obst;
143 #define PUSH_PARENT(stmt) \
144 statement_t *const prev_parent = current_parent; \
145 ((void)(current_parent = (stmt)))
146 #define POP_PARENT ((void)(current_parent = prev_parent))
148 /** special symbol used for anonymous entities. */
149 static const symbol_t *sym_anonymous = NULL;
151 /* symbols for Microsoft extended-decl-modifier */
152 static const symbol_t *sym_align = NULL;
153 static const symbol_t *sym_allocate = NULL;
154 static const symbol_t *sym_dllimport = NULL;
155 static const symbol_t *sym_dllexport = NULL;
156 static const symbol_t *sym_naked = NULL;
157 static const symbol_t *sym_noinline = NULL;
158 static const symbol_t *sym_noreturn = NULL;
159 static const symbol_t *sym_nothrow = NULL;
160 static const symbol_t *sym_novtable = NULL;
161 static const symbol_t *sym_property = NULL;
162 static const symbol_t *sym_get = NULL;
163 static const symbol_t *sym_put = NULL;
164 static const symbol_t *sym_selectany = NULL;
165 static const symbol_t *sym_thread = NULL;
166 static const symbol_t *sym_uuid = NULL;
167 static const symbol_t *sym_deprecated = NULL;
168 static const symbol_t *sym_restrict = NULL;
169 static const symbol_t *sym_noalias = NULL;
171 /** The token anchor set */
172 static unsigned char token_anchor_set[T_LAST_TOKEN];
174 /** The current source position. */
175 #define HERE (&token.source_position)
177 /** true if we are in GCC mode. */
178 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
180 static type_t *type_valist;
182 static statement_t *parse_compound_statement(bool inside_expression_statement);
183 static statement_t *parse_statement(void);
185 static expression_t *parse_sub_expression(precedence_t);
186 static expression_t *parse_expression(void);
187 static type_t *parse_typename(void);
189 static void parse_compound_type_entries(compound_t *compound_declaration);
190 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
191 bool may_be_abstract,
192 bool create_compound_member);
193 static entity_t *record_entity(entity_t *entity, bool is_definition);
195 static void semantic_comparison(binary_expression_t *expression);
197 #define STORAGE_CLASSES \
205 #define TYPE_QUALIFIERS \
210 case T__forceinline: \
211 case T___attribute__:
213 #ifdef PROVIDE_COMPLEX
214 #define COMPLEX_SPECIFIERS \
216 #define IMAGINARY_SPECIFIERS \
219 #define COMPLEX_SPECIFIERS
220 #define IMAGINARY_SPECIFIERS
223 #define TYPE_SPECIFIERS \
225 case T___builtin_va_list: \
244 #define DECLARATION_START \
249 #define TYPENAME_START \
253 #define EXPRESSION_START \
262 case T_CHARACTER_CONSTANT: \
263 case T_FLOATINGPOINT: \
267 case T_STRING_LITERAL: \
268 case T_WIDE_CHARACTER_CONSTANT: \
269 case T_WIDE_STRING_LITERAL: \
270 case T___FUNCDNAME__: \
271 case T___FUNCSIG__: \
272 case T___FUNCTION__: \
273 case T___PRETTY_FUNCTION__: \
274 case T___alignof__: \
275 case T___builtin_alloca: \
276 case T___builtin_classify_type: \
277 case T___builtin_constant_p: \
278 case T___builtin_expect: \
279 case T___builtin_huge_val: \
280 case T___builtin_inf: \
281 case T___builtin_inff: \
282 case T___builtin_infl: \
283 case T___builtin_isgreater: \
284 case T___builtin_isgreaterequal: \
285 case T___builtin_isless: \
286 case T___builtin_islessequal: \
287 case T___builtin_islessgreater: \
288 case T___builtin_isunordered: \
289 case T___builtin_nan: \
290 case T___builtin_nanf: \
291 case T___builtin_nanl: \
292 case T___builtin_offsetof: \
293 case T___builtin_prefetch: \
294 case T___builtin_va_arg: \
295 case T___builtin_va_end: \
296 case T___builtin_va_start: \
307 * Allocate an AST node with given size and
308 * initialize all fields with zero.
310 static void *allocate_ast_zero(size_t size)
312 void *res = allocate_ast(size);
313 memset(res, 0, size);
317 static size_t get_entity_struct_size(entity_kind_t kind)
319 static const size_t sizes[] = {
320 [ENTITY_VARIABLE] = sizeof(variable_t),
321 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
322 [ENTITY_FUNCTION] = sizeof(function_t),
323 [ENTITY_TYPEDEF] = sizeof(typedef_t),
324 [ENTITY_STRUCT] = sizeof(compound_t),
325 [ENTITY_UNION] = sizeof(compound_t),
326 [ENTITY_ENUM] = sizeof(enum_t),
327 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
328 [ENTITY_LABEL] = sizeof(label_t),
329 [ENTITY_LOCAL_LABEL] = sizeof(label_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 * Returns the index of the top element of the local label stack.
581 static size_t local_label_top(void)
583 return ARR_LEN(local_label_stack);
587 * Return the next token.
589 static inline void next_token(void)
591 token = lookahead_buffer[lookahead_bufpos];
592 lookahead_buffer[lookahead_bufpos] = lexer_token;
595 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
598 print_token(stderr, &token);
599 fprintf(stderr, "\n");
604 * Return the next token with a given lookahead.
606 static inline const token_t *look_ahead(int num)
608 assert(num > 0 && num <= MAX_LOOKAHEAD);
609 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
610 return &lookahead_buffer[pos];
614 * Adds a token to the token anchor set (a multi-set).
616 static void add_anchor_token(int token_type)
618 assert(0 <= token_type && token_type < T_LAST_TOKEN);
619 ++token_anchor_set[token_type];
622 static int save_and_reset_anchor_state(int token_type)
624 assert(0 <= token_type && token_type < T_LAST_TOKEN);
625 int count = token_anchor_set[token_type];
626 token_anchor_set[token_type] = 0;
630 static void restore_anchor_state(int token_type, int count)
632 assert(0 <= token_type && token_type < T_LAST_TOKEN);
633 token_anchor_set[token_type] = count;
637 * Remove a token from the token anchor set (a multi-set).
639 static void rem_anchor_token(int token_type)
641 assert(0 <= token_type && token_type < T_LAST_TOKEN);
642 assert(token_anchor_set[token_type] != 0);
643 --token_anchor_set[token_type];
646 static bool at_anchor(void)
650 return token_anchor_set[token.type];
654 * Eat tokens until a matching token is found.
656 static void eat_until_matching_token(int type)
660 case '(': end_token = ')'; break;
661 case '{': end_token = '}'; break;
662 case '[': end_token = ']'; break;
663 default: end_token = type; break;
666 unsigned parenthesis_count = 0;
667 unsigned brace_count = 0;
668 unsigned bracket_count = 0;
669 while (token.type != end_token ||
670 parenthesis_count != 0 ||
672 bracket_count != 0) {
673 switch (token.type) {
675 case '(': ++parenthesis_count; break;
676 case '{': ++brace_count; break;
677 case '[': ++bracket_count; break;
680 if (parenthesis_count > 0)
690 if (bracket_count > 0)
693 if (token.type == end_token &&
694 parenthesis_count == 0 &&
708 * Eat input tokens until an anchor is found.
710 static void eat_until_anchor(void)
712 while (token_anchor_set[token.type] == 0) {
713 if (token.type == '(' || token.type == '{' || token.type == '[')
714 eat_until_matching_token(token.type);
719 static void eat_block(void)
721 eat_until_matching_token('{');
722 if (token.type == '}')
726 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
729 * Report a parse error because an expected token was not found.
732 #if defined __GNUC__ && __GNUC__ >= 4
733 __attribute__((sentinel))
735 void parse_error_expected(const char *message, ...)
737 if (message != NULL) {
738 errorf(HERE, "%s", message);
741 va_start(ap, message);
742 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
747 * Report a type error.
749 static void type_error(const char *msg, const source_position_t *source_position,
752 errorf(source_position, "%s, but found type '%T'", msg, type);
756 * Report an incompatible type.
758 static void type_error_incompatible(const char *msg,
759 const source_position_t *source_position, type_t *type1, type_t *type2)
761 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
766 * Expect the the current token is the expected token.
767 * If not, generate an error, eat the current statement,
768 * and goto the end_error label.
770 #define expect(expected) \
772 if (UNLIKELY(token.type != (expected))) { \
773 parse_error_expected(NULL, (expected), NULL); \
774 add_anchor_token(expected); \
775 eat_until_anchor(); \
776 if (token.type == expected) \
778 rem_anchor_token(expected); \
784 static void scope_push(scope_t *new_scope)
787 new_scope->depth = scope->depth + 1;
789 new_scope->parent = scope;
793 static void scope_pop(void)
795 scope = scope->parent;
799 * Search an entity by its symbol in a given namespace.
801 static entity_t *get_entity(const symbol_t *const symbol, namespace_t namespc)
803 entity_t *entity = symbol->entity;
804 for( ; entity != NULL; entity = entity->base.symbol_next) {
805 if (entity->base.namespc == namespc)
813 * pushs an entity on the environment stack and links the corresponding symbol
816 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
818 symbol_t *symbol = entity->base.symbol;
819 namespace_t namespc = entity->base.namespc;
820 assert(namespc != NAMESPACE_INVALID);
822 /* replace/add entity into entity list of the symbol */
825 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
830 /* replace an entry? */
831 if (iter->base.namespc == namespc) {
832 entity->base.symbol_next = iter->base.symbol_next;
838 /* remember old declaration */
840 entry.symbol = symbol;
841 entry.old_entity = iter;
842 entry.namespc = namespc;
843 ARR_APP1(stack_entry_t, *stack_ptr, entry);
847 * Push an entity on the environment stack.
849 static void environment_push(entity_t *entity)
851 assert(entity->base.source_position.input_name != NULL);
852 assert(entity->base.parent_scope != NULL);
853 stack_push(&environment_stack, entity);
857 * Push a declaration on the global label stack.
859 * @param declaration the declaration
861 static void label_push(entity_t *label)
863 /* we abuse the parameters scope as parent for the labels */
864 label->base.parent_scope = ¤t_function->parameters;
865 stack_push(&label_stack, label);
869 * Push a declaration of the local label stack.
871 * @param declaration the declaration
873 static void local_label_push(entity_t *label)
875 assert(label->base.parent_scope != NULL);
876 label->base.parent_scope = scope;
877 stack_push(&local_label_stack, label);
881 * pops symbols from the environment stack until @p new_top is the top element
883 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
885 stack_entry_t *stack = *stack_ptr;
886 size_t top = ARR_LEN(stack);
889 assert(new_top <= top);
893 for(i = top; i > new_top; --i) {
894 stack_entry_t *entry = &stack[i - 1];
896 entity_t *old_entity = entry->old_entity;
897 symbol_t *symbol = entry->symbol;
898 namespace_t namespc = entry->namespc;
900 /* replace with old_entity/remove */
903 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
905 assert(iter != NULL);
906 /* replace an entry? */
907 if (iter->base.namespc == namespc)
911 /* restore definition from outer scopes (if there was one) */
912 if (old_entity != NULL) {
913 old_entity->base.symbol_next = iter->base.symbol_next;
914 *anchor = old_entity;
916 /* remove entry from list */
917 *anchor = iter->base.symbol_next;
921 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
925 * Pop all entries from the environment stack until the new_top
928 * @param new_top the new stack top
930 static void environment_pop_to(size_t new_top)
932 stack_pop_to(&environment_stack, new_top);
936 * Pop all entries from the global label stack until the new_top
939 * @param new_top the new stack top
941 static void label_pop_to(size_t new_top)
943 stack_pop_to(&label_stack, new_top);
947 * Pop all entries from the local label stack until the new_top
950 * @param new_top the new stack top
952 static void local_label_pop_to(size_t new_top)
954 stack_pop_to(&local_label_stack, new_top);
958 static int get_akind_rank(atomic_type_kind_t akind)
963 static int get_rank(const type_t *type)
965 assert(!is_typeref(type));
966 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
967 * and esp. footnote 108). However we can't fold constants (yet), so we
968 * can't decide whether unsigned int is possible, while int always works.
969 * (unsigned int would be preferable when possible... for stuff like
970 * struct { enum { ... } bla : 4; } ) */
971 if (type->kind == TYPE_ENUM)
972 return get_akind_rank(ATOMIC_TYPE_INT);
974 assert(type->kind == TYPE_ATOMIC);
975 return get_akind_rank(type->atomic.akind);
978 static type_t *promote_integer(type_t *type)
980 if (type->kind == TYPE_BITFIELD)
981 type = type->bitfield.base_type;
983 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
990 * Create a cast expression.
992 * @param expression the expression to cast
993 * @param dest_type the destination type
995 static expression_t *create_cast_expression(expression_t *expression,
998 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1000 cast->unary.value = expression;
1001 cast->base.type = dest_type;
1007 * Check if a given expression represents the 0 pointer constant.
1009 static bool is_null_pointer_constant(const expression_t *expression)
1011 /* skip void* cast */
1012 if (expression->kind == EXPR_UNARY_CAST
1013 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1014 expression = expression->unary.value;
1017 /* TODO: not correct yet, should be any constant integer expression
1018 * which evaluates to 0 */
1019 if (expression->kind != EXPR_CONST)
1022 type_t *const type = skip_typeref(expression->base.type);
1023 if (!is_type_integer(type))
1026 return expression->conste.v.int_value == 0;
1030 * Create an implicit cast expression.
1032 * @param expression the expression to cast
1033 * @param dest_type the destination type
1035 static expression_t *create_implicit_cast(expression_t *expression,
1038 type_t *const source_type = expression->base.type;
1040 if (source_type == dest_type)
1043 return create_cast_expression(expression, dest_type);
1046 typedef enum assign_error_t {
1048 ASSIGN_ERROR_INCOMPATIBLE,
1049 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1050 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1051 ASSIGN_WARNING_POINTER_FROM_INT,
1052 ASSIGN_WARNING_INT_FROM_POINTER
1055 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1056 const expression_t *const right,
1057 const char *context,
1058 const source_position_t *source_position)
1060 type_t *const orig_type_right = right->base.type;
1061 type_t *const type_left = skip_typeref(orig_type_left);
1062 type_t *const type_right = skip_typeref(orig_type_right);
1065 case ASSIGN_SUCCESS:
1067 case ASSIGN_ERROR_INCOMPATIBLE:
1068 errorf(source_position,
1069 "destination type '%T' in %s is incompatible with type '%T'",
1070 orig_type_left, context, orig_type_right);
1073 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1074 if (warning.other) {
1075 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1076 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1078 /* the left type has all qualifiers from the right type */
1079 unsigned missing_qualifiers
1080 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1081 warningf(source_position,
1082 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1083 orig_type_left, context, orig_type_right, missing_qualifiers);
1088 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1089 if (warning.other) {
1090 warningf(source_position,
1091 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1092 orig_type_left, context, right, orig_type_right);
1096 case ASSIGN_WARNING_POINTER_FROM_INT:
1097 if (warning.other) {
1098 warningf(source_position,
1099 "%s makes pointer '%T' from integer '%T' without a cast",
1100 context, orig_type_left, orig_type_right);
1104 case ASSIGN_WARNING_INT_FROM_POINTER:
1105 if (warning.other) {
1106 warningf(source_position,
1107 "%s makes integer '%T' from pointer '%T' without a cast",
1108 context, orig_type_left, orig_type_right);
1113 panic("invalid error value");
1117 /** Implements the rules from § 6.5.16.1 */
1118 static assign_error_t semantic_assign(type_t *orig_type_left,
1119 const expression_t *const right)
1121 type_t *const orig_type_right = right->base.type;
1122 type_t *const type_left = skip_typeref(orig_type_left);
1123 type_t *const type_right = skip_typeref(orig_type_right);
1125 if (is_type_pointer(type_left)) {
1126 if (is_null_pointer_constant(right)) {
1127 return ASSIGN_SUCCESS;
1128 } else if (is_type_pointer(type_right)) {
1129 type_t *points_to_left
1130 = skip_typeref(type_left->pointer.points_to);
1131 type_t *points_to_right
1132 = skip_typeref(type_right->pointer.points_to);
1133 assign_error_t res = ASSIGN_SUCCESS;
1135 /* the left type has all qualifiers from the right type */
1136 unsigned missing_qualifiers
1137 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1138 if (missing_qualifiers != 0) {
1139 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1142 points_to_left = get_unqualified_type(points_to_left);
1143 points_to_right = get_unqualified_type(points_to_right);
1145 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1148 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1149 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1150 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1153 if (!types_compatible(points_to_left, points_to_right)) {
1154 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1158 } else if (is_type_integer(type_right)) {
1159 return ASSIGN_WARNING_POINTER_FROM_INT;
1161 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1162 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1163 && is_type_pointer(type_right))) {
1164 return ASSIGN_SUCCESS;
1165 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1166 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1167 type_t *const unqual_type_left = get_unqualified_type(type_left);
1168 type_t *const unqual_type_right = get_unqualified_type(type_right);
1169 if (types_compatible(unqual_type_left, unqual_type_right)) {
1170 return ASSIGN_SUCCESS;
1172 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1173 return ASSIGN_WARNING_INT_FROM_POINTER;
1176 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1177 return ASSIGN_SUCCESS;
1179 return ASSIGN_ERROR_INCOMPATIBLE;
1182 static expression_t *parse_constant_expression(void)
1184 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1186 if (!is_constant_expression(result)) {
1187 errorf(&result->base.source_position,
1188 "expression '%E' is not constant\n", result);
1194 static expression_t *parse_assignment_expression(void)
1196 return parse_sub_expression(PREC_ASSIGNMENT);
1199 static type_t *make_global_typedef(const char *name, type_t *type)
1201 symbol_t *const symbol = symbol_table_insert(name);
1203 entity_t *const entity = allocate_entity_zero(ENTITY_TYPEDEF);
1204 entity->base.symbol = symbol;
1205 entity->base.source_position = builtin_source_position;
1206 entity->base.namespc = NAMESPACE_NORMAL;
1207 entity->typedefe.type = type;
1208 entity->typedefe.builtin = true;
1210 record_entity(entity, false);
1212 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF);
1213 typedef_type->typedeft.typedefe = &entity->typedefe;
1215 return typedef_type;
1218 static string_t parse_string_literals(void)
1220 assert(token.type == T_STRING_LITERAL);
1221 string_t result = token.v.string;
1225 while (token.type == T_STRING_LITERAL) {
1226 result = concat_strings(&result, &token.v.string);
1233 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1234 [GNU_AK_CONST] = "const",
1235 [GNU_AK_VOLATILE] = "volatile",
1236 [GNU_AK_CDECL] = "cdecl",
1237 [GNU_AK_STDCALL] = "stdcall",
1238 [GNU_AK_FASTCALL] = "fastcall",
1239 [GNU_AK_DEPRECATED] = "deprecated",
1240 [GNU_AK_NOINLINE] = "noinline",
1241 [GNU_AK_NORETURN] = "noreturn",
1242 [GNU_AK_NAKED] = "naked",
1243 [GNU_AK_PURE] = "pure",
1244 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1245 [GNU_AK_MALLOC] = "malloc",
1246 [GNU_AK_WEAK] = "weak",
1247 [GNU_AK_CONSTRUCTOR] = "constructor",
1248 [GNU_AK_DESTRUCTOR] = "destructor",
1249 [GNU_AK_NOTHROW] = "nothrow",
1250 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1251 [GNU_AK_COMMON] = "common",
1252 [GNU_AK_NOCOMMON] = "nocommon",
1253 [GNU_AK_PACKED] = "packed",
1254 [GNU_AK_SHARED] = "shared",
1255 [GNU_AK_NOTSHARED] = "notshared",
1256 [GNU_AK_USED] = "used",
1257 [GNU_AK_UNUSED] = "unused",
1258 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1259 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1260 [GNU_AK_LONGCALL] = "longcall",
1261 [GNU_AK_SHORTCALL] = "shortcall",
1262 [GNU_AK_LONG_CALL] = "long_call",
1263 [GNU_AK_SHORT_CALL] = "short_call",
1264 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1265 [GNU_AK_INTERRUPT] = "interrupt",
1266 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1267 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1268 [GNU_AK_NESTING] = "nesting",
1269 [GNU_AK_NEAR] = "near",
1270 [GNU_AK_FAR] = "far",
1271 [GNU_AK_SIGNAL] = "signal",
1272 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1273 [GNU_AK_TINY_DATA] = "tiny_data",
1274 [GNU_AK_SAVEALL] = "saveall",
1275 [GNU_AK_FLATTEN] = "flatten",
1276 [GNU_AK_SSEREGPARM] = "sseregparm",
1277 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1278 [GNU_AK_RETURN_TWICE] = "return_twice",
1279 [GNU_AK_MAY_ALIAS] = "may_alias",
1280 [GNU_AK_MS_STRUCT] = "ms_struct",
1281 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1282 [GNU_AK_DLLIMPORT] = "dllimport",
1283 [GNU_AK_DLLEXPORT] = "dllexport",
1284 [GNU_AK_ALIGNED] = "aligned",
1285 [GNU_AK_ALIAS] = "alias",
1286 [GNU_AK_SECTION] = "section",
1287 [GNU_AK_FORMAT] = "format",
1288 [GNU_AK_FORMAT_ARG] = "format_arg",
1289 [GNU_AK_WEAKREF] = "weakref",
1290 [GNU_AK_NONNULL] = "nonnull",
1291 [GNU_AK_TLS_MODEL] = "tls_model",
1292 [GNU_AK_VISIBILITY] = "visibility",
1293 [GNU_AK_REGPARM] = "regparm",
1294 [GNU_AK_MODE] = "mode",
1295 [GNU_AK_MODEL] = "model",
1296 [GNU_AK_TRAP_EXIT] = "trap_exit",
1297 [GNU_AK_SP_SWITCH] = "sp_switch",
1298 [GNU_AK_SENTINEL] = "sentinel"
1302 * compare two string, ignoring double underscores on the second.
1304 static int strcmp_underscore(const char *s1, const char *s2)
1306 if (s2[0] == '_' && s2[1] == '_') {
1307 size_t len2 = strlen(s2);
1308 size_t len1 = strlen(s1);
1309 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1310 return strncmp(s1, s2+2, len2-4);
1314 return strcmp(s1, s2);
1318 * Allocate a new gnu temporal attribute.
1320 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1322 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1323 attribute->kind = kind;
1324 attribute->next = NULL;
1325 attribute->invalid = false;
1326 attribute->have_arguments = false;
1332 * parse one constant expression argument.
1334 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1336 expression_t *expression;
1337 add_anchor_token(')');
1338 expression = parse_constant_expression();
1339 rem_anchor_token(')');
1341 attribute->u.argument = fold_constant(expression);
1344 attribute->invalid = true;
1348 * parse a list of constant expressions arguments.
1350 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1352 argument_list_t **list = &attribute->u.arguments;
1353 argument_list_t *entry;
1354 expression_t *expression;
1355 add_anchor_token(')');
1356 add_anchor_token(',');
1358 expression = parse_constant_expression();
1359 entry = obstack_alloc(&temp_obst, sizeof(entry));
1360 entry->argument = fold_constant(expression);
1363 list = &entry->next;
1364 if (token.type != ',')
1368 rem_anchor_token(',');
1369 rem_anchor_token(')');
1373 attribute->invalid = true;
1377 * parse one string literal argument.
1379 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1382 add_anchor_token('(');
1383 if (token.type != T_STRING_LITERAL) {
1384 parse_error_expected("while parsing attribute directive",
1385 T_STRING_LITERAL, NULL);
1388 *string = parse_string_literals();
1389 rem_anchor_token('(');
1393 attribute->invalid = true;
1397 * parse one tls model.
1399 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1401 static const char *const tls_models[] = {
1407 string_t string = { NULL, 0 };
1408 parse_gnu_attribute_string_arg(attribute, &string);
1409 if (string.begin != NULL) {
1410 for(size_t i = 0; i < 4; ++i) {
1411 if (strcmp(tls_models[i], string.begin) == 0) {
1412 attribute->u.value = i;
1416 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1418 attribute->invalid = true;
1422 * parse one tls model.
1424 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1426 static const char *const visibilities[] = {
1432 string_t string = { NULL, 0 };
1433 parse_gnu_attribute_string_arg(attribute, &string);
1434 if (string.begin != NULL) {
1435 for(size_t i = 0; i < 4; ++i) {
1436 if (strcmp(visibilities[i], string.begin) == 0) {
1437 attribute->u.value = i;
1441 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1443 attribute->invalid = true;
1447 * parse one (code) model.
1449 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1451 static const char *const visibilities[] = {
1456 string_t string = { NULL, 0 };
1457 parse_gnu_attribute_string_arg(attribute, &string);
1458 if (string.begin != NULL) {
1459 for(int i = 0; i < 3; ++i) {
1460 if (strcmp(visibilities[i], string.begin) == 0) {
1461 attribute->u.value = i;
1465 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1467 attribute->invalid = true;
1470 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1472 /* TODO: find out what is allowed here... */
1474 /* at least: byte, word, pointer, list of machine modes
1475 * __XXX___ is interpreted as XXX */
1476 add_anchor_token(')');
1478 if (token.type != T_IDENTIFIER) {
1479 expect(T_IDENTIFIER);
1482 /* This isn't really correct, the backend should provide a list of machine
1483 * specific modes (according to gcc philosophy that is...) */
1484 const char *symbol_str = token.v.symbol->string;
1485 if (strcmp_underscore("QI", symbol_str) == 0 ||
1486 strcmp_underscore("byte", symbol_str) == 0) {
1487 attribute->u.akind = ATOMIC_TYPE_CHAR;
1488 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1489 attribute->u.akind = ATOMIC_TYPE_SHORT;
1490 } else if (strcmp_underscore("SI", symbol_str) == 0
1491 || strcmp_underscore("word", symbol_str) == 0
1492 || strcmp_underscore("pointer", symbol_str) == 0) {
1493 attribute->u.akind = ATOMIC_TYPE_INT;
1494 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1495 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1498 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1499 attribute->invalid = true;
1503 rem_anchor_token(')');
1507 attribute->invalid = true;
1511 * parse one interrupt argument.
1513 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1515 static const char *const interrupts[] = {
1522 string_t string = { NULL, 0 };
1523 parse_gnu_attribute_string_arg(attribute, &string);
1524 if (string.begin != NULL) {
1525 for(size_t i = 0; i < 5; ++i) {
1526 if (strcmp(interrupts[i], string.begin) == 0) {
1527 attribute->u.value = i;
1531 errorf(HERE, "'%s' is not an interrupt", string.begin);
1533 attribute->invalid = true;
1537 * parse ( identifier, const expression, const expression )
1539 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1541 static const char *const format_names[] = {
1549 if (token.type != T_IDENTIFIER) {
1550 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1553 const char *name = token.v.symbol->string;
1554 for(i = 0; i < 4; ++i) {
1555 if (strcmp_underscore(format_names[i], name) == 0)
1559 if (warning.attribute)
1560 warningf(HERE, "'%s' is an unrecognized format function type", name);
1565 add_anchor_token(')');
1566 add_anchor_token(',');
1567 parse_constant_expression();
1568 rem_anchor_token(',');
1569 rem_anchor_token(')');
1572 add_anchor_token(')');
1573 parse_constant_expression();
1574 rem_anchor_token(')');
1578 attribute->u.value = true;
1581 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1583 if (!attribute->have_arguments)
1586 /* should have no arguments */
1587 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1588 eat_until_matching_token('(');
1589 /* we have already consumed '(', so we stop before ')', eat it */
1591 attribute->invalid = true;
1595 * Parse one GNU attribute.
1597 * Note that attribute names can be specified WITH or WITHOUT
1598 * double underscores, ie const or __const__.
1600 * The following attributes are parsed without arguments
1625 * no_instrument_function
1626 * warn_unused_result
1643 * externally_visible
1651 * The following attributes are parsed with arguments
1652 * aligned( const expression )
1653 * alias( string literal )
1654 * section( string literal )
1655 * format( identifier, const expression, const expression )
1656 * format_arg( const expression )
1657 * tls_model( string literal )
1658 * visibility( string literal )
1659 * regparm( const expression )
1660 * model( string leteral )
1661 * trap_exit( const expression )
1662 * sp_switch( string literal )
1664 * The following attributes might have arguments
1665 * weak_ref( string literal )
1666 * non_null( const expression // ',' )
1667 * interrupt( string literal )
1668 * sentinel( constant expression )
1670 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1672 gnu_attribute_t *head = *attributes;
1673 gnu_attribute_t *last = *attributes;
1674 decl_modifiers_t modifiers = 0;
1675 gnu_attribute_t *attribute;
1677 eat(T___attribute__);
1681 if (token.type != ')') {
1682 /* find the end of the list */
1684 while (last->next != NULL)
1688 /* non-empty attribute list */
1691 if (token.type == T_const) {
1693 } else if (token.type == T_volatile) {
1695 } else if (token.type == T_cdecl) {
1696 /* __attribute__((cdecl)), WITH ms mode */
1698 } else if (token.type == T_IDENTIFIER) {
1699 const symbol_t *sym = token.v.symbol;
1702 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1709 for(i = 0; i < GNU_AK_LAST; ++i) {
1710 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1713 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1716 if (kind == GNU_AK_LAST) {
1717 if (warning.attribute)
1718 warningf(HERE, "'%s' attribute directive ignored", name);
1720 /* skip possible arguments */
1721 if (token.type == '(') {
1722 eat_until_matching_token(')');
1725 /* check for arguments */
1726 attribute = allocate_gnu_attribute(kind);
1727 if (token.type == '(') {
1729 if (token.type == ')') {
1730 /* empty args are allowed */
1733 attribute->have_arguments = true;
1737 case GNU_AK_VOLATILE:
1742 case GNU_AK_NOCOMMON:
1744 case GNU_AK_NOTSHARED:
1745 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1746 case GNU_AK_WARN_UNUSED_RESULT:
1747 case GNU_AK_LONGCALL:
1748 case GNU_AK_SHORTCALL:
1749 case GNU_AK_LONG_CALL:
1750 case GNU_AK_SHORT_CALL:
1751 case GNU_AK_FUNCTION_VECTOR:
1752 case GNU_AK_INTERRUPT_HANDLER:
1753 case GNU_AK_NMI_HANDLER:
1754 case GNU_AK_NESTING:
1758 case GNU_AK_EIGTHBIT_DATA:
1759 case GNU_AK_TINY_DATA:
1760 case GNU_AK_SAVEALL:
1761 case GNU_AK_FLATTEN:
1762 case GNU_AK_SSEREGPARM:
1763 case GNU_AK_EXTERNALLY_VISIBLE:
1764 case GNU_AK_RETURN_TWICE:
1765 case GNU_AK_MAY_ALIAS:
1766 case GNU_AK_MS_STRUCT:
1767 case GNU_AK_GCC_STRUCT:
1770 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1771 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1772 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1773 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1774 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1775 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1776 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1777 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1778 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1779 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1780 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1781 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1782 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1783 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1784 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1785 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1786 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1787 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1789 case GNU_AK_ALIGNED:
1790 /* __align__ may be used without an argument */
1791 if (attribute->have_arguments) {
1792 parse_gnu_attribute_const_arg(attribute);
1796 case GNU_AK_FORMAT_ARG:
1797 case GNU_AK_REGPARM:
1798 case GNU_AK_TRAP_EXIT:
1799 if (!attribute->have_arguments) {
1800 /* should have arguments */
1801 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1802 attribute->invalid = true;
1804 parse_gnu_attribute_const_arg(attribute);
1807 case GNU_AK_SECTION:
1808 case GNU_AK_SP_SWITCH:
1809 if (!attribute->have_arguments) {
1810 /* should have arguments */
1811 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1812 attribute->invalid = true;
1814 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1817 if (!attribute->have_arguments) {
1818 /* should have arguments */
1819 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1820 attribute->invalid = true;
1822 parse_gnu_attribute_format_args(attribute);
1824 case GNU_AK_WEAKREF:
1825 /* may have one string argument */
1826 if (attribute->have_arguments)
1827 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1829 case GNU_AK_NONNULL:
1830 if (attribute->have_arguments)
1831 parse_gnu_attribute_const_arg_list(attribute);
1833 case GNU_AK_TLS_MODEL:
1834 if (!attribute->have_arguments) {
1835 /* should have arguments */
1836 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1838 parse_gnu_attribute_tls_model_arg(attribute);
1840 case GNU_AK_VISIBILITY:
1841 if (!attribute->have_arguments) {
1842 /* should have arguments */
1843 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1845 parse_gnu_attribute_visibility_arg(attribute);
1848 if (!attribute->have_arguments) {
1849 /* should have arguments */
1850 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1852 parse_gnu_attribute_model_arg(attribute);
1856 if (!attribute->have_arguments) {
1857 /* should have arguments */
1858 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1860 parse_gnu_attribute_mode_arg(attribute);
1863 case GNU_AK_INTERRUPT:
1864 /* may have one string argument */
1865 if (attribute->have_arguments)
1866 parse_gnu_attribute_interrupt_arg(attribute);
1868 case GNU_AK_SENTINEL:
1869 /* may have one string argument */
1870 if (attribute->have_arguments)
1871 parse_gnu_attribute_const_arg(attribute);
1874 /* already handled */
1878 check_no_argument(attribute, name);
1881 if (attribute != NULL) {
1883 last->next = attribute;
1886 head = last = attribute;
1890 if (token.type != ',')
1904 * Parse GNU attributes.
1906 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1908 decl_modifiers_t modifiers = 0;
1911 switch (token.type) {
1912 case T___attribute__:
1913 modifiers |= parse_gnu_attribute(attributes);
1919 if (token.type != T_STRING_LITERAL) {
1920 parse_error_expected("while parsing assembler attribute",
1921 T_STRING_LITERAL, NULL);
1922 eat_until_matching_token('(');
1925 parse_string_literals();
1930 case T_cdecl: modifiers |= DM_CDECL; break;
1931 case T__fastcall: modifiers |= DM_FASTCALL; break;
1932 case T__stdcall: modifiers |= DM_STDCALL; break;
1935 /* TODO record modifier */
1937 warningf(HERE, "Ignoring declaration modifier %K", &token);
1941 default: return modifiers;
1948 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1950 static variable_t *determine_lhs_var(expression_t *const expr,
1951 variable_t *lhs_var)
1953 switch (expr->kind) {
1954 case EXPR_REFERENCE: {
1955 entity_t *const entity = expr->reference.entity;
1956 /* we should only find variables as lavlues... */
1957 if (entity->base.kind != ENTITY_VARIABLE)
1960 return &entity->variable;
1963 case EXPR_ARRAY_ACCESS: {
1964 expression_t *const ref = expr->array_access.array_ref;
1965 variable_t * var = NULL;
1966 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1967 var = determine_lhs_var(ref, lhs_var);
1970 mark_vars_read(expr->select.compound, lhs_var);
1972 mark_vars_read(expr->array_access.index, lhs_var);
1977 if (is_type_compound(skip_typeref(expr->base.type))) {
1978 return determine_lhs_var(expr->select.compound, lhs_var);
1980 mark_vars_read(expr->select.compound, lhs_var);
1985 case EXPR_UNARY_DEREFERENCE: {
1986 expression_t *const val = expr->unary.value;
1987 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1989 return determine_lhs_var(val->unary.value, lhs_var);
1991 mark_vars_read(val, NULL);
1997 mark_vars_read(expr, NULL);
2002 #define VAR_ANY ((variable_t*)-1)
2005 * Mark declarations, which are read. This is used to deted variables, which
2009 * x is not marked as "read", because it is only read to calculate its own new
2013 * x and y are not detected as "not read", because multiple variables are
2016 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
2018 switch (expr->kind) {
2019 case EXPR_REFERENCE: {
2020 entity_t *const entity = expr->reference.entity;
2021 if (entity->kind != ENTITY_VARIABLE)
2024 variable_t *variable = &entity->variable;
2025 if (lhs_var != variable && lhs_var != VAR_ANY) {
2026 variable->read = true;
2032 // TODO respect pure/const
2033 mark_vars_read(expr->call.function, NULL);
2034 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2035 mark_vars_read(arg->expression, NULL);
2039 case EXPR_CONDITIONAL:
2040 // TODO lhs_decl should depend on whether true/false have an effect
2041 mark_vars_read(expr->conditional.condition, NULL);
2042 if (expr->conditional.true_expression != NULL)
2043 mark_vars_read(expr->conditional.true_expression, lhs_var);
2044 mark_vars_read(expr->conditional.false_expression, lhs_var);
2048 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2050 mark_vars_read(expr->select.compound, lhs_var);
2053 case EXPR_ARRAY_ACCESS: {
2054 expression_t *const ref = expr->array_access.array_ref;
2055 mark_vars_read(ref, lhs_var);
2056 lhs_var = determine_lhs_var(ref, lhs_var);
2057 mark_vars_read(expr->array_access.index, lhs_var);
2062 mark_vars_read(expr->va_arge.ap, lhs_var);
2065 case EXPR_UNARY_CAST:
2066 /* Special case: Use void cast to mark a variable as "read" */
2067 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2072 case EXPR_UNARY_THROW:
2073 if (expr->unary.value == NULL)
2076 case EXPR_UNARY_DEREFERENCE:
2077 case EXPR_UNARY_DELETE:
2078 case EXPR_UNARY_DELETE_ARRAY:
2079 if (lhs_var == VAR_ANY)
2083 case EXPR_UNARY_NEGATE:
2084 case EXPR_UNARY_PLUS:
2085 case EXPR_UNARY_BITWISE_NEGATE:
2086 case EXPR_UNARY_NOT:
2087 case EXPR_UNARY_TAKE_ADDRESS:
2088 case EXPR_UNARY_POSTFIX_INCREMENT:
2089 case EXPR_UNARY_POSTFIX_DECREMENT:
2090 case EXPR_UNARY_PREFIX_INCREMENT:
2091 case EXPR_UNARY_PREFIX_DECREMENT:
2092 case EXPR_UNARY_CAST_IMPLICIT:
2093 case EXPR_UNARY_ASSUME:
2095 mark_vars_read(expr->unary.value, lhs_var);
2098 case EXPR_BINARY_ADD:
2099 case EXPR_BINARY_SUB:
2100 case EXPR_BINARY_MUL:
2101 case EXPR_BINARY_DIV:
2102 case EXPR_BINARY_MOD:
2103 case EXPR_BINARY_EQUAL:
2104 case EXPR_BINARY_NOTEQUAL:
2105 case EXPR_BINARY_LESS:
2106 case EXPR_BINARY_LESSEQUAL:
2107 case EXPR_BINARY_GREATER:
2108 case EXPR_BINARY_GREATEREQUAL:
2109 case EXPR_BINARY_BITWISE_AND:
2110 case EXPR_BINARY_BITWISE_OR:
2111 case EXPR_BINARY_BITWISE_XOR:
2112 case EXPR_BINARY_LOGICAL_AND:
2113 case EXPR_BINARY_LOGICAL_OR:
2114 case EXPR_BINARY_SHIFTLEFT:
2115 case EXPR_BINARY_SHIFTRIGHT:
2116 case EXPR_BINARY_COMMA:
2117 case EXPR_BINARY_ISGREATER:
2118 case EXPR_BINARY_ISGREATEREQUAL:
2119 case EXPR_BINARY_ISLESS:
2120 case EXPR_BINARY_ISLESSEQUAL:
2121 case EXPR_BINARY_ISLESSGREATER:
2122 case EXPR_BINARY_ISUNORDERED:
2123 mark_vars_read(expr->binary.left, lhs_var);
2124 mark_vars_read(expr->binary.right, lhs_var);
2127 case EXPR_BINARY_ASSIGN:
2128 case EXPR_BINARY_MUL_ASSIGN:
2129 case EXPR_BINARY_DIV_ASSIGN:
2130 case EXPR_BINARY_MOD_ASSIGN:
2131 case EXPR_BINARY_ADD_ASSIGN:
2132 case EXPR_BINARY_SUB_ASSIGN:
2133 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2134 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2135 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2136 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2137 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2138 if (lhs_var == VAR_ANY)
2140 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2141 mark_vars_read(expr->binary.right, lhs_var);
2146 determine_lhs_var(expr->va_starte.ap, lhs_var);
2152 case EXPR_CHARACTER_CONSTANT:
2153 case EXPR_WIDE_CHARACTER_CONSTANT:
2154 case EXPR_STRING_LITERAL:
2155 case EXPR_WIDE_STRING_LITERAL:
2156 case EXPR_COMPOUND_LITERAL: // TODO init?
2158 case EXPR_CLASSIFY_TYPE:
2161 case EXPR_BUILTIN_SYMBOL:
2162 case EXPR_BUILTIN_CONSTANT_P:
2163 case EXPR_BUILTIN_PREFETCH:
2165 case EXPR_STATEMENT: // TODO
2166 case EXPR_LABEL_ADDRESS:
2167 case EXPR_BINARY_BUILTIN_EXPECT:
2168 case EXPR_REFERENCE_ENUM_VALUE:
2172 panic("unhandled expression");
2175 static designator_t *parse_designation(void)
2177 designator_t *result = NULL;
2178 designator_t *last = NULL;
2181 designator_t *designator;
2182 switch (token.type) {
2184 designator = allocate_ast_zero(sizeof(designator[0]));
2185 designator->source_position = token.source_position;
2187 add_anchor_token(']');
2188 designator->array_index = parse_constant_expression();
2189 rem_anchor_token(']');
2193 designator = allocate_ast_zero(sizeof(designator[0]));
2194 designator->source_position = token.source_position;
2196 if (token.type != T_IDENTIFIER) {
2197 parse_error_expected("while parsing designator",
2198 T_IDENTIFIER, NULL);
2201 designator->symbol = token.v.symbol;
2209 assert(designator != NULL);
2211 last->next = designator;
2213 result = designator;
2221 static initializer_t *initializer_from_string(array_type_t *type,
2222 const string_t *const string)
2224 /* TODO: check len vs. size of array type */
2227 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2228 initializer->string.string = *string;
2233 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2234 wide_string_t *const string)
2236 /* TODO: check len vs. size of array type */
2239 initializer_t *const initializer =
2240 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2241 initializer->wide_string.string = *string;
2247 * Build an initializer from a given expression.
2249 static initializer_t *initializer_from_expression(type_t *orig_type,
2250 expression_t *expression)
2252 /* TODO check that expression is a constant expression */
2254 /* § 6.7.8.14/15 char array may be initialized by string literals */
2255 type_t *type = skip_typeref(orig_type);
2256 type_t *expr_type_orig = expression->base.type;
2257 type_t *expr_type = skip_typeref(expr_type_orig);
2258 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2259 array_type_t *const array_type = &type->array;
2260 type_t *const element_type = skip_typeref(array_type->element_type);
2262 if (element_type->kind == TYPE_ATOMIC) {
2263 atomic_type_kind_t akind = element_type->atomic.akind;
2264 switch (expression->kind) {
2265 case EXPR_STRING_LITERAL:
2266 if (akind == ATOMIC_TYPE_CHAR
2267 || akind == ATOMIC_TYPE_SCHAR
2268 || akind == ATOMIC_TYPE_UCHAR) {
2269 return initializer_from_string(array_type,
2270 &expression->string.value);
2273 case EXPR_WIDE_STRING_LITERAL: {
2274 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2275 if (get_unqualified_type(element_type) == bare_wchar_type) {
2276 return initializer_from_wide_string(array_type,
2277 &expression->wide_string.value);
2287 assign_error_t error = semantic_assign(type, expression);
2288 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2290 report_assign_error(error, type, expression, "initializer",
2291 &expression->base.source_position);
2293 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2295 if (type->kind == TYPE_BITFIELD) {
2296 type = type->bitfield.base_type;
2299 result->value.value = create_implicit_cast(expression, type);
2305 * Checks if a given expression can be used as an constant initializer.
2307 static bool is_initializer_constant(const expression_t *expression)
2309 return is_constant_expression(expression)
2310 || is_address_constant(expression);
2314 * Parses an scalar initializer.
2316 * § 6.7.8.11; eat {} without warning
2318 static initializer_t *parse_scalar_initializer(type_t *type,
2319 bool must_be_constant)
2321 /* there might be extra {} hierarchies */
2323 if (token.type == '{') {
2325 warningf(HERE, "extra curly braces around scalar initializer");
2329 } while (token.type == '{');
2332 expression_t *expression = parse_assignment_expression();
2333 mark_vars_read(expression, NULL);
2334 if (must_be_constant && !is_initializer_constant(expression)) {
2335 errorf(&expression->base.source_position,
2336 "Initialisation expression '%E' is not constant\n",
2340 initializer_t *initializer = initializer_from_expression(type, expression);
2342 if (initializer == NULL) {
2343 errorf(&expression->base.source_position,
2344 "expression '%E' (type '%T') doesn't match expected type '%T'",
2345 expression, expression->base.type, type);
2350 bool additional_warning_displayed = false;
2351 while (braces > 0) {
2352 if (token.type == ',') {
2355 if (token.type != '}') {
2356 if (!additional_warning_displayed && warning.other) {
2357 warningf(HERE, "additional elements in scalar initializer");
2358 additional_warning_displayed = true;
2369 * An entry in the type path.
2371 typedef struct type_path_entry_t type_path_entry_t;
2372 struct type_path_entry_t {
2373 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2375 size_t index; /**< For array types: the current index. */
2376 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2381 * A type path expression a position inside compound or array types.
2383 typedef struct type_path_t type_path_t;
2384 struct type_path_t {
2385 type_path_entry_t *path; /**< An flexible array containing the current path. */
2386 type_t *top_type; /**< type of the element the path points */
2387 size_t max_index; /**< largest index in outermost array */
2391 * Prints a type path for debugging.
2393 static __attribute__((unused)) void debug_print_type_path(
2394 const type_path_t *path)
2396 size_t len = ARR_LEN(path->path);
2398 for(size_t i = 0; i < len; ++i) {
2399 const type_path_entry_t *entry = & path->path[i];
2401 type_t *type = skip_typeref(entry->type);
2402 if (is_type_compound(type)) {
2403 /* in gcc mode structs can have no members */
2404 if (entry->v.compound_entry == NULL) {
2408 fprintf(stderr, ".%s",
2409 entry->v.compound_entry->base.symbol->string);
2410 } else if (is_type_array(type)) {
2411 fprintf(stderr, "[%zu]", entry->v.index);
2413 fprintf(stderr, "-INVALID-");
2416 if (path->top_type != NULL) {
2417 fprintf(stderr, " (");
2418 print_type(path->top_type);
2419 fprintf(stderr, ")");
2424 * Return the top type path entry, ie. in a path
2425 * (type).a.b returns the b.
2427 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2429 size_t len = ARR_LEN(path->path);
2431 return &path->path[len-1];
2435 * Enlarge the type path by an (empty) element.
2437 static type_path_entry_t *append_to_type_path(type_path_t *path)
2439 size_t len = ARR_LEN(path->path);
2440 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2442 type_path_entry_t *result = & path->path[len];
2443 memset(result, 0, sizeof(result[0]));
2448 * Descending into a sub-type. Enter the scope of the current top_type.
2450 static void descend_into_subtype(type_path_t *path)
2452 type_t *orig_top_type = path->top_type;
2453 type_t *top_type = skip_typeref(orig_top_type);
2455 type_path_entry_t *top = append_to_type_path(path);
2456 top->type = top_type;
2458 if (is_type_compound(top_type)) {
2459 compound_t *compound = top_type->compound.compound;
2460 entity_t *entry = compound->members.entities;
2462 if (entry != NULL) {
2463 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2464 top->v.compound_entry = &entry->declaration;
2465 path->top_type = entry->declaration.type;
2467 path->top_type = NULL;
2469 } else if (is_type_array(top_type)) {
2471 path->top_type = top_type->array.element_type;
2473 assert(!is_type_valid(top_type));
2478 * Pop an entry from the given type path, ie. returning from
2479 * (type).a.b to (type).a
2481 static void ascend_from_subtype(type_path_t *path)
2483 type_path_entry_t *top = get_type_path_top(path);
2485 path->top_type = top->type;
2487 size_t len = ARR_LEN(path->path);
2488 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2492 * Pop entries from the given type path until the given
2493 * path level is reached.
2495 static void ascend_to(type_path_t *path, size_t top_path_level)
2497 size_t len = ARR_LEN(path->path);
2499 while (len > top_path_level) {
2500 ascend_from_subtype(path);
2501 len = ARR_LEN(path->path);
2505 static bool walk_designator(type_path_t *path, const designator_t *designator,
2506 bool used_in_offsetof)
2508 for( ; designator != NULL; designator = designator->next) {
2509 type_path_entry_t *top = get_type_path_top(path);
2510 type_t *orig_type = top->type;
2512 type_t *type = skip_typeref(orig_type);
2514 if (designator->symbol != NULL) {
2515 symbol_t *symbol = designator->symbol;
2516 if (!is_type_compound(type)) {
2517 if (is_type_valid(type)) {
2518 errorf(&designator->source_position,
2519 "'.%Y' designator used for non-compound type '%T'",
2523 top->type = type_error_type;
2524 top->v.compound_entry = NULL;
2525 orig_type = type_error_type;
2527 compound_t *compound = type->compound.compound;
2528 entity_t *iter = compound->members.entities;
2529 for( ; iter != NULL; iter = iter->base.next) {
2530 if (iter->base.symbol == symbol) {
2535 errorf(&designator->source_position,
2536 "'%T' has no member named '%Y'", orig_type, symbol);
2539 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2540 if (used_in_offsetof) {
2541 type_t *real_type = skip_typeref(iter->declaration.type);
2542 if (real_type->kind == TYPE_BITFIELD) {
2543 errorf(&designator->source_position,
2544 "offsetof designator '%Y' may not specify bitfield",
2550 top->type = orig_type;
2551 top->v.compound_entry = &iter->declaration;
2552 orig_type = iter->declaration.type;
2555 expression_t *array_index = designator->array_index;
2556 assert(designator->array_index != NULL);
2558 if (!is_type_array(type)) {
2559 if (is_type_valid(type)) {
2560 errorf(&designator->source_position,
2561 "[%E] designator used for non-array type '%T'",
2562 array_index, orig_type);
2567 long index = fold_constant(array_index);
2568 if (!used_in_offsetof) {
2570 errorf(&designator->source_position,
2571 "array index [%E] must be positive", array_index);
2572 } else if (type->array.size_constant) {
2573 long array_size = type->array.size;
2574 if (index >= array_size) {
2575 errorf(&designator->source_position,
2576 "designator [%E] (%d) exceeds array size %d",
2577 array_index, index, array_size);
2582 top->type = orig_type;
2583 top->v.index = (size_t) index;
2584 orig_type = type->array.element_type;
2586 path->top_type = orig_type;
2588 if (designator->next != NULL) {
2589 descend_into_subtype(path);
2598 static void advance_current_object(type_path_t *path, size_t top_path_level)
2600 type_path_entry_t *top = get_type_path_top(path);
2602 type_t *type = skip_typeref(top->type);
2603 if (is_type_union(type)) {
2604 /* in unions only the first element is initialized */
2605 top->v.compound_entry = NULL;
2606 } else if (is_type_struct(type)) {
2607 declaration_t *entry = top->v.compound_entry;
2609 entity_t *next_entity = entry->base.next;
2610 if (next_entity != NULL) {
2611 assert(is_declaration(next_entity));
2612 entry = &next_entity->declaration;
2617 top->v.compound_entry = entry;
2618 if (entry != NULL) {
2619 path->top_type = entry->type;
2622 } else if (is_type_array(type)) {
2623 assert(is_type_array(type));
2627 if (!type->array.size_constant || top->v.index < type->array.size) {
2631 assert(!is_type_valid(type));
2635 /* we're past the last member of the current sub-aggregate, try if we
2636 * can ascend in the type hierarchy and continue with another subobject */
2637 size_t len = ARR_LEN(path->path);
2639 if (len > top_path_level) {
2640 ascend_from_subtype(path);
2641 advance_current_object(path, top_path_level);
2643 path->top_type = NULL;
2648 * skip until token is found.
2650 static void skip_until(int type)
2652 while (token.type != type) {
2653 if (token.type == T_EOF)
2660 * skip any {...} blocks until a closing bracket is reached.
2662 static void skip_initializers(void)
2664 if (token.type == '{')
2667 while (token.type != '}') {
2668 if (token.type == T_EOF)
2670 if (token.type == '{') {
2678 static initializer_t *create_empty_initializer(void)
2680 static initializer_t empty_initializer
2681 = { .list = { { INITIALIZER_LIST }, 0 } };
2682 return &empty_initializer;
2686 * Parse a part of an initialiser for a struct or union,
2688 static initializer_t *parse_sub_initializer(type_path_t *path,
2689 type_t *outer_type, size_t top_path_level,
2690 parse_initializer_env_t *env)
2692 if (token.type == '}') {
2693 /* empty initializer */
2694 return create_empty_initializer();
2697 type_t *orig_type = path->top_type;
2698 type_t *type = NULL;
2700 if (orig_type == NULL) {
2701 /* We are initializing an empty compound. */
2703 type = skip_typeref(orig_type);
2706 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2709 designator_t *designator = NULL;
2710 if (token.type == '.' || token.type == '[') {
2711 designator = parse_designation();
2712 goto finish_designator;
2713 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2714 /* GNU-style designator ("identifier: value") */
2715 designator = allocate_ast_zero(sizeof(designator[0]));
2716 designator->source_position = token.source_position;
2717 designator->symbol = token.v.symbol;
2722 /* reset path to toplevel, evaluate designator from there */
2723 ascend_to(path, top_path_level);
2724 if (!walk_designator(path, designator, false)) {
2725 /* can't continue after designation error */
2729 initializer_t *designator_initializer
2730 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2731 designator_initializer->designator.designator = designator;
2732 ARR_APP1(initializer_t*, initializers, designator_initializer);
2734 orig_type = path->top_type;
2735 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2740 if (token.type == '{') {
2741 if (type != NULL && is_type_scalar(type)) {
2742 sub = parse_scalar_initializer(type, env->must_be_constant);
2746 if (env->entity != NULL) {
2748 "extra brace group at end of initializer for '%Y'",
2749 env->entity->base.symbol);
2751 errorf(HERE, "extra brace group at end of initializer");
2754 descend_into_subtype(path);
2756 add_anchor_token('}');
2757 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2759 rem_anchor_token('}');
2762 ascend_from_subtype(path);
2766 goto error_parse_next;
2770 /* must be an expression */
2771 expression_t *expression = parse_assignment_expression();
2773 if (env->must_be_constant && !is_initializer_constant(expression)) {
2774 errorf(&expression->base.source_position,
2775 "Initialisation expression '%E' is not constant\n",
2780 /* we are already outside, ... */
2781 type_t *const outer_type_skip = skip_typeref(outer_type);
2782 if (is_type_compound(outer_type_skip) &&
2783 !outer_type_skip->compound.compound->complete) {
2784 goto error_parse_next;
2789 /* handle { "string" } special case */
2790 if ((expression->kind == EXPR_STRING_LITERAL
2791 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2792 && outer_type != NULL) {
2793 sub = initializer_from_expression(outer_type, expression);
2795 if (token.type == ',') {
2798 if (token.type != '}' && warning.other) {
2799 warningf(HERE, "excessive elements in initializer for type '%T'",
2802 /* TODO: eat , ... */
2807 /* descend into subtypes until expression matches type */
2809 orig_type = path->top_type;
2810 type = skip_typeref(orig_type);
2812 sub = initializer_from_expression(orig_type, expression);
2816 if (!is_type_valid(type)) {
2819 if (is_type_scalar(type)) {
2820 errorf(&expression->base.source_position,
2821 "expression '%E' doesn't match expected type '%T'",
2822 expression, orig_type);
2826 descend_into_subtype(path);
2830 /* update largest index of top array */
2831 const type_path_entry_t *first = &path->path[0];
2832 type_t *first_type = first->type;
2833 first_type = skip_typeref(first_type);
2834 if (is_type_array(first_type)) {
2835 size_t index = first->v.index;
2836 if (index > path->max_index)
2837 path->max_index = index;
2841 /* append to initializers list */
2842 ARR_APP1(initializer_t*, initializers, sub);
2845 if (warning.other) {
2846 if (env->entity != NULL) {
2847 warningf(HERE, "excess elements in struct initializer for '%Y'",
2848 env->entity->base.symbol);
2850 warningf(HERE, "excess elements in struct initializer");
2856 if (token.type == '}') {
2860 if (token.type == '}') {
2865 /* advance to the next declaration if we are not at the end */
2866 advance_current_object(path, top_path_level);
2867 orig_type = path->top_type;
2868 if (orig_type != NULL)
2869 type = skip_typeref(orig_type);
2875 size_t len = ARR_LEN(initializers);
2876 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2877 initializer_t *result = allocate_ast_zero(size);
2878 result->kind = INITIALIZER_LIST;
2879 result->list.len = len;
2880 memcpy(&result->list.initializers, initializers,
2881 len * sizeof(initializers[0]));
2883 DEL_ARR_F(initializers);
2884 ascend_to(path, top_path_level+1);
2889 skip_initializers();
2890 DEL_ARR_F(initializers);
2891 ascend_to(path, top_path_level+1);
2896 * Parses an initializer. Parsers either a compound literal
2897 * (env->declaration == NULL) or an initializer of a declaration.
2899 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2901 type_t *type = skip_typeref(env->type);
2902 initializer_t *result = NULL;
2905 if (is_type_scalar(type)) {
2906 result = parse_scalar_initializer(type, env->must_be_constant);
2907 } else if (token.type == '{') {
2911 memset(&path, 0, sizeof(path));
2912 path.top_type = env->type;
2913 path.path = NEW_ARR_F(type_path_entry_t, 0);
2915 descend_into_subtype(&path);
2917 add_anchor_token('}');
2918 result = parse_sub_initializer(&path, env->type, 1, env);
2919 rem_anchor_token('}');
2921 max_index = path.max_index;
2922 DEL_ARR_F(path.path);
2926 /* parse_scalar_initializer() also works in this case: we simply
2927 * have an expression without {} around it */
2928 result = parse_scalar_initializer(type, env->must_be_constant);
2931 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2932 * the array type size */
2933 if (is_type_array(type) && type->array.size_expression == NULL
2934 && result != NULL) {
2936 switch (result->kind) {
2937 case INITIALIZER_LIST:
2938 size = max_index + 1;
2941 case INITIALIZER_STRING:
2942 size = result->string.string.size;
2945 case INITIALIZER_WIDE_STRING:
2946 size = result->wide_string.string.size;
2949 case INITIALIZER_DESIGNATOR:
2950 case INITIALIZER_VALUE:
2951 /* can happen for parse errors */
2956 internal_errorf(HERE, "invalid initializer type");
2959 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2960 cnst->base.type = type_size_t;
2961 cnst->conste.v.int_value = size;
2963 type_t *new_type = duplicate_type(type);
2965 new_type->array.size_expression = cnst;
2966 new_type->array.size_constant = true;
2967 new_type->array.has_implicit_size = true;
2968 new_type->array.size = size;
2969 env->type = new_type;
2977 static void append_entity(scope_t *scope, entity_t *entity)
2979 if (scope->last_entity != NULL) {
2980 scope->last_entity->base.next = entity;
2982 scope->entities = entity;
2984 scope->last_entity = entity;
2988 static compound_t *parse_compound_type_specifier(bool is_struct)
2990 gnu_attribute_t *attributes = NULL;
2991 decl_modifiers_t modifiers = 0;
2998 symbol_t *symbol = NULL;
2999 compound_t *compound = NULL;
3001 if (token.type == T___attribute__) {
3002 modifiers |= parse_attributes(&attributes);
3005 if (token.type == T_IDENTIFIER) {
3006 symbol = token.v.symbol;
3009 namespace_t const namespc =
3010 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3011 entity_t *entity = get_entity(symbol, namespc);
3012 if (entity != NULL) {
3013 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3014 compound = &entity->compound;
3015 if (compound->base.parent_scope != scope &&
3016 (token.type == '{' || token.type == ';')) {
3017 /* we're in an inner scope and have a definition. Override
3018 existing definition in outer scope */
3020 } else if (compound->complete && token.type == '{') {
3021 assert(symbol != NULL);
3022 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3023 is_struct ? "struct" : "union", symbol,
3024 &compound->base.source_position);
3025 /* clear members in the hope to avoid further errors */
3026 compound->members.entities = NULL;
3029 } else if (token.type != '{') {
3031 parse_error_expected("while parsing struct type specifier",
3032 T_IDENTIFIER, '{', NULL);
3034 parse_error_expected("while parsing union type specifier",
3035 T_IDENTIFIER, '{', NULL);
3041 if (compound == NULL) {
3042 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3043 entity_t *entity = allocate_entity_zero(kind);
3044 compound = &entity->compound;
3046 compound->base.namespc =
3047 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3048 compound->base.source_position = token.source_position;
3049 compound->base.symbol = symbol;
3050 compound->base.parent_scope = scope;
3051 if (symbol != NULL) {
3052 environment_push(entity);
3054 append_entity(scope, entity);
3057 if (token.type == '{') {
3058 compound->complete = true;
3060 parse_compound_type_entries(compound);
3061 modifiers |= parse_attributes(&attributes);
3064 compound->modifiers |= modifiers;
3068 static void parse_enum_entries(type_t *const enum_type)
3072 if (token.type == '}') {
3074 errorf(HERE, "empty enum not allowed");
3078 add_anchor_token('}');
3080 if (token.type != T_IDENTIFIER) {
3081 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3083 rem_anchor_token('}');
3087 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3088 entity->enum_value.enum_type = enum_type;
3089 entity->base.symbol = token.v.symbol;
3090 entity->base.source_position = token.source_position;
3093 if (token.type == '=') {
3095 expression_t *value = parse_constant_expression();
3097 value = create_implicit_cast(value, enum_type);
3098 entity->enum_value.value = value;
3103 record_entity(entity, false);
3105 if (token.type != ',')
3108 } while (token.type != '}');
3109 rem_anchor_token('}');
3117 static type_t *parse_enum_specifier(void)
3119 gnu_attribute_t *attributes = NULL;
3124 if (token.type == T_IDENTIFIER) {
3125 symbol = token.v.symbol;
3128 entity = get_entity(symbol, NAMESPACE_ENUM);
3129 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3130 } else if (token.type != '{') {
3131 parse_error_expected("while parsing enum type specifier",
3132 T_IDENTIFIER, '{', NULL);
3139 if (entity == NULL) {
3140 entity = allocate_entity_zero(ENTITY_ENUM);
3141 entity->base.namespc = NAMESPACE_ENUM;
3142 entity->base.source_position = token.source_position;
3143 entity->base.symbol = symbol;
3144 entity->base.parent_scope = scope;
3147 type_t *const type = allocate_type_zero(TYPE_ENUM);
3148 type->enumt.enume = &entity->enume;
3150 if (token.type == '{') {
3151 if (entity->enume.complete) {
3152 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3153 symbol, &entity->base.source_position);
3155 if (symbol != NULL) {
3156 environment_push(entity);
3158 append_entity(scope, entity);
3159 entity->enume.complete = true;
3161 parse_enum_entries(type);
3162 parse_attributes(&attributes);
3163 } else if(!entity->enume.complete && !(c_mode & _GNUC)) {
3164 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3172 * if a symbol is a typedef to another type, return true
3174 static bool is_typedef_symbol(symbol_t *symbol)
3176 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3177 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3180 static type_t *parse_typeof(void)
3187 add_anchor_token(')');
3189 expression_t *expression = NULL;
3191 bool old_type_prop = in_type_prop;
3192 bool old_gcc_extension = in_gcc_extension;
3193 in_type_prop = true;
3195 while (token.type == T___extension__) {
3196 /* This can be a prefix to a typename or an expression. */
3198 in_gcc_extension = true;
3200 switch (token.type) {
3202 if (is_typedef_symbol(token.v.symbol)) {
3203 type = parse_typename();
3205 expression = parse_expression();
3206 type = expression->base.type;
3211 type = parse_typename();
3215 expression = parse_expression();
3216 type = expression->base.type;
3219 in_type_prop = old_type_prop;
3220 in_gcc_extension = old_gcc_extension;
3222 rem_anchor_token(')');
3225 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3226 typeof_type->typeoft.expression = expression;
3227 typeof_type->typeoft.typeof_type = type;
3234 typedef enum specifiers_t {
3235 SPECIFIER_SIGNED = 1 << 0,
3236 SPECIFIER_UNSIGNED = 1 << 1,
3237 SPECIFIER_LONG = 1 << 2,
3238 SPECIFIER_INT = 1 << 3,
3239 SPECIFIER_DOUBLE = 1 << 4,
3240 SPECIFIER_CHAR = 1 << 5,
3241 SPECIFIER_SHORT = 1 << 6,
3242 SPECIFIER_LONG_LONG = 1 << 7,
3243 SPECIFIER_FLOAT = 1 << 8,
3244 SPECIFIER_BOOL = 1 << 9,
3245 SPECIFIER_VOID = 1 << 10,
3246 SPECIFIER_INT8 = 1 << 11,
3247 SPECIFIER_INT16 = 1 << 12,
3248 SPECIFIER_INT32 = 1 << 13,
3249 SPECIFIER_INT64 = 1 << 14,
3250 SPECIFIER_INT128 = 1 << 15,
3251 SPECIFIER_COMPLEX = 1 << 16,
3252 SPECIFIER_IMAGINARY = 1 << 17,
3255 static type_t *create_builtin_type(symbol_t *const symbol,
3256 type_t *const real_type)
3258 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3259 type->builtin.symbol = symbol;
3260 type->builtin.real_type = real_type;
3262 type_t *result = typehash_insert(type);
3263 if (type != result) {
3270 static type_t *get_typedef_type(symbol_t *symbol)
3272 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3273 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3276 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3277 type->typedeft.typedefe = &entity->typedefe;
3283 * check for the allowed MS alignment values.
3285 static bool check_alignment_value(long long intvalue)
3287 if (intvalue < 1 || intvalue > 8192) {
3288 errorf(HERE, "illegal alignment value");
3291 unsigned v = (unsigned)intvalue;
3292 for (unsigned i = 1; i <= 8192; i += i) {
3296 errorf(HERE, "alignment must be power of two");
3300 #define DET_MOD(name, tag) do { \
3301 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3302 *modifiers |= tag; \
3305 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3307 decl_modifiers_t *modifiers = &specifiers->modifiers;
3310 if (token.type == T_restrict) {
3312 DET_MOD(restrict, DM_RESTRICT);
3314 } else if (token.type != T_IDENTIFIER)
3316 symbol_t *symbol = token.v.symbol;
3317 if (symbol == sym_align) {
3320 if (token.type != T_INTEGER)
3322 if (check_alignment_value(token.v.intvalue)) {
3323 if (specifiers->alignment != 0 && warning.other)
3324 warningf(HERE, "align used more than once");
3325 specifiers->alignment = (unsigned char)token.v.intvalue;
3329 } else if (symbol == sym_allocate) {
3332 if (token.type != T_IDENTIFIER)
3334 (void)token.v.symbol;
3336 } else if (symbol == sym_dllimport) {
3338 DET_MOD(dllimport, DM_DLLIMPORT);
3339 } else if (symbol == sym_dllexport) {
3341 DET_MOD(dllexport, DM_DLLEXPORT);
3342 } else if (symbol == sym_thread) {
3344 DET_MOD(thread, DM_THREAD);
3345 } else if (symbol == sym_naked) {
3347 DET_MOD(naked, DM_NAKED);
3348 } else if (symbol == sym_noinline) {
3350 DET_MOD(noinline, DM_NOINLINE);
3351 } else if (symbol == sym_noreturn) {
3353 DET_MOD(noreturn, DM_NORETURN);
3354 } else if (symbol == sym_nothrow) {
3356 DET_MOD(nothrow, DM_NOTHROW);
3357 } else if (symbol == sym_novtable) {
3359 DET_MOD(novtable, DM_NOVTABLE);
3360 } else if (symbol == sym_property) {
3364 bool is_get = false;
3365 if (token.type != T_IDENTIFIER)
3367 if (token.v.symbol == sym_get) {
3369 } else if (token.v.symbol == sym_put) {
3371 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3376 if (token.type != T_IDENTIFIER)
3379 if (specifiers->get_property_sym != NULL) {
3380 errorf(HERE, "get property name already specified");
3382 specifiers->get_property_sym = token.v.symbol;
3385 if (specifiers->put_property_sym != NULL) {
3386 errorf(HERE, "put property name already specified");
3388 specifiers->put_property_sym = token.v.symbol;
3392 if (token.type == ',') {
3399 } else if (symbol == sym_selectany) {
3401 DET_MOD(selectany, DM_SELECTANY);
3402 } else if (symbol == sym_uuid) {
3405 if (token.type != T_STRING_LITERAL)
3409 } else if (symbol == sym_deprecated) {
3411 if (specifiers->deprecated != 0 && warning.other)
3412 warningf(HERE, "deprecated used more than once");
3413 specifiers->deprecated = true;
3414 if (token.type == '(') {
3416 if (token.type == T_STRING_LITERAL) {
3417 specifiers->deprecated_string = token.v.string.begin;
3420 errorf(HERE, "string literal expected");
3424 } else if (symbol == sym_noalias) {
3426 DET_MOD(noalias, DM_NOALIAS);
3429 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3431 if (token.type == '(')
3435 if (token.type == ',')
3442 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3444 entity_t *entity = allocate_entity_zero(kind);
3445 entity->base.source_position = *HERE;
3446 entity->base.symbol = symbol;
3447 if (is_declaration(entity)) {
3448 entity->declaration.type = type_error_type;
3449 entity->declaration.implicit = true;
3450 } else if (kind == ENTITY_TYPEDEF) {
3451 entity->typedefe.type = type_error_type;
3453 record_entity(entity, false);
3458 * Finish the construction of a struct type by calculating
3459 * its size, offsets, alignment.
3461 static void finish_struct_type(compound_type_t *type)
3463 assert(type->compound != NULL);
3465 compound_t *compound = type->compound;
3466 if (!compound->complete)
3471 il_alignment_t alignment = 1;
3472 bool need_pad = false;
3474 entity_t *entry = compound->members.entities;
3475 for (; entry != NULL; entry = entry->base.next) {
3476 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3479 type_t *m_type = skip_typeref(entry->declaration.type);
3480 if (! is_type_valid(m_type)) {
3481 /* simply ignore errors here */
3484 il_alignment_t m_alignment = m_type->base.alignment;
3485 if (m_alignment > alignment)
3486 alignment = m_alignment;
3488 offset = (size + m_alignment - 1) & -m_alignment;
3492 entry->compound_member.offset = offset;
3493 size = offset + m_type->base.size;
3495 if (type->base.alignment != 0) {
3496 alignment = type->base.alignment;
3499 offset = (size + alignment - 1) & -alignment;
3503 if (warning.padded && need_pad) {
3504 warningf(&compound->base.source_position,
3505 "'%#T' needs padding", type, compound->base.symbol);
3507 if (warning.packed && !need_pad) {
3508 warningf(&compound->base.source_position,
3509 "superfluous packed attribute on '%#T'",
3510 type, compound->base.symbol);
3513 type->base.size = offset;
3514 type->base.alignment = alignment;
3518 * Finish the construction of an union type by calculating
3519 * its size and alignment.
3521 static void finish_union_type(compound_type_t *type)
3523 assert(type->compound != NULL);
3525 compound_t *compound = type->compound;
3526 if (! compound->complete)
3530 il_alignment_t alignment = 1;
3532 entity_t *entry = compound->members.entities;
3533 for (; entry != NULL; entry = entry->base.next) {
3534 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3537 type_t *m_type = skip_typeref(entry->declaration.type);
3538 if (! is_type_valid(m_type))
3541 entry->compound_member.offset = 0;
3542 if (m_type->base.size > size)
3543 size = m_type->base.size;
3544 if (m_type->base.alignment > alignment)
3545 alignment = m_type->base.alignment;
3547 if (type->base.alignment != 0) {
3548 alignment = type->base.alignment;
3550 size = (size + alignment - 1) & -alignment;
3551 type->base.size = size;
3552 type->base.alignment = alignment;
3555 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3557 type_t *type = NULL;
3558 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3559 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3560 unsigned type_specifiers = 0;
3561 bool newtype = false;
3562 bool saw_error = false;
3563 bool old_gcc_extension = in_gcc_extension;
3565 specifiers->source_position = token.source_position;
3568 specifiers->modifiers
3569 |= parse_attributes(&specifiers->gnu_attributes);
3570 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3571 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3573 switch (token.type) {
3576 #define MATCH_STORAGE_CLASS(token, class) \
3578 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3579 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3581 specifiers->storage_class = class; \
3585 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3586 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3587 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3588 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3589 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3594 add_anchor_token(')');
3595 parse_microsoft_extended_decl_modifier(specifiers);
3596 rem_anchor_token(')');
3601 switch (specifiers->storage_class) {
3602 case STORAGE_CLASS_NONE:
3603 specifiers->storage_class = STORAGE_CLASS_THREAD;
3606 case STORAGE_CLASS_EXTERN:
3607 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3610 case STORAGE_CLASS_STATIC:
3611 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3615 errorf(HERE, "multiple storage classes in declaration specifiers");
3621 /* type qualifiers */
3622 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3624 qualifiers |= qualifier; \
3628 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3629 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3630 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3631 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3632 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3633 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3634 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3635 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3637 case T___extension__:
3639 in_gcc_extension = true;
3642 /* type specifiers */
3643 #define MATCH_SPECIFIER(token, specifier, name) \
3646 if (type_specifiers & specifier) { \
3647 errorf(HERE, "multiple " name " type specifiers given"); \
3649 type_specifiers |= specifier; \
3653 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3654 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3655 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3656 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3657 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3658 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3659 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3660 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3661 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3662 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3663 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3664 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3665 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3666 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3667 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3668 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3669 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3671 case T__forceinline:
3672 /* only in microsoft mode */
3673 specifiers->modifiers |= DM_FORCEINLINE;
3678 specifiers->is_inline = true;
3683 if (type_specifiers & SPECIFIER_LONG_LONG) {
3684 errorf(HERE, "multiple type specifiers given");
3685 } else if (type_specifiers & SPECIFIER_LONG) {
3686 type_specifiers |= SPECIFIER_LONG_LONG;
3688 type_specifiers |= SPECIFIER_LONG;
3693 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3695 type->compound.compound = parse_compound_type_specifier(true);
3696 finish_struct_type(&type->compound);
3700 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3701 type->compound.compound = parse_compound_type_specifier(false);
3702 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3703 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3704 finish_union_type(&type->compound);
3708 type = parse_enum_specifier();
3711 type = parse_typeof();
3713 case T___builtin_va_list:
3714 type = duplicate_type(type_valist);
3718 case T_IDENTIFIER: {
3719 /* only parse identifier if we haven't found a type yet */
3720 if (type != NULL || type_specifiers != 0) {
3721 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3722 * declaration, so it doesn't generate errors about expecting '(' or
3724 switch (look_ahead(1)->type) {
3731 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3734 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3739 goto finish_specifiers;
3743 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3744 if (typedef_type == NULL) {
3745 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3746 * declaration, so it doesn't generate 'implicit int' followed by more
3747 * errors later on. */
3748 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3753 errorf(HERE, "%K does not name a type", &token);
3756 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3758 type = allocate_type_zero(TYPE_TYPEDEF);
3759 type->typedeft.typedefe = &entity->typedefe;
3763 if (la1_type == '*')
3764 goto finish_specifiers;
3769 goto finish_specifiers;
3774 type = typedef_type;
3778 /* function specifier */
3780 goto finish_specifiers;
3785 in_gcc_extension = old_gcc_extension;
3787 if (type == NULL || (saw_error && type_specifiers != 0)) {
3788 atomic_type_kind_t atomic_type;
3790 /* match valid basic types */
3791 switch (type_specifiers) {
3792 case SPECIFIER_VOID:
3793 atomic_type = ATOMIC_TYPE_VOID;
3795 case SPECIFIER_CHAR:
3796 atomic_type = ATOMIC_TYPE_CHAR;
3798 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3799 atomic_type = ATOMIC_TYPE_SCHAR;
3801 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3802 atomic_type = ATOMIC_TYPE_UCHAR;
3804 case SPECIFIER_SHORT:
3805 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3806 case SPECIFIER_SHORT | SPECIFIER_INT:
3807 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3808 atomic_type = ATOMIC_TYPE_SHORT;
3810 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3811 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3812 atomic_type = ATOMIC_TYPE_USHORT;
3815 case SPECIFIER_SIGNED:
3816 case SPECIFIER_SIGNED | SPECIFIER_INT:
3817 atomic_type = ATOMIC_TYPE_INT;
3819 case SPECIFIER_UNSIGNED:
3820 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3821 atomic_type = ATOMIC_TYPE_UINT;
3823 case SPECIFIER_LONG:
3824 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3825 case SPECIFIER_LONG | SPECIFIER_INT:
3826 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3827 atomic_type = ATOMIC_TYPE_LONG;
3829 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3830 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3831 atomic_type = ATOMIC_TYPE_ULONG;
3834 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3835 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3836 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3837 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3839 atomic_type = ATOMIC_TYPE_LONGLONG;
3840 goto warn_about_long_long;
3842 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3843 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3845 atomic_type = ATOMIC_TYPE_ULONGLONG;
3846 warn_about_long_long:
3847 if (warning.long_long) {
3848 warningf(&specifiers->source_position,
3849 "ISO C90 does not support 'long long'");
3853 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3854 atomic_type = unsigned_int8_type_kind;
3857 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3858 atomic_type = unsigned_int16_type_kind;
3861 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3862 atomic_type = unsigned_int32_type_kind;
3865 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3866 atomic_type = unsigned_int64_type_kind;
3869 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3870 atomic_type = unsigned_int128_type_kind;
3873 case SPECIFIER_INT8:
3874 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3875 atomic_type = int8_type_kind;
3878 case SPECIFIER_INT16:
3879 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3880 atomic_type = int16_type_kind;
3883 case SPECIFIER_INT32:
3884 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3885 atomic_type = int32_type_kind;
3888 case SPECIFIER_INT64:
3889 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3890 atomic_type = int64_type_kind;
3893 case SPECIFIER_INT128:
3894 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3895 atomic_type = int128_type_kind;
3898 case SPECIFIER_FLOAT:
3899 atomic_type = ATOMIC_TYPE_FLOAT;
3901 case SPECIFIER_DOUBLE:
3902 atomic_type = ATOMIC_TYPE_DOUBLE;
3904 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3905 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3907 case SPECIFIER_BOOL:
3908 atomic_type = ATOMIC_TYPE_BOOL;
3910 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3911 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3912 atomic_type = ATOMIC_TYPE_FLOAT;
3914 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3915 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3916 atomic_type = ATOMIC_TYPE_DOUBLE;
3918 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3919 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3920 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3923 /* invalid specifier combination, give an error message */
3924 if (type_specifiers == 0) {
3928 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3929 if (!(c_mode & _CXX) && !strict_mode) {
3930 if (warning.implicit_int) {
3931 warningf(HERE, "no type specifiers in declaration, using 'int'");
3933 atomic_type = ATOMIC_TYPE_INT;
3936 errorf(HERE, "no type specifiers given in declaration");
3938 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3939 (type_specifiers & SPECIFIER_UNSIGNED)) {
3940 errorf(HERE, "signed and unsigned specifiers given");
3941 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3942 errorf(HERE, "only integer types can be signed or unsigned");
3944 errorf(HERE, "multiple datatypes in declaration");
3949 if (type_specifiers & SPECIFIER_COMPLEX) {
3950 type = allocate_type_zero(TYPE_COMPLEX);
3951 type->complex.akind = atomic_type;
3952 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3953 type = allocate_type_zero(TYPE_IMAGINARY);
3954 type->imaginary.akind = atomic_type;
3956 type = allocate_type_zero(TYPE_ATOMIC);
3957 type->atomic.akind = atomic_type;
3960 } else if (type_specifiers != 0) {
3961 errorf(HERE, "multiple datatypes in declaration");
3964 /* FIXME: check type qualifiers here */
3966 type->base.qualifiers = qualifiers;
3967 type->base.modifiers = modifiers;
3969 type_t *result = typehash_insert(type);
3970 if (newtype && result != type) {
3974 specifiers->type = result;
3978 specifiers->type = type_error_type;
3982 static type_qualifiers_t parse_type_qualifiers(void)
3984 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3987 switch (token.type) {
3988 /* type qualifiers */
3989 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3990 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3991 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3992 /* microsoft extended type modifiers */
3993 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3994 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3995 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3996 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3997 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4006 * Parses an K&R identifier list
4008 static void parse_identifier_list(scope_t *scope)
4011 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4012 entity->base.source_position = token.source_position;
4013 entity->base.namespc = NAMESPACE_NORMAL;
4014 entity->base.symbol = token.v.symbol;
4015 /* a K&R parameter has no type, yet */
4018 append_entity(scope, entity);
4020 if (token.type != ',') {
4024 } while (token.type == T_IDENTIFIER);
4027 static type_t *automatic_type_conversion(type_t *orig_type);
4029 static void semantic_parameter(declaration_t *declaration)
4031 /* TODO: improve error messages */
4032 source_position_t const* const pos = &declaration->base.source_position;
4035 switch (declaration->declared_storage_class) {
4036 /* Allowed storage classes */
4037 case STORAGE_CLASS_NONE:
4038 case STORAGE_CLASS_REGISTER:
4042 errorf(pos, "parameter may only have none or register storage class");
4046 type_t *const orig_type = declaration->type;
4047 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
4048 * sugar. Turn it into a pointer.
4049 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4050 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4052 type_t *const type = automatic_type_conversion(orig_type);
4053 declaration->type = type;
4055 if (is_type_incomplete(skip_typeref(type))) {
4056 errorf(pos, "parameter '%#T' is of incomplete type",
4057 orig_type, declaration->base.symbol);
4061 static entity_t *parse_parameter(void)
4063 declaration_specifiers_t specifiers;
4064 memset(&specifiers, 0, sizeof(specifiers));
4066 parse_declaration_specifiers(&specifiers);
4068 entity_t *entity = parse_declarator(&specifiers, true, false);
4073 * Parses function type parameters (and optionally creates variable_t entities
4074 * for them in a scope)
4076 static void parse_parameters(function_type_t *type, scope_t *scope)
4079 add_anchor_token(')');
4080 int saved_comma_state = save_and_reset_anchor_state(',');
4082 if (token.type == T_IDENTIFIER &&
4083 !is_typedef_symbol(token.v.symbol)) {
4084 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4085 if (la1_type == ',' || la1_type == ')') {
4086 type->kr_style_parameters = true;
4087 parse_identifier_list(scope);
4088 goto parameters_finished;
4092 if (token.type == ')') {
4093 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4094 if (!(c_mode & _CXX))
4095 type->unspecified_parameters = true;
4096 goto parameters_finished;
4099 function_parameter_t *parameter;
4100 function_parameter_t *last_parameter = NULL;
4103 switch (token.type) {
4106 type->variadic = true;
4107 goto parameters_finished;
4110 case T___extension__:
4113 entity_t *entity = parse_parameter();
4114 if (entity->kind == ENTITY_TYPEDEF) {
4115 errorf(&entity->base.source_position,
4116 "typedef not allowed as function parameter");
4119 assert(is_declaration(entity));
4121 /* func(void) is not a parameter */
4122 if (last_parameter == NULL
4123 && token.type == ')'
4124 && entity->base.symbol == NULL
4125 && skip_typeref(entity->declaration.type) == type_void) {
4126 goto parameters_finished;
4128 semantic_parameter(&entity->declaration);
4130 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4131 memset(parameter, 0, sizeof(parameter[0]));
4132 parameter->type = entity->declaration.type;
4134 if (scope != NULL) {
4135 append_entity(scope, entity);
4138 if (last_parameter != NULL) {
4139 last_parameter->next = parameter;
4141 type->parameters = parameter;
4143 last_parameter = parameter;
4148 goto parameters_finished;
4150 if (token.type != ',') {
4151 goto parameters_finished;
4157 parameters_finished:
4158 rem_anchor_token(')');
4162 restore_anchor_state(',', saved_comma_state);
4165 typedef enum construct_type_kind_t {
4170 } construct_type_kind_t;
4172 typedef struct construct_type_t construct_type_t;
4173 struct construct_type_t {
4174 construct_type_kind_t kind;
4175 construct_type_t *next;
4178 typedef struct parsed_pointer_t parsed_pointer_t;
4179 struct parsed_pointer_t {
4180 construct_type_t construct_type;
4181 type_qualifiers_t type_qualifiers;
4184 typedef struct construct_function_type_t construct_function_type_t;
4185 struct construct_function_type_t {
4186 construct_type_t construct_type;
4187 type_t *function_type;
4190 typedef struct parsed_array_t parsed_array_t;
4191 struct parsed_array_t {
4192 construct_type_t construct_type;
4193 type_qualifiers_t type_qualifiers;
4199 typedef struct construct_base_type_t construct_base_type_t;
4200 struct construct_base_type_t {
4201 construct_type_t construct_type;
4205 static construct_type_t *parse_pointer_declarator(void)
4209 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4210 memset(pointer, 0, sizeof(pointer[0]));
4211 pointer->construct_type.kind = CONSTRUCT_POINTER;
4212 pointer->type_qualifiers = parse_type_qualifiers();
4214 return (construct_type_t*) pointer;
4217 static construct_type_t *parse_array_declarator(void)
4220 add_anchor_token(']');
4222 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4223 memset(array, 0, sizeof(array[0]));
4224 array->construct_type.kind = CONSTRUCT_ARRAY;
4226 if (token.type == T_static) {
4227 array->is_static = true;
4231 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4232 if (type_qualifiers != 0) {
4233 if (token.type == T_static) {
4234 array->is_static = true;
4238 array->type_qualifiers = type_qualifiers;
4240 if (token.type == '*' && look_ahead(1)->type == ']') {
4241 array->is_variable = true;
4243 } else if (token.type != ']') {
4244 array->size = parse_assignment_expression();
4247 rem_anchor_token(']');
4251 return (construct_type_t*) array;
4254 static construct_type_t *parse_function_declarator(scope_t *scope)
4256 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4258 /* TODO: revive this... once we know exactly how to do it */
4260 decl_modifiers_t modifiers = entity->declaration.modifiers;
4262 unsigned mask = modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
4264 if (mask & (mask-1)) {
4265 const char *first = NULL, *second = NULL;
4267 /* more than one calling convention set */
4268 if (modifiers & DM_CDECL) {
4269 if (first == NULL) first = "cdecl";
4270 else if (second == NULL) second = "cdecl";
4272 if (modifiers & DM_STDCALL) {
4273 if (first == NULL) first = "stdcall";
4274 else if (second == NULL) second = "stdcall";
4276 if (modifiers & DM_FASTCALL) {
4277 if (first == NULL) first = "fastcall";
4278 else if (second == NULL) second = "fastcall";
4280 if (modifiers & DM_THISCALL) {
4281 if (first == NULL) first = "thiscall";
4282 else if (second == NULL) second = "thiscall";
4284 errorf(&entity->base.source_position,
4285 "%s and %s attributes are not compatible", first, second);
4288 if (modifiers & DM_CDECL)
4289 type->function.calling_convention = CC_CDECL;
4290 else if (modifiers & DM_STDCALL)
4291 type->function.calling_convention = CC_STDCALL;
4292 else if (modifiers & DM_FASTCALL)
4293 type->function.calling_convention = CC_FASTCALL;
4294 else if (modifiers & DM_THISCALL)
4295 type->function.calling_convention = CC_THISCALL;
4298 parse_parameters(&type->function, scope);
4300 construct_function_type_t *construct_function_type =
4301 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4302 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4303 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4304 construct_function_type->function_type = type;
4306 return &construct_function_type->construct_type;
4309 typedef struct parse_declarator_env_t {
4310 decl_modifiers_t modifiers;
4312 source_position_t source_position;
4314 } parse_declarator_env_t;
4316 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4317 bool may_be_abstract)
4319 /* construct a single linked list of construct_type_t's which describe
4320 * how to construct the final declarator type */
4321 construct_type_t *first = NULL;
4322 construct_type_t *last = NULL;
4323 gnu_attribute_t *attributes = NULL;
4325 decl_modifiers_t modifiers = parse_attributes(&attributes);
4328 while (token.type == '*') {
4329 construct_type_t *type = parse_pointer_declarator();
4339 /* TODO: find out if this is correct */
4340 modifiers |= parse_attributes(&attributes);
4344 env->modifiers |= modifiers;
4346 construct_type_t *inner_types = NULL;
4348 switch (token.type) {
4351 errorf(HERE, "no identifier expected in typename");
4353 env->symbol = token.v.symbol;
4354 env->source_position = token.source_position;
4360 add_anchor_token(')');
4361 inner_types = parse_inner_declarator(env, may_be_abstract);
4362 if (inner_types != NULL) {
4363 /* All later declarators only modify the return type */
4366 rem_anchor_token(')');
4370 if (may_be_abstract)
4372 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4377 construct_type_t *p = last;
4380 construct_type_t *type;
4381 switch (token.type) {
4383 scope_t *scope = NULL;
4385 scope = &env->parameters;
4387 type = parse_function_declarator(scope);
4391 type = parse_array_declarator();
4394 goto declarator_finished;
4397 /* insert in the middle of the list (behind p) */
4399 type->next = p->next;
4410 declarator_finished:
4411 /* append inner_types at the end of the list, we don't to set last anymore
4412 * as it's not needed anymore */
4414 assert(first == NULL);
4415 first = inner_types;
4417 last->next = inner_types;
4425 static void parse_declaration_attributes(entity_t *entity)
4427 gnu_attribute_t *attributes = NULL;
4428 decl_modifiers_t modifiers = parse_attributes(&attributes);
4434 if (entity->kind == ENTITY_TYPEDEF) {
4435 modifiers |= entity->typedefe.modifiers;
4436 type = entity->typedefe.type;
4438 assert(is_declaration(entity));
4439 modifiers |= entity->declaration.modifiers;
4440 type = entity->declaration.type;
4445 /* handle these strange/stupid mode attributes */
4446 gnu_attribute_t *attribute = attributes;
4447 for ( ; attribute != NULL; attribute = attribute->next) {
4448 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4451 atomic_type_kind_t akind = attribute->u.akind;
4452 if (!is_type_signed(type)) {
4454 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4455 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4456 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4457 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4459 panic("invalid akind in mode attribute");
4463 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4464 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4465 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4466 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4468 panic("invalid akind in mode attribute");
4472 type = make_atomic_type(akind, type->base.qualifiers);
4475 type_modifiers_t type_modifiers = type->base.modifiers;
4476 if (modifiers & DM_TRANSPARENT_UNION)
4477 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4479 if (type->base.modifiers != type_modifiers) {
4480 type_t *copy = duplicate_type(type);
4481 copy->base.modifiers = type_modifiers;
4483 type = typehash_insert(copy);
4485 obstack_free(type_obst, copy);
4489 if (entity->kind == ENTITY_TYPEDEF) {
4490 entity->typedefe.type = type;
4491 entity->typedefe.modifiers = modifiers;
4493 entity->declaration.type = type;
4494 entity->declaration.modifiers = modifiers;
4498 static type_t *construct_declarator_type(construct_type_t *construct_list,
4501 construct_type_t *iter = construct_list;
4502 for( ; iter != NULL; iter = iter->next) {
4503 switch (iter->kind) {
4504 case CONSTRUCT_INVALID:
4505 internal_errorf(HERE, "invalid type construction found");
4506 case CONSTRUCT_FUNCTION: {
4507 construct_function_type_t *construct_function_type
4508 = (construct_function_type_t*) iter;
4510 type_t *function_type = construct_function_type->function_type;
4512 function_type->function.return_type = type;
4514 type_t *skipped_return_type = skip_typeref(type);
4516 if (is_type_function(skipped_return_type)) {
4517 errorf(HERE, "function returning function is not allowed");
4518 } else if (is_type_array(skipped_return_type)) {
4519 errorf(HERE, "function returning array is not allowed");
4521 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4523 "type qualifiers in return type of function type are meaningless");
4527 type = function_type;
4531 case CONSTRUCT_POINTER: {
4532 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4533 type = make_pointer_type(type, parsed_pointer->type_qualifiers);
4537 case CONSTRUCT_ARRAY: {
4538 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4539 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4541 expression_t *size_expression = parsed_array->size;
4542 if (size_expression != NULL) {
4544 = create_implicit_cast(size_expression, type_size_t);
4547 array_type->base.qualifiers = parsed_array->type_qualifiers;
4548 array_type->array.element_type = type;
4549 array_type->array.is_static = parsed_array->is_static;
4550 array_type->array.is_variable = parsed_array->is_variable;
4551 array_type->array.size_expression = size_expression;
4553 if (size_expression != NULL) {
4554 if (is_constant_expression(size_expression)) {
4555 array_type->array.size_constant = true;
4556 array_type->array.size
4557 = fold_constant(size_expression);
4559 array_type->array.is_vla = true;
4563 type_t *skipped_type = skip_typeref(type);
4565 if (is_type_incomplete(skipped_type)) {
4566 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4567 } else if (is_type_function(skipped_type)) {
4568 errorf(HERE, "array of functions is not allowed");
4575 type_t *hashed_type = typehash_insert(type);
4576 if (hashed_type != type) {
4577 /* the function type was constructed earlier freeing it here will
4578 * destroy other types... */
4579 if (iter->kind != CONSTRUCT_FUNCTION) {
4589 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4590 bool may_be_abstract,
4591 bool create_compound_member)
4593 parse_declarator_env_t env;
4594 memset(&env, 0, sizeof(env));
4596 construct_type_t *construct_type
4597 = parse_inner_declarator(&env, may_be_abstract);
4598 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4600 if (construct_type != NULL) {
4601 obstack_free(&temp_obst, construct_type);
4605 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4606 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4607 entity->base.symbol = env.symbol;
4608 entity->base.source_position = env.source_position;
4609 entity->typedefe.type = type;
4611 if (create_compound_member) {
4612 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4613 } else if (is_type_function(skip_typeref(type))) {
4614 entity = allocate_entity_zero(ENTITY_FUNCTION);
4616 entity->function.is_inline = specifiers->is_inline;
4617 entity->function.parameters = env.parameters;
4619 entity = allocate_entity_zero(ENTITY_VARIABLE);
4621 entity->variable.get_property_sym = specifiers->get_property_sym;
4622 entity->variable.put_property_sym = specifiers->put_property_sym;
4623 if (specifiers->alignment != 0) {
4624 /* TODO: add checks here */
4625 entity->variable.alignment = specifiers->alignment;
4628 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4629 warningf(&env.source_position,
4630 "variable '%Y' declared 'inline'\n", env.symbol);
4634 entity->base.source_position = env.source_position;
4635 entity->base.symbol = env.symbol;
4636 entity->base.namespc = NAMESPACE_NORMAL;
4637 entity->declaration.type = type;
4638 entity->declaration.modifiers = env.modifiers | specifiers->modifiers;
4639 entity->declaration.deprecated_string = specifiers->deprecated_string;
4641 storage_class_t storage_class = specifiers->storage_class;
4642 entity->declaration.declared_storage_class = storage_class;
4644 if (storage_class == STORAGE_CLASS_NONE && scope != file_scope) {
4645 storage_class = STORAGE_CLASS_AUTO;
4647 entity->declaration.storage_class = storage_class;
4650 parse_declaration_attributes(entity);
4655 static type_t *parse_abstract_declarator(type_t *base_type)
4657 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4659 type_t *result = construct_declarator_type(construct_type, base_type);
4660 if (construct_type != NULL) {
4661 obstack_free(&temp_obst, construct_type);
4668 * Check if the declaration of main is suspicious. main should be a
4669 * function with external linkage, returning int, taking either zero
4670 * arguments, two, or three arguments of appropriate types, ie.
4672 * int main([ int argc, char **argv [, char **env ] ]).
4674 * @param decl the declaration to check
4675 * @param type the function type of the declaration
4677 static void check_type_of_main(const entity_t *entity)
4679 const source_position_t *pos = &entity->base.source_position;
4680 if (entity->kind != ENTITY_FUNCTION) {
4681 warningf(pos, "'main' is not a function");
4685 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4686 warningf(pos, "'main' is normally a non-static function");
4689 type_t *type = skip_typeref(entity->declaration.type);
4690 assert(is_type_function(type));
4692 function_type_t *func_type = &type->function;
4693 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4694 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4695 func_type->return_type);
4697 const function_parameter_t *parm = func_type->parameters;
4699 type_t *const first_type = parm->type;
4700 if (!types_compatible(skip_typeref(first_type), type_int)) {
4702 "first argument of 'main' should be 'int', but is '%T'",
4707 type_t *const second_type = parm->type;
4708 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4709 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4713 type_t *const third_type = parm->type;
4714 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4715 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4719 goto warn_arg_count;
4723 warningf(pos, "'main' takes only zero, two or three arguments");
4729 * Check if a symbol is the equal to "main".
4731 static bool is_sym_main(const symbol_t *const sym)
4733 return strcmp(sym->string, "main") == 0;
4737 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4738 * for various problems that occur for multiple definitions
4740 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4742 const symbol_t *const symbol = entity->base.symbol;
4743 const namespace_t namespc = entity->base.namespc;
4744 const source_position_t *pos = &entity->base.source_position;
4746 assert(symbol != NULL);
4747 entity_t *previous_entity = get_entity(symbol, namespc);
4748 /* pushing the same entity twice will break the stack structure */
4749 assert(previous_entity != entity);
4751 if (entity->kind == ENTITY_FUNCTION) {
4752 type_t *const orig_type = entity->declaration.type;
4753 type_t *const type = skip_typeref(orig_type);
4755 assert(is_type_function(type));
4756 if (type->function.unspecified_parameters &&
4757 warning.strict_prototypes &&
4758 previous_entity == NULL) {
4759 warningf(pos, "function declaration '%#T' is not a prototype",
4763 if (warning.main && scope == file_scope && is_sym_main(symbol)) {
4764 check_type_of_main(entity);
4768 if (is_declaration(entity)) {
4769 if (warning.nested_externs
4770 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4771 && scope != file_scope) {
4772 warningf(pos, "nested extern declaration of '%#T'",
4773 entity->declaration.type, symbol);
4777 if (previous_entity != NULL
4778 && previous_entity->base.parent_scope == ¤t_function->parameters
4779 && scope->depth == previous_entity->base.parent_scope->depth + 1) {
4781 assert(previous_entity->kind == ENTITY_VARIABLE);
4783 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4784 entity->declaration.type, symbol,
4785 previous_entity->declaration.type, symbol,
4786 &previous_entity->base.source_position);
4790 if (previous_entity != NULL
4791 && previous_entity->base.parent_scope == scope) {
4793 if (previous_entity->kind != entity->kind) {
4795 "redeclaration of '%Y' as different kind of symbol (declared %P)",
4796 symbol, &previous_entity->base.source_position);
4799 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4801 "redeclaration of enum entry '%Y' (declared %P)",
4802 symbol, &previous_entity->base.source_position);
4805 if (previous_entity->kind == ENTITY_TYPEDEF) {
4806 /* TODO: C++ allows this for exactly the same type */
4808 "redefinition of typedef '%Y' (declared %P)",
4809 symbol, &previous_entity->base.source_position);
4813 /* at this point we should have only VARIABLES or FUNCTIONS */
4814 assert(is_declaration(previous_entity) && is_declaration(entity));
4816 /* can happen for K&R style declarations */
4817 if (previous_entity->kind == ENTITY_VARIABLE
4818 && previous_entity->declaration.type == NULL
4819 && entity->kind == ENTITY_VARIABLE) {
4820 previous_entity->declaration.type = entity->declaration.type;
4821 previous_entity->declaration.storage_class
4822 = entity->declaration.storage_class;
4823 previous_entity->declaration.declared_storage_class
4824 = entity->declaration.declared_storage_class;
4825 previous_entity->declaration.modifiers
4826 = entity->declaration.modifiers;
4827 previous_entity->declaration.deprecated_string
4828 = entity->declaration.deprecated_string;
4830 assert(entity->declaration.type != NULL);
4832 declaration_t *const previous_declaration
4833 = &previous_entity->declaration;
4834 declaration_t *const declaration = &entity->declaration;
4835 type_t *const orig_type = entity->declaration.type;
4836 type_t *const type = skip_typeref(orig_type);
4838 type_t *prev_type = skip_typeref(previous_declaration->type);
4840 if (!types_compatible(type, prev_type)) {
4842 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4843 orig_type, symbol, previous_declaration->type, symbol,
4844 &previous_entity->base.source_position);
4846 unsigned old_storage_class = previous_declaration->storage_class;
4847 if (warning.redundant_decls && is_definition
4848 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4849 && !(previous_declaration->modifiers & DM_USED)
4850 && !previous_declaration->used) {
4851 warningf(&previous_entity->base.source_position,
4852 "unnecessary static forward declaration for '%#T'",
4853 previous_declaration->type, symbol);
4856 unsigned new_storage_class = declaration->storage_class;
4857 if (is_type_incomplete(prev_type)) {
4858 previous_declaration->type = type;
4862 /* pretend no storage class means extern for function
4863 * declarations (except if the previous declaration is neither
4864 * none nor extern) */
4865 if (entity->kind == ENTITY_FUNCTION) {
4866 if (prev_type->function.unspecified_parameters) {
4867 previous_declaration->type = type;
4871 switch (old_storage_class) {
4872 case STORAGE_CLASS_NONE:
4873 old_storage_class = STORAGE_CLASS_EXTERN;
4876 case STORAGE_CLASS_EXTERN:
4877 if (is_definition) {
4878 if (warning.missing_prototypes &&
4879 prev_type->function.unspecified_parameters &&
4880 !is_sym_main(symbol)) {
4881 warningf(pos, "no previous prototype for '%#T'",
4884 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4885 new_storage_class = STORAGE_CLASS_EXTERN;
4894 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4895 new_storage_class == STORAGE_CLASS_EXTERN) {
4896 warn_redundant_declaration:
4897 if (!is_definition &&
4898 warning.redundant_decls &&
4899 is_type_valid(prev_type) &&
4900 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4902 "redundant declaration for '%Y' (declared %P)",
4903 symbol, &previous_entity->base.source_position);
4905 } else if (current_function == NULL) {
4906 if (old_storage_class != STORAGE_CLASS_STATIC &&
4907 new_storage_class == STORAGE_CLASS_STATIC) {
4909 "static declaration of '%Y' follows non-static declaration (declared %P)",
4910 symbol, &previous_entity->base.source_position);
4911 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4912 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4913 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4915 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4917 goto error_redeclaration;
4918 goto warn_redundant_declaration;
4920 } else if (is_type_valid(prev_type)) {
4921 if (old_storage_class == new_storage_class) {
4922 error_redeclaration:
4923 errorf(pos, "redeclaration of '%Y' (declared %P)",
4924 symbol, &previous_entity->base.source_position);
4927 "redeclaration of '%Y' with different linkage (declared %P)",
4928 symbol, &previous_entity->base.source_position);
4933 previous_declaration->modifiers |= declaration->modifiers;
4934 if (entity->kind == ENTITY_FUNCTION) {
4935 previous_entity->function.is_inline |= entity->function.is_inline;
4937 return previous_entity;
4940 if (entity->kind == ENTITY_FUNCTION) {
4941 if (is_definition &&
4942 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4943 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4944 warningf(pos, "no previous prototype for '%#T'",
4945 entity->declaration.type, symbol);
4946 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4947 warningf(pos, "no previous declaration for '%#T'",
4948 entity->declaration.type, symbol);
4951 } else if (warning.missing_declarations
4952 && entity->kind == ENTITY_VARIABLE
4953 && scope == file_scope) {
4954 declaration_t *declaration = &entity->declaration;
4955 if (declaration->storage_class == STORAGE_CLASS_NONE ||
4956 declaration->storage_class == STORAGE_CLASS_THREAD) {
4957 warningf(pos, "no previous declaration for '%#T'",
4958 declaration->type, symbol);
4963 assert(entity->base.parent_scope == NULL);
4964 assert(scope != NULL);
4966 entity->base.parent_scope = scope;
4967 entity->base.namespc = NAMESPACE_NORMAL;
4968 environment_push(entity);
4969 append_entity(scope, entity);
4974 static void parser_error_multiple_definition(entity_t *entity,
4975 const source_position_t *source_position)
4977 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4978 entity->base.symbol, &entity->base.source_position);
4981 static bool is_declaration_specifier(const token_t *token,
4982 bool only_specifiers_qualifiers)
4984 switch (token->type) {
4989 return is_typedef_symbol(token->v.symbol);
4991 case T___extension__:
4993 return !only_specifiers_qualifiers;
5000 static void parse_init_declarator_rest(entity_t *entity)
5002 assert(is_declaration(entity));
5003 declaration_t *const declaration = &entity->declaration;
5007 type_t *orig_type = declaration->type;
5008 type_t *type = skip_typeref(orig_type);
5010 if (entity->kind == ENTITY_VARIABLE
5011 && entity->variable.initializer != NULL) {
5012 parser_error_multiple_definition(entity, HERE);
5015 bool must_be_constant = false;
5016 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5017 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5018 entity->base.parent_scope == file_scope) {
5019 must_be_constant = true;
5022 if (is_type_function(type)) {
5023 errorf(&entity->base.source_position,
5024 "function '%#T' is initialized like a variable",
5025 orig_type, entity->base.symbol);
5026 orig_type = type_error_type;
5029 parse_initializer_env_t env;
5030 env.type = orig_type;
5031 env.must_be_constant = must_be_constant;
5032 env.entity = entity;
5033 current_init_decl = entity;
5035 initializer_t *initializer = parse_initializer(&env);
5036 current_init_decl = NULL;
5038 if (entity->kind == ENTITY_VARIABLE) {
5039 /* § 6.7.5 (22) array initializers for arrays with unknown size
5040 * determine the array type size */
5041 declaration->type = env.type;
5042 entity->variable.initializer = initializer;
5046 /* parse rest of a declaration without any declarator */
5047 static void parse_anonymous_declaration_rest(
5048 const declaration_specifiers_t *specifiers)
5052 if (warning.other) {
5053 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5054 warningf(&specifiers->source_position,
5055 "useless storage class in empty declaration");
5058 type_t *type = specifiers->type;
5059 switch (type->kind) {
5060 case TYPE_COMPOUND_STRUCT:
5061 case TYPE_COMPOUND_UNION: {
5062 if (type->compound.compound->base.symbol == NULL) {
5063 warningf(&specifiers->source_position,
5064 "unnamed struct/union that defines no instances");
5073 warningf(&specifiers->source_position, "empty declaration");
5079 static void parse_declaration_rest(entity_t *ndeclaration,
5080 const declaration_specifiers_t *specifiers,
5081 parsed_declaration_func finished_declaration)
5083 add_anchor_token(';');
5084 add_anchor_token(',');
5086 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5088 if (token.type == '=') {
5089 parse_init_declarator_rest(entity);
5092 if (token.type != ',')
5096 add_anchor_token('=');
5097 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5098 rem_anchor_token('=');
5103 rem_anchor_token(';');
5104 rem_anchor_token(',');
5107 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5109 symbol_t *symbol = entity->base.symbol;
5110 if (symbol == NULL) {
5111 errorf(HERE, "anonymous declaration not valid as function parameter");
5115 assert(entity->base.namespc == NAMESPACE_NORMAL);
5116 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5117 if (previous_entity == NULL
5118 || previous_entity->base.parent_scope != scope) {
5119 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5124 if (is_definition) {
5125 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5128 return record_entity(entity, false);
5131 static void parse_declaration(parsed_declaration_func finished_declaration)
5133 declaration_specifiers_t specifiers;
5134 memset(&specifiers, 0, sizeof(specifiers));
5136 add_anchor_token(';');
5137 parse_declaration_specifiers(&specifiers);
5138 rem_anchor_token(';');
5140 if (token.type == ';') {
5141 parse_anonymous_declaration_rest(&specifiers);
5143 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5144 parse_declaration_rest(entity, &specifiers, finished_declaration);
5148 static type_t *get_default_promoted_type(type_t *orig_type)
5150 type_t *result = orig_type;
5152 type_t *type = skip_typeref(orig_type);
5153 if (is_type_integer(type)) {
5154 result = promote_integer(type);
5155 } else if (type == type_float) {
5156 result = type_double;
5162 static void parse_kr_declaration_list(entity_t *entity)
5164 if (entity->kind != ENTITY_FUNCTION)
5167 type_t *type = skip_typeref(entity->declaration.type);
5168 assert(is_type_function(type));
5169 if (!type->function.kr_style_parameters)
5173 add_anchor_token('{');
5175 /* push function parameters */
5176 size_t const top = environment_top();
5177 scope_push(&entity->function.parameters);
5179 entity_t *parameter = entity->function.parameters.entities;
5180 for ( ; parameter != NULL; parameter = parameter->base.next) {
5181 assert(parameter->base.parent_scope == NULL);
5182 parameter->base.parent_scope = scope;
5183 environment_push(parameter);
5186 /* parse declaration list */
5187 while (is_declaration_specifier(&token, false)) {
5188 parse_declaration(finished_kr_declaration);
5191 /* pop function parameters */
5192 assert(scope == &entity->function.parameters);
5194 environment_pop_to(top);
5196 /* update function type */
5197 type_t *new_type = duplicate_type(type);
5199 function_parameter_t *parameters = NULL;
5200 function_parameter_t *last_parameter = NULL;
5202 entity_t *parameter_declaration = entity->function.parameters.entities;
5203 for( ; parameter_declaration != NULL;
5204 parameter_declaration = parameter_declaration->base.next) {
5205 type_t *parameter_type = parameter_declaration->declaration.type;
5206 if (parameter_type == NULL) {
5208 errorf(HERE, "no type specified for function parameter '%Y'",
5209 parameter_declaration->base.symbol);
5211 if (warning.implicit_int) {
5212 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5213 parameter_declaration->base.symbol);
5215 parameter_type = type_int;
5216 parameter_declaration->declaration.type = parameter_type;
5220 semantic_parameter(¶meter_declaration->declaration);
5221 parameter_type = parameter_declaration->declaration.type;
5224 * we need the default promoted types for the function type
5226 parameter_type = get_default_promoted_type(parameter_type);
5228 function_parameter_t *function_parameter
5229 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5230 memset(function_parameter, 0, sizeof(function_parameter[0]));
5232 function_parameter->type = parameter_type;
5233 if (last_parameter != NULL) {
5234 last_parameter->next = function_parameter;
5236 parameters = function_parameter;
5238 last_parameter = function_parameter;
5241 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5243 new_type->function.parameters = parameters;
5244 new_type->function.unspecified_parameters = true;
5246 type = typehash_insert(new_type);
5247 if (type != new_type) {
5248 obstack_free(type_obst, new_type);
5251 entity->declaration.type = type;
5253 rem_anchor_token('{');
5256 static bool first_err = true;
5259 * When called with first_err set, prints the name of the current function,
5262 static void print_in_function(void)
5266 diagnosticf("%s: In function '%Y':\n",
5267 current_function->base.base.source_position.input_name,
5268 current_function->base.base.symbol);
5273 * Check if all labels are defined in the current function.
5274 * Check if all labels are used in the current function.
5276 static void check_labels(void)
5278 for (const goto_statement_t *goto_statement = goto_first;
5279 goto_statement != NULL;
5280 goto_statement = goto_statement->next) {
5281 /* skip computed gotos */
5282 if (goto_statement->expression != NULL)
5285 label_t *label = goto_statement->label;
5288 if (label->base.source_position.input_name == NULL) {
5289 print_in_function();
5290 errorf(&goto_statement->base.source_position,
5291 "label '%Y' used but not defined", label->base.symbol);
5297 if (warning.unused_label) {
5298 for (const label_statement_t *label_statement = label_first;
5299 label_statement != NULL;
5300 label_statement = label_statement->next) {
5301 label_t *label = label_statement->label;
5303 if (! label->used) {
5304 print_in_function();
5305 warningf(&label_statement->base.source_position,
5306 "label '%Y' defined but not used", label->base.symbol);
5310 label_first = label_last = NULL;
5313 static void warn_unused_decl(entity_t *entity, entity_t *end,
5314 char const *const what)
5316 for (; entity != NULL; entity = entity->base.next) {
5317 if (!is_declaration(entity))
5320 declaration_t *declaration = &entity->declaration;
5321 if (declaration->implicit)
5324 if (!declaration->used) {
5325 print_in_function();
5326 warningf(&entity->base.source_position, "%s '%Y' is unused",
5327 what, entity->base.symbol);
5328 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5329 print_in_function();
5330 warningf(&entity->base.source_position, "%s '%Y' is never read",
5331 what, entity->base.symbol);
5339 static void check_unused_variables(statement_t *const stmt, void *const env)
5343 switch (stmt->kind) {
5344 case STATEMENT_DECLARATION: {
5345 declaration_statement_t const *const decls = &stmt->declaration;
5346 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5352 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5361 * Check declarations of current_function for unused entities.
5363 static void check_declarations(void)
5365 if (warning.unused_parameter) {
5366 const scope_t *scope = ¤t_function->parameters;
5368 /* do not issue unused warnings for main */
5369 if (!is_sym_main(current_function->base.base.symbol)) {
5370 warn_unused_decl(scope->entities, NULL, "parameter");
5373 if (warning.unused_variable) {
5374 walk_statements(current_function->statement, check_unused_variables,
5379 static int determine_truth(expression_t const* const cond)
5382 !is_constant_expression(cond) ? 0 :
5383 fold_constant(cond) != 0 ? 1 :
5387 static bool expression_returns(expression_t const *const expr)
5389 switch (expr->kind) {
5391 expression_t const *const func = expr->call.function;
5392 if (func->kind == EXPR_REFERENCE) {
5393 entity_t *entity = func->reference.entity;
5394 if (entity->kind == ENTITY_FUNCTION
5395 && entity->declaration.modifiers & DM_NORETURN)
5399 if (!expression_returns(func))
5402 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5403 if (!expression_returns(arg->expression))
5410 case EXPR_REFERENCE:
5411 case EXPR_REFERENCE_ENUM_VALUE:
5413 case EXPR_CHARACTER_CONSTANT:
5414 case EXPR_WIDE_CHARACTER_CONSTANT:
5415 case EXPR_STRING_LITERAL:
5416 case EXPR_WIDE_STRING_LITERAL:
5417 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5418 case EXPR_LABEL_ADDRESS:
5419 case EXPR_CLASSIFY_TYPE:
5420 case EXPR_SIZEOF: // TODO handle obscure VLA case
5423 case EXPR_BUILTIN_SYMBOL:
5424 case EXPR_BUILTIN_CONSTANT_P:
5425 case EXPR_BUILTIN_PREFETCH:
5428 case EXPR_STATEMENT: // TODO implement
5431 case EXPR_CONDITIONAL:
5432 // TODO handle constant expression
5434 expression_returns(expr->conditional.condition) && (
5435 expression_returns(expr->conditional.true_expression) ||
5436 expression_returns(expr->conditional.false_expression)
5440 return expression_returns(expr->select.compound);
5442 case EXPR_ARRAY_ACCESS:
5444 expression_returns(expr->array_access.array_ref) &&
5445 expression_returns(expr->array_access.index);
5448 return expression_returns(expr->va_starte.ap);
5451 return expression_returns(expr->va_arge.ap);
5453 EXPR_UNARY_CASES_MANDATORY
5454 return expression_returns(expr->unary.value);
5456 case EXPR_UNARY_THROW:
5460 // TODO handle constant lhs of && and ||
5462 expression_returns(expr->binary.left) &&
5463 expression_returns(expr->binary.right);
5469 panic("unhandled expression");
5472 static bool noreturn_candidate;
5474 static void check_reachable(statement_t *const stmt)
5476 if (stmt->base.reachable)
5478 if (stmt->kind != STATEMENT_DO_WHILE)
5479 stmt->base.reachable = true;
5481 statement_t *last = stmt;
5483 switch (stmt->kind) {
5484 case STATEMENT_INVALID:
5485 case STATEMENT_EMPTY:
5486 case STATEMENT_DECLARATION:
5487 case STATEMENT_LOCAL_LABEL:
5489 next = stmt->base.next;
5492 case STATEMENT_COMPOUND:
5493 next = stmt->compound.statements;
5496 case STATEMENT_RETURN:
5497 noreturn_candidate = false;
5500 case STATEMENT_IF: {
5501 if_statement_t const* const ifs = &stmt->ifs;
5502 int const val = determine_truth(ifs->condition);
5505 check_reachable(ifs->true_statement);
5510 if (ifs->false_statement != NULL) {
5511 check_reachable(ifs->false_statement);
5515 next = stmt->base.next;
5519 case STATEMENT_SWITCH: {
5520 switch_statement_t const *const switchs = &stmt->switchs;
5521 expression_t const *const expr = switchs->expression;
5523 if (is_constant_expression(expr)) {
5524 long const val = fold_constant(expr);
5525 case_label_statement_t * defaults = NULL;
5526 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5527 if (i->expression == NULL) {
5532 if (i->first_case <= val && val <= i->last_case) {
5533 check_reachable((statement_t*)i);
5538 if (defaults != NULL) {
5539 check_reachable((statement_t*)defaults);
5543 bool has_default = false;
5544 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5545 if (i->expression == NULL)
5548 check_reachable((statement_t*)i);
5555 next = stmt->base.next;
5559 case STATEMENT_EXPRESSION: {
5560 /* Check for noreturn function call */
5561 expression_t const *const expr = stmt->expression.expression;
5562 if (!expression_returns(expr))
5565 next = stmt->base.next;
5569 case STATEMENT_CONTINUE: {
5570 statement_t *parent = stmt;
5572 parent = parent->base.parent;
5573 if (parent == NULL) /* continue not within loop */
5577 switch (parent->kind) {
5578 case STATEMENT_WHILE: goto continue_while;
5579 case STATEMENT_DO_WHILE: goto continue_do_while;
5580 case STATEMENT_FOR: goto continue_for;
5587 case STATEMENT_BREAK: {
5588 statement_t *parent = stmt;
5590 parent = parent->base.parent;
5591 if (parent == NULL) /* break not within loop/switch */
5594 switch (parent->kind) {
5595 case STATEMENT_SWITCH:
5596 case STATEMENT_WHILE:
5597 case STATEMENT_DO_WHILE:
5600 next = parent->base.next;
5601 goto found_break_parent;
5610 case STATEMENT_GOTO:
5611 if (stmt->gotos.expression) {
5612 statement_t *parent = stmt->base.parent;
5613 if (parent == NULL) /* top level goto */
5617 next = stmt->gotos.label->statement;
5618 if (next == NULL) /* missing label */
5623 case STATEMENT_LABEL:
5624 next = stmt->label.statement;
5627 case STATEMENT_CASE_LABEL:
5628 next = stmt->case_label.statement;
5631 case STATEMENT_WHILE: {
5632 while_statement_t const *const whiles = &stmt->whiles;
5633 int const val = determine_truth(whiles->condition);
5636 check_reachable(whiles->body);
5641 next = stmt->base.next;
5645 case STATEMENT_DO_WHILE:
5646 next = stmt->do_while.body;
5649 case STATEMENT_FOR: {
5650 for_statement_t *const fors = &stmt->fors;
5652 if (fors->condition_reachable)
5654 fors->condition_reachable = true;
5656 expression_t const *const cond = fors->condition;
5658 cond == NULL ? 1 : determine_truth(cond);
5661 check_reachable(fors->body);
5666 next = stmt->base.next;
5670 case STATEMENT_MS_TRY: {
5671 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5672 check_reachable(ms_try->try_statement);
5673 next = ms_try->final_statement;
5677 case STATEMENT_LEAVE: {
5678 statement_t *parent = stmt;
5680 parent = parent->base.parent;
5681 if (parent == NULL) /* __leave not within __try */
5684 if (parent->kind == STATEMENT_MS_TRY) {
5686 next = parent->ms_try.final_statement;
5694 while (next == NULL) {
5695 next = last->base.parent;
5697 noreturn_candidate = false;
5699 type_t *const type = current_function->base.type;
5700 assert(is_type_function(type));
5701 type_t *const ret = skip_typeref(type->function.return_type);
5702 if (warning.return_type &&
5703 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5704 is_type_valid(ret) &&
5705 !is_sym_main(current_function->base.base.symbol)) {
5706 warningf(&stmt->base.source_position,
5707 "control reaches end of non-void function");
5712 switch (next->kind) {
5713 case STATEMENT_INVALID:
5714 case STATEMENT_EMPTY:
5715 case STATEMENT_DECLARATION:
5716 case STATEMENT_LOCAL_LABEL:
5717 case STATEMENT_EXPRESSION:
5719 case STATEMENT_RETURN:
5720 case STATEMENT_CONTINUE:
5721 case STATEMENT_BREAK:
5722 case STATEMENT_GOTO:
5723 case STATEMENT_LEAVE:
5724 panic("invalid control flow in function");
5726 case STATEMENT_COMPOUND:
5728 case STATEMENT_SWITCH:
5729 case STATEMENT_LABEL:
5730 case STATEMENT_CASE_LABEL:
5732 next = next->base.next;
5735 case STATEMENT_WHILE: {
5737 if (next->base.reachable)
5739 next->base.reachable = true;
5741 while_statement_t const *const whiles = &next->whiles;
5742 int const val = determine_truth(whiles->condition);
5745 check_reachable(whiles->body);
5751 next = next->base.next;
5755 case STATEMENT_DO_WHILE: {
5757 if (next->base.reachable)
5759 next->base.reachable = true;
5761 do_while_statement_t const *const dw = &next->do_while;
5762 int const val = determine_truth(dw->condition);
5765 check_reachable(dw->body);
5771 next = next->base.next;
5775 case STATEMENT_FOR: {
5777 for_statement_t *const fors = &next->fors;
5779 fors->step_reachable = true;
5781 if (fors->condition_reachable)
5783 fors->condition_reachable = true;
5785 expression_t const *const cond = fors->condition;
5787 cond == NULL ? 1 : determine_truth(cond);
5790 check_reachable(fors->body);
5796 next = next->base.next;
5800 case STATEMENT_MS_TRY:
5802 next = next->ms_try.final_statement;
5807 check_reachable(next);
5810 static void check_unreachable(statement_t* const stmt, void *const env)
5814 switch (stmt->kind) {
5815 case STATEMENT_DO_WHILE:
5816 if (!stmt->base.reachable) {
5817 expression_t const *const cond = stmt->do_while.condition;
5818 if (determine_truth(cond) >= 0) {
5819 warningf(&cond->base.source_position,
5820 "condition of do-while-loop is unreachable");
5825 case STATEMENT_FOR: {
5826 for_statement_t const* const fors = &stmt->fors;
5828 // if init and step are unreachable, cond is unreachable, too
5829 if (!stmt->base.reachable && !fors->step_reachable) {
5830 warningf(&stmt->base.source_position, "statement is unreachable");
5832 if (!stmt->base.reachable && fors->initialisation != NULL) {
5833 warningf(&fors->initialisation->base.source_position,
5834 "initialisation of for-statement is unreachable");
5837 if (!fors->condition_reachable && fors->condition != NULL) {
5838 warningf(&fors->condition->base.source_position,
5839 "condition of for-statement is unreachable");
5842 if (!fors->step_reachable && fors->step != NULL) {
5843 warningf(&fors->step->base.source_position,
5844 "step of for-statement is unreachable");
5850 case STATEMENT_COMPOUND:
5851 if (stmt->compound.statements != NULL)
5856 if (!stmt->base.reachable)
5857 warningf(&stmt->base.source_position, "statement is unreachable");
5862 static void parse_external_declaration(void)
5864 /* function-definitions and declarations both start with declaration
5866 declaration_specifiers_t specifiers;
5867 memset(&specifiers, 0, sizeof(specifiers));
5869 add_anchor_token(';');
5870 parse_declaration_specifiers(&specifiers);
5871 rem_anchor_token(';');
5873 /* must be a declaration */
5874 if (token.type == ';') {
5875 parse_anonymous_declaration_rest(&specifiers);
5879 add_anchor_token(',');
5880 add_anchor_token('=');
5881 add_anchor_token(';');
5882 add_anchor_token('{');
5884 /* declarator is common to both function-definitions and declarations */
5885 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5887 rem_anchor_token('{');
5888 rem_anchor_token(';');
5889 rem_anchor_token('=');
5890 rem_anchor_token(',');
5892 /* must be a declaration */
5893 switch (token.type) {
5897 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
5901 /* must be a function definition */
5902 parse_kr_declaration_list(ndeclaration);
5904 if (token.type != '{') {
5905 parse_error_expected("while parsing function definition", '{', NULL);
5906 eat_until_matching_token(';');
5910 assert(is_declaration(ndeclaration));
5911 type_t *type = ndeclaration->declaration.type;
5913 /* note that we don't skip typerefs: the standard doesn't allow them here
5914 * (so we can't use is_type_function here) */
5915 if (type->kind != TYPE_FUNCTION) {
5916 if (is_type_valid(type)) {
5917 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5918 type, ndeclaration->base.symbol);
5924 if (warning.aggregate_return &&
5925 is_type_compound(skip_typeref(type->function.return_type))) {
5926 warningf(HERE, "function '%Y' returns an aggregate",
5927 ndeclaration->base.symbol);
5929 if (warning.traditional && !type->function.unspecified_parameters) {
5930 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5931 ndeclaration->base.symbol);
5933 if (warning.old_style_definition && type->function.unspecified_parameters) {
5934 warningf(HERE, "old-style function definition '%Y'",
5935 ndeclaration->base.symbol);
5938 /* § 6.7.5.3 (14) a function definition with () means no
5939 * parameters (and not unspecified parameters) */
5940 if (type->function.unspecified_parameters
5941 && type->function.parameters == NULL
5942 && !type->function.kr_style_parameters) {
5943 type_t *duplicate = duplicate_type(type);
5944 duplicate->function.unspecified_parameters = false;
5946 type = typehash_insert(duplicate);
5947 if (type != duplicate) {
5948 obstack_free(type_obst, duplicate);
5950 ndeclaration->declaration.type = type;
5953 entity_t *const entity = record_entity(ndeclaration, true);
5954 assert(entity->kind == ENTITY_FUNCTION);
5955 assert(ndeclaration->kind == ENTITY_FUNCTION);
5957 function_t *function = &entity->function;
5958 if (ndeclaration != entity) {
5959 function->parameters = ndeclaration->function.parameters;
5961 assert(is_declaration(entity));
5962 type = skip_typeref(entity->declaration.type);
5964 /* push function parameters and switch scope */
5965 size_t const top = environment_top();
5966 scope_push(&function->parameters);
5968 entity_t *parameter = function->parameters.entities;
5969 for( ; parameter != NULL; parameter = parameter->base.next) {
5970 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5971 parameter->base.parent_scope = scope;
5973 assert(parameter->base.parent_scope == NULL
5974 || parameter->base.parent_scope == scope);
5975 parameter->base.parent_scope = scope;
5976 if (parameter->base.symbol == NULL) {
5977 errorf(¶meter->base.source_position, "parameter name omitted");
5980 environment_push(parameter);
5983 if (function->statement != NULL) {
5984 parser_error_multiple_definition(entity, HERE);
5987 /* parse function body */
5988 int label_stack_top = label_top();
5989 function_t *old_current_function = current_function;
5990 current_function = function;
5991 current_parent = NULL;
5993 statement_t *const body = parse_compound_statement(false);
5994 function->statement = body;
5997 check_declarations();
5998 if (warning.return_type ||
5999 warning.unreachable_code ||
6000 (warning.missing_noreturn
6001 && !(function->base.modifiers & DM_NORETURN))) {
6002 noreturn_candidate = true;
6003 check_reachable(body);
6004 if (warning.unreachable_code)
6005 walk_statements(body, check_unreachable, NULL);
6006 if (warning.missing_noreturn &&
6007 noreturn_candidate &&
6008 !(function->base.modifiers & DM_NORETURN)) {
6009 warningf(&body->base.source_position,
6010 "function '%#T' is candidate for attribute 'noreturn'",
6011 type, entity->base.symbol);
6015 assert(current_parent == NULL);
6016 assert(current_function == function);
6017 current_function = old_current_function;
6018 label_pop_to(label_stack_top);
6021 assert(scope == &function->parameters);
6023 environment_pop_to(top);
6026 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6027 source_position_t *source_position,
6028 const symbol_t *symbol)
6030 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6032 type->bitfield.base_type = base_type;
6033 type->bitfield.size_expression = size;
6036 type_t *skipped_type = skip_typeref(base_type);
6037 if (!is_type_integer(skipped_type)) {
6038 errorf(HERE, "bitfield base type '%T' is not an integer type",
6042 bit_size = skipped_type->base.size * 8;
6045 if (is_constant_expression(size)) {
6046 long v = fold_constant(size);
6049 errorf(source_position, "negative width in bit-field '%Y'",
6051 } else if (v == 0) {
6052 errorf(source_position, "zero width for bit-field '%Y'",
6054 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6055 errorf(source_position, "width of '%Y' exceeds its type",
6058 type->bitfield.bit_size = v;
6065 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6067 entity_t *iter = compound->members.entities;
6068 for( ; iter != NULL; iter = iter->base.next) {
6069 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6072 if (iter->base.symbol == NULL) {
6073 type_t *type = skip_typeref(iter->declaration.type);
6074 if (is_type_compound(type)) {
6076 = find_compound_entry(type->compound.compound, symbol);
6083 if (iter->base.symbol == symbol) {
6091 static void parse_compound_declarators(compound_t *compound,
6092 const declaration_specifiers_t *specifiers)
6097 if (token.type == ':') {
6098 source_position_t source_position = *HERE;
6101 type_t *base_type = specifiers->type;
6102 expression_t *size = parse_constant_expression();
6104 type_t *type = make_bitfield_type(base_type, size,
6105 &source_position, sym_anonymous);
6107 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6108 entity->base.namespc = NAMESPACE_NORMAL;
6109 entity->base.source_position = source_position;
6110 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6111 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6112 entity->declaration.modifiers = specifiers->modifiers;
6113 entity->declaration.type = type;
6115 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6116 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6118 if (token.type == ':') {
6119 source_position_t source_position = *HERE;
6121 expression_t *size = parse_constant_expression();
6123 type_t *type = entity->declaration.type;
6124 type_t *bitfield_type = make_bitfield_type(type, size,
6125 &source_position, entity->base.symbol);
6126 entity->declaration.type = bitfield_type;
6130 /* make sure we don't define a symbol multiple times */
6131 symbol_t *symbol = entity->base.symbol;
6132 if (symbol != NULL) {
6133 entity_t *prev = find_compound_entry(compound, symbol);
6136 assert(prev->base.symbol == symbol);
6137 errorf(&entity->base.source_position,
6138 "multiple declarations of symbol '%Y' (declared %P)",
6139 symbol, &prev->base.source_position);
6143 append_entity(&compound->members, entity);
6145 if (token.type != ',')
6155 static void semantic_compound(compound_t *compound)
6157 entity_t *entity = compound->members.entities;
6158 for ( ; entity != NULL; entity = entity->base.next) {
6159 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6161 type_t *orig_type = entity->declaration.type;
6162 type_t *type = skip_typeref(orig_type);
6164 if (is_type_function(type)) {
6166 "compound member '%Y' must not have function type '%T'",
6167 entity->base.symbol, orig_type);
6168 } else if (is_type_incomplete(type)) {
6169 /* §6.7.2.1 (16) flexible array member */
6170 if (is_type_array(type) && entity->base.next == NULL) {
6171 compound->has_flexible_member = true;
6174 "compound member '%Y' has incomplete type '%T'",
6175 entity->base.symbol, orig_type);
6181 static void parse_compound_type_entries(compound_t *compound)
6184 add_anchor_token('}');
6186 while (token.type != '}') {
6187 if (token.type == T_EOF) {
6188 errorf(HERE, "EOF while parsing struct");
6191 declaration_specifiers_t specifiers;
6192 memset(&specifiers, 0, sizeof(specifiers));
6193 parse_declaration_specifiers(&specifiers);
6195 parse_compound_declarators(compound, &specifiers);
6197 semantic_compound(compound);
6198 rem_anchor_token('}');
6202 static type_t *parse_typename(void)
6204 declaration_specifiers_t specifiers;
6205 memset(&specifiers, 0, sizeof(specifiers));
6206 parse_declaration_specifiers(&specifiers);
6207 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6208 /* TODO: improve error message, user does probably not know what a
6209 * storage class is...
6211 errorf(HERE, "typename may not have a storage class");
6214 type_t *result = parse_abstract_declarator(specifiers.type);
6222 typedef expression_t* (*parse_expression_function)(void);
6223 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6225 typedef struct expression_parser_function_t expression_parser_function_t;
6226 struct expression_parser_function_t {
6227 parse_expression_function parser;
6228 unsigned infix_precedence;
6229 parse_expression_infix_function infix_parser;
6232 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6235 * Prints an error message if an expression was expected but not read
6237 static expression_t *expected_expression_error(void)
6239 /* skip the error message if the error token was read */
6240 if (token.type != T_ERROR) {
6241 errorf(HERE, "expected expression, got token '%K'", &token);
6245 return create_invalid_expression();
6249 * Parse a string constant.
6251 static expression_t *parse_string_const(void)
6254 if (token.type == T_STRING_LITERAL) {
6255 string_t res = token.v.string;
6257 while (token.type == T_STRING_LITERAL) {
6258 res = concat_strings(&res, &token.v.string);
6261 if (token.type != T_WIDE_STRING_LITERAL) {
6262 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6263 /* note: that we use type_char_ptr here, which is already the
6264 * automatic converted type. revert_automatic_type_conversion
6265 * will construct the array type */
6266 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6267 cnst->string.value = res;
6271 wres = concat_string_wide_string(&res, &token.v.wide_string);
6273 wres = token.v.wide_string;
6278 switch (token.type) {
6279 case T_WIDE_STRING_LITERAL:
6280 wres = concat_wide_strings(&wres, &token.v.wide_string);
6283 case T_STRING_LITERAL:
6284 wres = concat_wide_string_string(&wres, &token.v.string);
6288 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6289 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6290 cnst->wide_string.value = wres;
6299 * Parse a boolean constant.
6301 static expression_t *parse_bool_const(bool value)
6303 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6304 cnst->base.type = type_bool;
6305 cnst->conste.v.int_value = value;
6313 * Parse an integer constant.
6315 static expression_t *parse_int_const(void)
6317 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6318 cnst->base.type = token.datatype;
6319 cnst->conste.v.int_value = token.v.intvalue;
6327 * Parse a character constant.
6329 static expression_t *parse_character_constant(void)
6331 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6332 cnst->base.type = token.datatype;
6333 cnst->conste.v.character = token.v.string;
6335 if (cnst->conste.v.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 wide character constant.
6350 static expression_t *parse_wide_character_constant(void)
6352 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6353 cnst->base.type = token.datatype;
6354 cnst->conste.v.wide_character = token.v.wide_string;
6356 if (cnst->conste.v.wide_character.size != 1) {
6357 if (warning.multichar && GNU_MODE) {
6358 warningf(HERE, "multi-character character constant");
6360 errorf(HERE, "more than 1 characters in character constant");
6369 * Parse a float constant.
6371 static expression_t *parse_float_const(void)
6373 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6374 cnst->base.type = token.datatype;
6375 cnst->conste.v.float_value = token.v.floatvalue;
6382 static entity_t *create_implicit_function(symbol_t *symbol,
6383 const source_position_t *source_position)
6385 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6386 ntype->function.return_type = type_int;
6387 ntype->function.unspecified_parameters = true;
6389 type_t *type = typehash_insert(ntype);
6390 if (type != ntype) {
6394 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6395 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6396 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6397 entity->declaration.type = type;
6398 entity->declaration.implicit = true;
6399 entity->base.symbol = symbol;
6400 entity->base.source_position = *source_position;
6402 bool strict_prototypes_old = warning.strict_prototypes;
6403 warning.strict_prototypes = false;
6404 record_entity(entity, false);
6405 warning.strict_prototypes = strict_prototypes_old;
6411 * Creates a return_type (func)(argument_type) function type if not
6414 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6415 type_t *argument_type2)
6417 function_parameter_t *parameter2
6418 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6419 memset(parameter2, 0, sizeof(parameter2[0]));
6420 parameter2->type = argument_type2;
6422 function_parameter_t *parameter1
6423 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6424 memset(parameter1, 0, sizeof(parameter1[0]));
6425 parameter1->type = argument_type1;
6426 parameter1->next = parameter2;
6428 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6429 type->function.return_type = return_type;
6430 type->function.parameters = parameter1;
6432 type_t *result = typehash_insert(type);
6433 if (result != type) {
6441 * Creates a return_type (func)(argument_type) function type if not
6444 * @param return_type the return type
6445 * @param argument_type the argument type
6447 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6449 function_parameter_t *parameter
6450 = obstack_alloc(type_obst, sizeof(parameter[0]));
6451 memset(parameter, 0, sizeof(parameter[0]));
6452 parameter->type = argument_type;
6454 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6455 type->function.return_type = return_type;
6456 type->function.parameters = parameter;
6458 type_t *result = typehash_insert(type);
6459 if (result != type) {
6466 static type_t *make_function_0_type(type_t *return_type)
6468 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6469 type->function.return_type = return_type;
6470 type->function.parameters = NULL;
6472 type_t *result = typehash_insert(type);
6473 if (result != type) {
6481 * Creates a function type for some function like builtins.
6483 * @param symbol the symbol describing the builtin
6485 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6487 switch (symbol->ID) {
6488 case T___builtin_alloca:
6489 return make_function_1_type(type_void_ptr, type_size_t);
6490 case T___builtin_huge_val:
6491 return make_function_0_type(type_double);
6492 case T___builtin_inf:
6493 return make_function_0_type(type_double);
6494 case T___builtin_inff:
6495 return make_function_0_type(type_float);
6496 case T___builtin_infl:
6497 return make_function_0_type(type_long_double);
6498 case T___builtin_nan:
6499 return make_function_1_type(type_double, type_char_ptr);
6500 case T___builtin_nanf:
6501 return make_function_1_type(type_float, type_char_ptr);
6502 case T___builtin_nanl:
6503 return make_function_1_type(type_long_double, type_char_ptr);
6504 case T___builtin_va_end:
6505 return make_function_1_type(type_void, type_valist);
6506 case T___builtin_expect:
6507 return make_function_2_type(type_long, type_long, type_long);
6509 internal_errorf(HERE, "not implemented builtin symbol found");
6514 * Performs automatic type cast as described in § 6.3.2.1.
6516 * @param orig_type the original type
6518 static type_t *automatic_type_conversion(type_t *orig_type)
6520 type_t *type = skip_typeref(orig_type);
6521 if (is_type_array(type)) {
6522 array_type_t *array_type = &type->array;
6523 type_t *element_type = array_type->element_type;
6524 unsigned qualifiers = array_type->base.qualifiers;
6526 return make_pointer_type(element_type, qualifiers);
6529 if (is_type_function(type)) {
6530 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6537 * reverts the automatic casts of array to pointer types and function
6538 * to function-pointer types as defined § 6.3.2.1
6540 type_t *revert_automatic_type_conversion(const expression_t *expression)
6542 switch (expression->kind) {
6543 case EXPR_REFERENCE: {
6544 entity_t *entity = expression->reference.entity;
6545 if (is_declaration(entity)) {
6546 return entity->declaration.type;
6547 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6548 return entity->enum_value.enum_type;
6550 panic("no declaration or enum in reference");
6555 entity_t *entity = expression->select.compound_entry;
6556 assert(is_declaration(entity));
6557 type_t *type = entity->declaration.type;
6558 return get_qualified_type(type,
6559 expression->base.type->base.qualifiers);
6562 case EXPR_UNARY_DEREFERENCE: {
6563 const expression_t *const value = expression->unary.value;
6564 type_t *const type = skip_typeref(value->base.type);
6565 assert(is_type_pointer(type));
6566 return type->pointer.points_to;
6569 case EXPR_BUILTIN_SYMBOL:
6570 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6572 case EXPR_ARRAY_ACCESS: {
6573 const expression_t *array_ref = expression->array_access.array_ref;
6574 type_t *type_left = skip_typeref(array_ref->base.type);
6575 if (!is_type_valid(type_left))
6577 assert(is_type_pointer(type_left));
6578 return type_left->pointer.points_to;
6581 case EXPR_STRING_LITERAL: {
6582 size_t size = expression->string.value.size;
6583 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6586 case EXPR_WIDE_STRING_LITERAL: {
6587 size_t size = expression->wide_string.value.size;
6588 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6591 case EXPR_COMPOUND_LITERAL:
6592 return expression->compound_literal.type;
6597 return expression->base.type;
6600 static expression_t *parse_reference(void)
6602 symbol_t *const symbol = token.v.symbol;
6604 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6606 if (entity == NULL) {
6607 if (!strict_mode && look_ahead(1)->type == '(') {
6608 /* an implicitly declared function */
6609 if (warning.implicit_function_declaration) {
6610 warningf(HERE, "implicit declaration of function '%Y'",
6614 entity = create_implicit_function(symbol, HERE);
6616 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6617 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6623 if (is_declaration(entity)) {
6624 orig_type = entity->declaration.type;
6625 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6626 orig_type = entity->enum_value.enum_type;
6627 } else if (entity->kind == ENTITY_TYPEDEF) {
6628 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6631 return create_invalid_expression();
6633 panic("expected declaration or enum value in reference");
6636 /* we always do the auto-type conversions; the & and sizeof parser contains
6637 * code to revert this! */
6638 type_t *type = automatic_type_conversion(orig_type);
6640 expression_kind_t kind = EXPR_REFERENCE;
6641 if (entity->kind == ENTITY_ENUM_VALUE)
6642 kind = EXPR_REFERENCE_ENUM_VALUE;
6644 expression_t *expression = allocate_expression_zero(kind);
6645 expression->reference.entity = entity;
6646 expression->base.type = type;
6648 /* this declaration is used */
6649 if (is_declaration(entity)) {
6650 entity->declaration.used = true;
6653 if (entity->base.parent_scope != file_scope
6654 && entity->base.parent_scope->depth < current_function->parameters.depth
6655 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6656 if (entity->kind == ENTITY_VARIABLE) {
6657 /* access of a variable from an outer function */
6658 entity->variable.address_taken = true;
6660 current_function->need_closure = true;
6663 /* check for deprecated functions */
6664 if (warning.deprecated_declarations
6665 && is_declaration(entity)
6666 && entity->declaration.modifiers & DM_DEPRECATED) {
6667 declaration_t *declaration = &entity->declaration;
6669 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6670 "function" : "variable";
6672 if (declaration->deprecated_string != NULL) {
6673 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6674 prefix, entity->base.symbol, &entity->base.source_position,
6675 declaration->deprecated_string);
6677 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6678 entity->base.symbol, &entity->base.source_position);
6682 if (warning.init_self && entity == current_init_decl && !in_type_prop
6683 && entity->kind == ENTITY_VARIABLE) {
6684 current_init_decl = NULL;
6685 warningf(HERE, "variable '%#T' is initialized by itself",
6686 entity->declaration.type, entity->base.symbol);
6693 static bool semantic_cast(expression_t *cast)
6695 expression_t *expression = cast->unary.value;
6696 type_t *orig_dest_type = cast->base.type;
6697 type_t *orig_type_right = expression->base.type;
6698 type_t const *dst_type = skip_typeref(orig_dest_type);
6699 type_t const *src_type = skip_typeref(orig_type_right);
6700 source_position_t const *pos = &cast->base.source_position;
6702 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6703 if (dst_type == type_void)
6706 /* only integer and pointer can be casted to pointer */
6707 if (is_type_pointer(dst_type) &&
6708 !is_type_pointer(src_type) &&
6709 !is_type_integer(src_type) &&
6710 is_type_valid(src_type)) {
6711 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6715 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6716 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6720 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6721 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6725 if (warning.cast_qual &&
6726 is_type_pointer(src_type) &&
6727 is_type_pointer(dst_type)) {
6728 type_t *src = skip_typeref(src_type->pointer.points_to);
6729 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6730 unsigned missing_qualifiers =
6731 src->base.qualifiers & ~dst->base.qualifiers;
6732 if (missing_qualifiers != 0) {
6734 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6735 missing_qualifiers, orig_type_right);
6741 static expression_t *parse_compound_literal(type_t *type)
6743 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6745 parse_initializer_env_t env;
6748 env.must_be_constant = false;
6749 initializer_t *initializer = parse_initializer(&env);
6752 expression->compound_literal.initializer = initializer;
6753 expression->compound_literal.type = type;
6754 expression->base.type = automatic_type_conversion(type);
6760 * Parse a cast expression.
6762 static expression_t *parse_cast(void)
6764 add_anchor_token(')');
6766 source_position_t source_position = token.source_position;
6768 type_t *type = parse_typename();
6770 rem_anchor_token(')');
6773 if (token.type == '{') {
6774 return parse_compound_literal(type);
6777 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6778 cast->base.source_position = source_position;
6780 expression_t *value = parse_sub_expression(PREC_CAST);
6781 cast->base.type = type;
6782 cast->unary.value = value;
6784 if (! semantic_cast(cast)) {
6785 /* TODO: record the error in the AST. else it is impossible to detect it */
6790 return create_invalid_expression();
6794 * Parse a statement expression.
6796 static expression_t *parse_statement_expression(void)
6798 add_anchor_token(')');
6800 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6802 statement_t *statement = parse_compound_statement(true);
6803 expression->statement.statement = statement;
6805 /* find last statement and use its type */
6806 type_t *type = type_void;
6807 const statement_t *stmt = statement->compound.statements;
6809 while (stmt->base.next != NULL)
6810 stmt = stmt->base.next;
6812 if (stmt->kind == STATEMENT_EXPRESSION) {
6813 type = stmt->expression.expression->base.type;
6815 } else if (warning.other) {
6816 warningf(&expression->base.source_position, "empty statement expression ({})");
6818 expression->base.type = type;
6820 rem_anchor_token(')');
6828 * Parse a parenthesized expression.
6830 static expression_t *parse_parenthesized_expression(void)
6834 switch (token.type) {
6836 /* gcc extension: a statement expression */
6837 return parse_statement_expression();
6841 return parse_cast();
6843 if (is_typedef_symbol(token.v.symbol)) {
6844 return parse_cast();
6848 add_anchor_token(')');
6849 expression_t *result = parse_expression();
6850 rem_anchor_token(')');
6857 static expression_t *parse_function_keyword(void)
6861 if (current_function == NULL) {
6862 errorf(HERE, "'__func__' used outside of a function");
6865 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6866 expression->base.type = type_char_ptr;
6867 expression->funcname.kind = FUNCNAME_FUNCTION;
6874 static expression_t *parse_pretty_function_keyword(void)
6876 if (current_function == NULL) {
6877 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6880 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6881 expression->base.type = type_char_ptr;
6882 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6884 eat(T___PRETTY_FUNCTION__);
6889 static expression_t *parse_funcsig_keyword(void)
6891 if (current_function == NULL) {
6892 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6895 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6896 expression->base.type = type_char_ptr;
6897 expression->funcname.kind = FUNCNAME_FUNCSIG;
6904 static expression_t *parse_funcdname_keyword(void)
6906 if (current_function == NULL) {
6907 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6910 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6911 expression->base.type = type_char_ptr;
6912 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6914 eat(T___FUNCDNAME__);
6919 static designator_t *parse_designator(void)
6921 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6922 result->source_position = *HERE;
6924 if (token.type != T_IDENTIFIER) {
6925 parse_error_expected("while parsing member designator",
6926 T_IDENTIFIER, NULL);
6929 result->symbol = token.v.symbol;
6932 designator_t *last_designator = result;
6934 if (token.type == '.') {
6936 if (token.type != T_IDENTIFIER) {
6937 parse_error_expected("while parsing member designator",
6938 T_IDENTIFIER, NULL);
6941 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6942 designator->source_position = *HERE;
6943 designator->symbol = token.v.symbol;
6946 last_designator->next = designator;
6947 last_designator = designator;
6950 if (token.type == '[') {
6952 add_anchor_token(']');
6953 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6954 designator->source_position = *HERE;
6955 designator->array_index = parse_expression();
6956 rem_anchor_token(']');
6958 if (designator->array_index == NULL) {
6962 last_designator->next = designator;
6963 last_designator = designator;
6975 * Parse the __builtin_offsetof() expression.
6977 static expression_t *parse_offsetof(void)
6979 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6980 expression->base.type = type_size_t;
6982 eat(T___builtin_offsetof);
6985 add_anchor_token(',');
6986 type_t *type = parse_typename();
6987 rem_anchor_token(',');
6989 add_anchor_token(')');
6990 designator_t *designator = parse_designator();
6991 rem_anchor_token(')');
6994 expression->offsetofe.type = type;
6995 expression->offsetofe.designator = designator;
6998 memset(&path, 0, sizeof(path));
6999 path.top_type = type;
7000 path.path = NEW_ARR_F(type_path_entry_t, 0);
7002 descend_into_subtype(&path);
7004 if (!walk_designator(&path, designator, true)) {
7005 return create_invalid_expression();
7008 DEL_ARR_F(path.path);
7012 return create_invalid_expression();
7016 * Parses a _builtin_va_start() expression.
7018 static expression_t *parse_va_start(void)
7020 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7022 eat(T___builtin_va_start);
7025 add_anchor_token(',');
7026 expression->va_starte.ap = parse_assignment_expression();
7027 rem_anchor_token(',');
7029 expression_t *const expr = parse_assignment_expression();
7030 if (expr->kind == EXPR_REFERENCE) {
7031 entity_t *const entity = expr->reference.entity;
7032 if (entity->base.parent_scope != ¤t_function->parameters
7033 || entity->base.next != NULL
7034 || entity->kind != ENTITY_VARIABLE) {
7035 errorf(&expr->base.source_position,
7036 "second argument of 'va_start' must be last parameter of the current function");
7038 expression->va_starte.parameter = &entity->variable;
7045 return create_invalid_expression();
7049 * Parses a _builtin_va_arg() expression.
7051 static expression_t *parse_va_arg(void)
7053 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7055 eat(T___builtin_va_arg);
7058 expression->va_arge.ap = parse_assignment_expression();
7060 expression->base.type = parse_typename();
7065 return create_invalid_expression();
7068 static expression_t *parse_builtin_symbol(void)
7070 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7072 symbol_t *symbol = token.v.symbol;
7074 expression->builtin_symbol.symbol = symbol;
7077 type_t *type = get_builtin_symbol_type(symbol);
7078 type = automatic_type_conversion(type);
7080 expression->base.type = type;
7085 * Parses a __builtin_constant() expression.
7087 static expression_t *parse_builtin_constant(void)
7089 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7091 eat(T___builtin_constant_p);
7094 add_anchor_token(')');
7095 expression->builtin_constant.value = parse_assignment_expression();
7096 rem_anchor_token(')');
7098 expression->base.type = type_int;
7102 return create_invalid_expression();
7106 * Parses a __builtin_prefetch() expression.
7108 static expression_t *parse_builtin_prefetch(void)
7110 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7112 eat(T___builtin_prefetch);
7115 add_anchor_token(')');
7116 expression->builtin_prefetch.adr = parse_assignment_expression();
7117 if (token.type == ',') {
7119 expression->builtin_prefetch.rw = parse_assignment_expression();
7121 if (token.type == ',') {
7123 expression->builtin_prefetch.locality = parse_assignment_expression();
7125 rem_anchor_token(')');
7127 expression->base.type = type_void;
7131 return create_invalid_expression();
7135 * Parses a __builtin_is_*() compare expression.
7137 static expression_t *parse_compare_builtin(void)
7139 expression_t *expression;
7141 switch (token.type) {
7142 case T___builtin_isgreater:
7143 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7145 case T___builtin_isgreaterequal:
7146 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7148 case T___builtin_isless:
7149 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7151 case T___builtin_islessequal:
7152 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7154 case T___builtin_islessgreater:
7155 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7157 case T___builtin_isunordered:
7158 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7161 internal_errorf(HERE, "invalid compare builtin found");
7163 expression->base.source_position = *HERE;
7167 expression->binary.left = parse_assignment_expression();
7169 expression->binary.right = parse_assignment_expression();
7172 type_t *const orig_type_left = expression->binary.left->base.type;
7173 type_t *const orig_type_right = expression->binary.right->base.type;
7175 type_t *const type_left = skip_typeref(orig_type_left);
7176 type_t *const type_right = skip_typeref(orig_type_right);
7177 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7178 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7179 type_error_incompatible("invalid operands in comparison",
7180 &expression->base.source_position, orig_type_left, orig_type_right);
7183 semantic_comparison(&expression->binary);
7188 return create_invalid_expression();
7193 * Parses a __builtin_expect() expression.
7195 static expression_t *parse_builtin_expect(void)
7197 expression_t *expression
7198 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7200 eat(T___builtin_expect);
7203 expression->binary.left = parse_assignment_expression();
7205 expression->binary.right = parse_constant_expression();
7208 expression->base.type = expression->binary.left->base.type;
7212 return create_invalid_expression();
7217 * Parses a MS assume() expression.
7219 static expression_t *parse_assume(void)
7221 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7226 add_anchor_token(')');
7227 expression->unary.value = parse_assignment_expression();
7228 rem_anchor_token(')');
7231 expression->base.type = type_void;
7234 return create_invalid_expression();
7238 * Return the declaration for a given label symbol or create a new one.
7240 * @param symbol the symbol of the label
7242 static label_t *get_label(symbol_t *symbol)
7245 assert(current_function != NULL);
7247 label = get_entity(symbol, NAMESPACE_LOCAL_LABEL);
7248 /* if we found a local label, we already created the declaration */
7249 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7250 if (label->base.parent_scope != scope) {
7251 assert(label->base.parent_scope->depth < scope->depth);
7252 current_function->goto_to_outer = true;
7254 return &label->label;
7257 label = get_entity(symbol, NAMESPACE_LABEL);
7258 /* if we found a label in the same function, then we already created the
7261 && label->base.parent_scope == ¤t_function->parameters) {
7262 return &label->label;
7265 /* otherwise we need to create a new one */
7266 label = allocate_entity_zero(ENTITY_LABEL);
7267 label->base.namespc = NAMESPACE_LABEL;
7268 label->base.symbol = symbol;
7272 return &label->label;
7276 * Parses a GNU && label address expression.
7278 static expression_t *parse_label_address(void)
7280 source_position_t source_position = token.source_position;
7282 if (token.type != T_IDENTIFIER) {
7283 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7286 symbol_t *symbol = token.v.symbol;
7289 label_t *label = get_label(symbol);
7291 label->address_taken = true;
7293 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7294 expression->base.source_position = source_position;
7296 /* label address is threaten as a void pointer */
7297 expression->base.type = type_void_ptr;
7298 expression->label_address.label = label;
7301 return create_invalid_expression();
7305 * Parse a microsoft __noop expression.
7307 static expression_t *parse_noop_expression(void)
7309 /* the result is a (int)0 */
7310 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7311 cnst->base.type = type_int;
7312 cnst->conste.v.int_value = 0;
7313 cnst->conste.is_ms_noop = true;
7317 if (token.type == '(') {
7318 /* parse arguments */
7320 add_anchor_token(')');
7321 add_anchor_token(',');
7323 if (token.type != ')') {
7325 (void)parse_assignment_expression();
7326 if (token.type != ',')
7332 rem_anchor_token(',');
7333 rem_anchor_token(')');
7341 * Parses a primary expression.
7343 static expression_t *parse_primary_expression(void)
7345 switch (token.type) {
7346 case T_false: return parse_bool_const(false);
7347 case T_true: return parse_bool_const(true);
7348 case T_INTEGER: return parse_int_const();
7349 case T_CHARACTER_CONSTANT: return parse_character_constant();
7350 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7351 case T_FLOATINGPOINT: return parse_float_const();
7352 case T_STRING_LITERAL:
7353 case T_WIDE_STRING_LITERAL: return parse_string_const();
7354 case T_IDENTIFIER: return parse_reference();
7355 case T___FUNCTION__:
7356 case T___func__: return parse_function_keyword();
7357 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7358 case T___FUNCSIG__: return parse_funcsig_keyword();
7359 case T___FUNCDNAME__: return parse_funcdname_keyword();
7360 case T___builtin_offsetof: return parse_offsetof();
7361 case T___builtin_va_start: return parse_va_start();
7362 case T___builtin_va_arg: return parse_va_arg();
7363 case T___builtin_expect:
7364 case T___builtin_alloca:
7365 case T___builtin_inf:
7366 case T___builtin_inff:
7367 case T___builtin_infl:
7368 case T___builtin_nan:
7369 case T___builtin_nanf:
7370 case T___builtin_nanl:
7371 case T___builtin_huge_val:
7372 case T___builtin_va_end: return parse_builtin_symbol();
7373 case T___builtin_isgreater:
7374 case T___builtin_isgreaterequal:
7375 case T___builtin_isless:
7376 case T___builtin_islessequal:
7377 case T___builtin_islessgreater:
7378 case T___builtin_isunordered: return parse_compare_builtin();
7379 case T___builtin_constant_p: return parse_builtin_constant();
7380 case T___builtin_prefetch: return parse_builtin_prefetch();
7381 case T__assume: return parse_assume();
7384 return parse_label_address();
7387 case '(': return parse_parenthesized_expression();
7388 case T___noop: return parse_noop_expression();
7391 errorf(HERE, "unexpected token %K, expected an expression", &token);
7392 return create_invalid_expression();
7396 * Check if the expression has the character type and issue a warning then.
7398 static void check_for_char_index_type(const expression_t *expression)
7400 type_t *const type = expression->base.type;
7401 const type_t *const base_type = skip_typeref(type);
7403 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7404 warning.char_subscripts) {
7405 warningf(&expression->base.source_position,
7406 "array subscript has type '%T'", type);
7410 static expression_t *parse_array_expression(expression_t *left)
7412 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7415 add_anchor_token(']');
7417 expression_t *inside = parse_expression();
7419 type_t *const orig_type_left = left->base.type;
7420 type_t *const orig_type_inside = inside->base.type;
7422 type_t *const type_left = skip_typeref(orig_type_left);
7423 type_t *const type_inside = skip_typeref(orig_type_inside);
7425 type_t *return_type;
7426 array_access_expression_t *array_access = &expression->array_access;
7427 if (is_type_pointer(type_left)) {
7428 return_type = type_left->pointer.points_to;
7429 array_access->array_ref = left;
7430 array_access->index = inside;
7431 check_for_char_index_type(inside);
7432 } else if (is_type_pointer(type_inside)) {
7433 return_type = type_inside->pointer.points_to;
7434 array_access->array_ref = inside;
7435 array_access->index = left;
7436 array_access->flipped = true;
7437 check_for_char_index_type(left);
7439 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7441 "array access on object with non-pointer types '%T', '%T'",
7442 orig_type_left, orig_type_inside);
7444 return_type = type_error_type;
7445 array_access->array_ref = left;
7446 array_access->index = inside;
7449 expression->base.type = automatic_type_conversion(return_type);
7451 rem_anchor_token(']');
7457 static expression_t *parse_typeprop(expression_kind_t const kind)
7459 expression_t *tp_expression = allocate_expression_zero(kind);
7460 tp_expression->base.type = type_size_t;
7462 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7464 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7466 /* we only refer to a type property, mark this case */
7467 bool old = in_type_prop;
7468 in_type_prop = true;
7471 expression_t *expression;
7472 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7474 add_anchor_token(')');
7475 orig_type = parse_typename();
7476 rem_anchor_token(')');
7479 if (token.type == '{') {
7480 /* It was not sizeof(type) after all. It is sizeof of an expression
7481 * starting with a compound literal */
7482 expression = parse_compound_literal(orig_type);
7483 goto typeprop_expression;
7486 expression = parse_sub_expression(PREC_UNARY);
7488 typeprop_expression:
7489 tp_expression->typeprop.tp_expression = expression;
7491 orig_type = revert_automatic_type_conversion(expression);
7492 expression->base.type = orig_type;
7495 tp_expression->typeprop.type = orig_type;
7496 type_t const* const type = skip_typeref(orig_type);
7497 char const* const wrong_type =
7498 is_type_incomplete(type) ? "incomplete" :
7499 type->kind == TYPE_FUNCTION ? "function designator" :
7500 type->kind == TYPE_BITFIELD ? "bitfield" :
7502 if (wrong_type != NULL) {
7503 errorf(&tp_expression->base.source_position,
7504 "operand of %s expression must not be of %s type '%T'",
7505 what, wrong_type, orig_type);
7510 return tp_expression;
7513 static expression_t *parse_sizeof(void)
7515 return parse_typeprop(EXPR_SIZEOF);
7518 static expression_t *parse_alignof(void)
7520 return parse_typeprop(EXPR_ALIGNOF);
7523 static expression_t *parse_select_expression(expression_t *compound)
7525 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7526 select->select.compound = compound;
7528 assert(token.type == '.' || token.type == T_MINUSGREATER);
7529 bool is_pointer = (token.type == T_MINUSGREATER);
7532 if (token.type != T_IDENTIFIER) {
7533 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7536 symbol_t *symbol = token.v.symbol;
7539 type_t *const orig_type = compound->base.type;
7540 type_t *const type = skip_typeref(orig_type);
7543 bool saw_error = false;
7544 if (is_type_pointer(type)) {
7547 "request for member '%Y' in something not a struct or union, but '%T'",
7551 type_left = skip_typeref(type->pointer.points_to);
7553 if (is_pointer && is_type_valid(type)) {
7554 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7561 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7562 type_left->kind == TYPE_COMPOUND_UNION) {
7563 compound_t *compound = type_left->compound.compound;
7565 if (!compound->complete) {
7566 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7568 goto create_error_entry;
7571 entry = find_compound_entry(compound, symbol);
7572 if (entry == NULL) {
7573 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7574 goto create_error_entry;
7577 if (is_type_valid(type_left) && !saw_error) {
7579 "request for member '%Y' in something not a struct or union, but '%T'",
7583 return create_invalid_expression();
7586 assert(is_declaration(entry));
7587 select->select.compound_entry = entry;
7589 type_t *entry_type = entry->declaration.type;
7591 = get_qualified_type(entry_type, type_left->base.qualifiers);
7593 /* we always do the auto-type conversions; the & and sizeof parser contains
7594 * code to revert this! */
7595 select->base.type = automatic_type_conversion(res_type);
7597 type_t *skipped = skip_typeref(res_type);
7598 if (skipped->kind == TYPE_BITFIELD) {
7599 select->base.type = skipped->bitfield.base_type;
7605 static void check_call_argument(const function_parameter_t *parameter,
7606 call_argument_t *argument, unsigned pos)
7608 type_t *expected_type = parameter->type;
7609 type_t *expected_type_skip = skip_typeref(expected_type);
7610 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7611 expression_t *arg_expr = argument->expression;
7612 type_t *arg_type = skip_typeref(arg_expr->base.type);
7614 /* handle transparent union gnu extension */
7615 if (is_type_union(expected_type_skip)
7616 && (expected_type_skip->base.modifiers
7617 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7618 compound_t *union_decl = expected_type_skip->compound.compound;
7619 type_t *best_type = NULL;
7620 entity_t *entry = union_decl->members.entities;
7621 for ( ; entry != NULL; entry = entry->base.next) {
7622 assert(is_declaration(entry));
7623 type_t *decl_type = entry->declaration.type;
7624 error = semantic_assign(decl_type, arg_expr);
7625 if (error == ASSIGN_ERROR_INCOMPATIBLE
7626 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7629 if (error == ASSIGN_SUCCESS) {
7630 best_type = decl_type;
7631 } else if (best_type == NULL) {
7632 best_type = decl_type;
7636 if (best_type != NULL) {
7637 expected_type = best_type;
7641 error = semantic_assign(expected_type, arg_expr);
7642 argument->expression = create_implicit_cast(argument->expression,
7645 if (error != ASSIGN_SUCCESS) {
7646 /* report exact scope in error messages (like "in argument 3") */
7648 snprintf(buf, sizeof(buf), "call argument %u", pos);
7649 report_assign_error(error, expected_type, arg_expr, buf,
7650 &arg_expr->base.source_position);
7651 } else if (warning.traditional || warning.conversion) {
7652 type_t *const promoted_type = get_default_promoted_type(arg_type);
7653 if (!types_compatible(expected_type_skip, promoted_type) &&
7654 !types_compatible(expected_type_skip, type_void_ptr) &&
7655 !types_compatible(type_void_ptr, promoted_type)) {
7656 /* Deliberately show the skipped types in this warning */
7657 warningf(&arg_expr->base.source_position,
7658 "passing call argument %u as '%T' rather than '%T' due to prototype",
7659 pos, expected_type_skip, promoted_type);
7665 * Parse a call expression, ie. expression '( ... )'.
7667 * @param expression the function address
7669 static expression_t *parse_call_expression(expression_t *expression)
7671 expression_t *result = allocate_expression_zero(EXPR_CALL);
7672 call_expression_t *call = &result->call;
7673 call->function = expression;
7675 type_t *const orig_type = expression->base.type;
7676 type_t *const type = skip_typeref(orig_type);
7678 function_type_t *function_type = NULL;
7679 if (is_type_pointer(type)) {
7680 type_t *const to_type = skip_typeref(type->pointer.points_to);
7682 if (is_type_function(to_type)) {
7683 function_type = &to_type->function;
7684 call->base.type = function_type->return_type;
7688 if (function_type == NULL && is_type_valid(type)) {
7689 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7692 /* parse arguments */
7694 add_anchor_token(')');
7695 add_anchor_token(',');
7697 if (token.type != ')') {
7698 call_argument_t *last_argument = NULL;
7701 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7703 argument->expression = parse_assignment_expression();
7704 if (last_argument == NULL) {
7705 call->arguments = argument;
7707 last_argument->next = argument;
7709 last_argument = argument;
7711 if (token.type != ',')
7716 rem_anchor_token(',');
7717 rem_anchor_token(')');
7720 if (function_type == NULL)
7723 function_parameter_t *parameter = function_type->parameters;
7724 call_argument_t *argument = call->arguments;
7725 if (!function_type->unspecified_parameters) {
7726 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7727 parameter = parameter->next, argument = argument->next) {
7728 check_call_argument(parameter, argument, ++pos);
7731 if (parameter != NULL) {
7732 errorf(HERE, "too few arguments to function '%E'", expression);
7733 } else if (argument != NULL && !function_type->variadic) {
7734 errorf(HERE, "too many arguments to function '%E'", expression);
7738 /* do default promotion */
7739 for( ; argument != NULL; argument = argument->next) {
7740 type_t *type = argument->expression->base.type;
7742 type = get_default_promoted_type(type);
7744 argument->expression
7745 = create_implicit_cast(argument->expression, type);
7748 check_format(&result->call);
7750 if (warning.aggregate_return &&
7751 is_type_compound(skip_typeref(function_type->return_type))) {
7752 warningf(&result->base.source_position,
7753 "function call has aggregate value");
7760 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7762 static bool same_compound_type(const type_t *type1, const type_t *type2)
7765 is_type_compound(type1) &&
7766 type1->kind == type2->kind &&
7767 type1->compound.compound == type2->compound.compound;
7771 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7773 * @param expression the conditional expression
7775 static expression_t *parse_conditional_expression(expression_t *expression)
7777 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7779 conditional_expression_t *conditional = &result->conditional;
7780 conditional->condition = expression;
7783 add_anchor_token(':');
7786 type_t *const condition_type_orig = expression->base.type;
7787 type_t *const condition_type = skip_typeref(condition_type_orig);
7788 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7789 type_error("expected a scalar type in conditional condition",
7790 &expression->base.source_position, condition_type_orig);
7793 expression_t *true_expression = expression;
7794 bool gnu_cond = false;
7795 if (GNU_MODE && token.type == ':') {
7798 true_expression = parse_expression();
7800 rem_anchor_token(':');
7802 expression_t *false_expression =
7803 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7805 type_t *const orig_true_type = true_expression->base.type;
7806 type_t *const orig_false_type = false_expression->base.type;
7807 type_t *const true_type = skip_typeref(orig_true_type);
7808 type_t *const false_type = skip_typeref(orig_false_type);
7811 type_t *result_type;
7812 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7813 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7814 /* ISO/IEC 14882:1998(E) §5.16:2 */
7815 if (true_expression->kind == EXPR_UNARY_THROW) {
7816 result_type = false_type;
7817 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7818 result_type = true_type;
7820 if (warning.other && (
7821 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7822 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7824 warningf(&conditional->base.source_position,
7825 "ISO C forbids conditional expression with only one void side");
7827 result_type = type_void;
7829 } else if (is_type_arithmetic(true_type)
7830 && is_type_arithmetic(false_type)) {
7831 result_type = semantic_arithmetic(true_type, false_type);
7833 true_expression = create_implicit_cast(true_expression, result_type);
7834 false_expression = create_implicit_cast(false_expression, result_type);
7836 conditional->true_expression = true_expression;
7837 conditional->false_expression = false_expression;
7838 conditional->base.type = result_type;
7839 } else if (same_compound_type(true_type, false_type)) {
7840 /* just take 1 of the 2 types */
7841 result_type = true_type;
7842 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7843 type_t *pointer_type;
7845 expression_t *other_expression;
7846 if (is_type_pointer(true_type) &&
7847 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7848 pointer_type = true_type;
7849 other_type = false_type;
7850 other_expression = false_expression;
7852 pointer_type = false_type;
7853 other_type = true_type;
7854 other_expression = true_expression;
7857 if (is_null_pointer_constant(other_expression)) {
7858 result_type = pointer_type;
7859 } else if (is_type_pointer(other_type)) {
7860 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7861 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7864 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7865 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7867 } else if (types_compatible(get_unqualified_type(to1),
7868 get_unqualified_type(to2))) {
7871 if (warning.other) {
7872 warningf(&conditional->base.source_position,
7873 "pointer types '%T' and '%T' in conditional expression are incompatible",
7874 true_type, false_type);
7879 type_t *const type =
7880 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7881 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7882 } else if (is_type_integer(other_type)) {
7883 if (warning.other) {
7884 warningf(&conditional->base.source_position,
7885 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7887 result_type = pointer_type;
7889 if (is_type_valid(other_type)) {
7890 type_error_incompatible("while parsing conditional",
7891 &expression->base.source_position, true_type, false_type);
7893 result_type = type_error_type;
7896 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7897 type_error_incompatible("while parsing conditional",
7898 &conditional->base.source_position, true_type,
7901 result_type = type_error_type;
7904 conditional->true_expression
7905 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7906 conditional->false_expression
7907 = create_implicit_cast(false_expression, result_type);
7908 conditional->base.type = result_type;
7911 return create_invalid_expression();
7915 * Parse an extension expression.
7917 static expression_t *parse_extension(void)
7919 eat(T___extension__);
7921 bool old_gcc_extension = in_gcc_extension;
7922 in_gcc_extension = true;
7923 expression_t *expression = parse_sub_expression(PREC_UNARY);
7924 in_gcc_extension = old_gcc_extension;
7929 * Parse a __builtin_classify_type() expression.
7931 static expression_t *parse_builtin_classify_type(void)
7933 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7934 result->base.type = type_int;
7936 eat(T___builtin_classify_type);
7939 add_anchor_token(')');
7940 expression_t *expression = parse_expression();
7941 rem_anchor_token(')');
7943 result->classify_type.type_expression = expression;
7947 return create_invalid_expression();
7951 * Parse a delete expression
7952 * ISO/IEC 14882:1998(E) §5.3.5
7954 static expression_t *parse_delete(void)
7956 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7957 result->base.type = type_void;
7961 if (token.type == '[') {
7963 result->kind = EXPR_UNARY_DELETE_ARRAY;
7968 expression_t *const value = parse_sub_expression(PREC_CAST);
7969 result->unary.value = value;
7971 type_t *const type = skip_typeref(value->base.type);
7972 if (!is_type_pointer(type)) {
7973 errorf(&value->base.source_position,
7974 "operand of delete must have pointer type");
7975 } else if (warning.other &&
7976 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7977 warningf(&value->base.source_position,
7978 "deleting 'void*' is undefined");
7985 * Parse a throw expression
7986 * ISO/IEC 14882:1998(E) §15:1
7988 static expression_t *parse_throw(void)
7990 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7991 result->base.type = type_void;
7995 expression_t *value = NULL;
7996 switch (token.type) {
7998 value = parse_assignment_expression();
7999 /* ISO/IEC 14882:1998(E) §15.1:3 */
8000 type_t *const orig_type = value->base.type;
8001 type_t *const type = skip_typeref(orig_type);
8002 if (is_type_incomplete(type)) {
8003 errorf(&value->base.source_position,
8004 "cannot throw object of incomplete type '%T'", orig_type);
8005 } else if (is_type_pointer(type)) {
8006 type_t *const points_to = skip_typeref(type->pointer.points_to);
8007 if (is_type_incomplete(points_to) &&
8008 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8009 errorf(&value->base.source_position,
8010 "cannot throw pointer to incomplete type '%T'", orig_type);
8018 result->unary.value = value;
8023 static bool check_pointer_arithmetic(const source_position_t *source_position,
8024 type_t *pointer_type,
8025 type_t *orig_pointer_type)
8027 type_t *points_to = pointer_type->pointer.points_to;
8028 points_to = skip_typeref(points_to);
8030 if (is_type_incomplete(points_to)) {
8031 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8032 errorf(source_position,
8033 "arithmetic with pointer to incomplete type '%T' not allowed",
8036 } else if (warning.pointer_arith) {
8037 warningf(source_position,
8038 "pointer of type '%T' used in arithmetic",
8041 } else if (is_type_function(points_to)) {
8043 errorf(source_position,
8044 "arithmetic with pointer to function type '%T' not allowed",
8047 } else if (warning.pointer_arith) {
8048 warningf(source_position,
8049 "pointer to a function '%T' used in arithmetic",
8056 static bool is_lvalue(const expression_t *expression)
8058 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8059 switch (expression->kind) {
8060 case EXPR_REFERENCE:
8061 case EXPR_ARRAY_ACCESS:
8063 case EXPR_UNARY_DEREFERENCE:
8067 /* Claim it is an lvalue, if the type is invalid. There was a parse
8068 * error before, which maybe prevented properly recognizing it as
8070 return !is_type_valid(skip_typeref(expression->base.type));
8074 static void semantic_incdec(unary_expression_t *expression)
8076 type_t *const orig_type = expression->value->base.type;
8077 type_t *const type = skip_typeref(orig_type);
8078 if (is_type_pointer(type)) {
8079 if (!check_pointer_arithmetic(&expression->base.source_position,
8083 } else if (!is_type_real(type) && is_type_valid(type)) {
8084 /* TODO: improve error message */
8085 errorf(&expression->base.source_position,
8086 "operation needs an arithmetic or pointer type");
8089 if (!is_lvalue(expression->value)) {
8090 /* TODO: improve error message */
8091 errorf(&expression->base.source_position, "lvalue required as operand");
8093 expression->base.type = orig_type;
8096 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8098 type_t *const orig_type = expression->value->base.type;
8099 type_t *const type = skip_typeref(orig_type);
8100 if (!is_type_arithmetic(type)) {
8101 if (is_type_valid(type)) {
8102 /* TODO: improve error message */
8103 errorf(&expression->base.source_position,
8104 "operation needs an arithmetic type");
8109 expression->base.type = orig_type;
8112 static void semantic_unexpr_plus(unary_expression_t *expression)
8114 semantic_unexpr_arithmetic(expression);
8115 if (warning.traditional)
8116 warningf(&expression->base.source_position,
8117 "traditional C rejects the unary plus operator");
8120 static expression_t const *get_reference_address(expression_t const *expr)
8122 bool regular_take_address = true;
8124 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8125 expr = expr->unary.value;
8127 regular_take_address = false;
8130 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8133 expr = expr->unary.value;
8136 /* special case for functions which are automatically converted to a
8137 * pointer to function without an extra TAKE_ADDRESS operation */
8138 if (!regular_take_address && expr->kind == EXPR_REFERENCE
8139 && expr->reference.entity->kind == ENTITY_FUNCTION) {
8146 static void warn_function_address_as_bool(expression_t const* expr)
8148 if (!warning.address)
8151 expr = get_reference_address(expr);
8153 warningf(&expr->base.source_position,
8154 "the address of '%Y' will always evaluate as 'true'",
8155 expr->reference.entity->base.symbol);
8159 static void semantic_not(unary_expression_t *expression)
8161 type_t *const orig_type = expression->value->base.type;
8162 type_t *const type = skip_typeref(orig_type);
8163 if (!is_type_scalar(type) && is_type_valid(type)) {
8164 errorf(&expression->base.source_position,
8165 "operand of ! must be of scalar type");
8168 warn_function_address_as_bool(expression->value);
8170 expression->base.type = type_int;
8173 static void semantic_unexpr_integer(unary_expression_t *expression)
8175 type_t *const orig_type = expression->value->base.type;
8176 type_t *const type = skip_typeref(orig_type);
8177 if (!is_type_integer(type)) {
8178 if (is_type_valid(type)) {
8179 errorf(&expression->base.source_position,
8180 "operand of ~ must be of integer type");
8185 expression->base.type = orig_type;
8188 static void semantic_dereference(unary_expression_t *expression)
8190 type_t *const orig_type = expression->value->base.type;
8191 type_t *const type = skip_typeref(orig_type);
8192 if (!is_type_pointer(type)) {
8193 if (is_type_valid(type)) {
8194 errorf(&expression->base.source_position,
8195 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8200 type_t *result_type = type->pointer.points_to;
8201 result_type = automatic_type_conversion(result_type);
8202 expression->base.type = result_type;
8206 * Record that an address is taken (expression represents an lvalue).
8208 * @param expression the expression
8209 * @param may_be_register if true, the expression might be an register
8211 static void set_address_taken(expression_t *expression, bool may_be_register)
8213 if (expression->kind != EXPR_REFERENCE)
8216 entity_t *const entity = expression->reference.entity;
8218 if (entity->kind != ENTITY_VARIABLE)
8221 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8222 && !may_be_register) {
8223 errorf(&expression->base.source_position,
8224 "address of register variable '%Y' requested",
8225 entity->base.symbol);
8228 entity->variable.address_taken = true;
8232 * Check the semantic of the address taken expression.
8234 static void semantic_take_addr(unary_expression_t *expression)
8236 expression_t *value = expression->value;
8237 value->base.type = revert_automatic_type_conversion(value);
8239 type_t *orig_type = value->base.type;
8240 type_t *type = skip_typeref(orig_type);
8241 if (!is_type_valid(type))
8245 if (value->kind != EXPR_ARRAY_ACCESS
8246 && value->kind != EXPR_UNARY_DEREFERENCE
8247 && !is_lvalue(value)) {
8248 errorf(&expression->base.source_position,
8249 "'&' requires an lvalue");
8251 if (type->kind == TYPE_BITFIELD) {
8252 errorf(&expression->base.source_position,
8253 "'&' not allowed on object with bitfield type '%T'",
8257 set_address_taken(value, false);
8259 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8262 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8263 static expression_t *parse_##unexpression_type(void) \
8265 expression_t *unary_expression \
8266 = allocate_expression_zero(unexpression_type); \
8268 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8270 sfunc(&unary_expression->unary); \
8272 return unary_expression; \
8275 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8276 semantic_unexpr_arithmetic)
8277 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8278 semantic_unexpr_plus)
8279 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8281 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8282 semantic_dereference)
8283 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8285 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8286 semantic_unexpr_integer)
8287 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8289 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8292 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8294 static expression_t *parse_##unexpression_type(expression_t *left) \
8296 expression_t *unary_expression \
8297 = allocate_expression_zero(unexpression_type); \
8299 unary_expression->unary.value = left; \
8301 sfunc(&unary_expression->unary); \
8303 return unary_expression; \
8306 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8307 EXPR_UNARY_POSTFIX_INCREMENT,
8309 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8310 EXPR_UNARY_POSTFIX_DECREMENT,
8313 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8315 /* TODO: handle complex + imaginary types */
8317 type_left = get_unqualified_type(type_left);
8318 type_right = get_unqualified_type(type_right);
8320 /* § 6.3.1.8 Usual arithmetic conversions */
8321 if (type_left == type_long_double || type_right == type_long_double) {
8322 return type_long_double;
8323 } else if (type_left == type_double || type_right == type_double) {
8325 } else if (type_left == type_float || type_right == type_float) {
8329 type_left = promote_integer(type_left);
8330 type_right = promote_integer(type_right);
8332 if (type_left == type_right)
8335 bool const signed_left = is_type_signed(type_left);
8336 bool const signed_right = is_type_signed(type_right);
8337 int const rank_left = get_rank(type_left);
8338 int const rank_right = get_rank(type_right);
8340 if (signed_left == signed_right)
8341 return rank_left >= rank_right ? type_left : type_right;
8350 u_rank = rank_right;
8351 u_type = type_right;
8353 s_rank = rank_right;
8354 s_type = type_right;
8359 if (u_rank >= s_rank)
8362 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8364 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8365 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8369 case ATOMIC_TYPE_INT: return type_unsigned_int;
8370 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8371 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8373 default: panic("invalid atomic type");
8378 * Check the semantic restrictions for a binary expression.
8380 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8382 expression_t *const left = expression->left;
8383 expression_t *const right = expression->right;
8384 type_t *const orig_type_left = left->base.type;
8385 type_t *const orig_type_right = right->base.type;
8386 type_t *const type_left = skip_typeref(orig_type_left);
8387 type_t *const type_right = skip_typeref(orig_type_right);
8389 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8390 /* TODO: improve error message */
8391 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8392 errorf(&expression->base.source_position,
8393 "operation needs arithmetic types");
8398 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8399 expression->left = create_implicit_cast(left, arithmetic_type);
8400 expression->right = create_implicit_cast(right, arithmetic_type);
8401 expression->base.type = arithmetic_type;
8404 static void warn_div_by_zero(binary_expression_t const *const expression)
8406 if (!warning.div_by_zero ||
8407 !is_type_integer(expression->base.type))
8410 expression_t const *const right = expression->right;
8411 /* The type of the right operand can be different for /= */
8412 if (is_type_integer(right->base.type) &&
8413 is_constant_expression(right) &&
8414 fold_constant(right) == 0) {
8415 warningf(&expression->base.source_position, "division by zero");
8420 * Check the semantic restrictions for a div/mod expression.
8422 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8423 semantic_binexpr_arithmetic(expression);
8424 warn_div_by_zero(expression);
8427 static void semantic_shift_op(binary_expression_t *expression)
8429 expression_t *const left = expression->left;
8430 expression_t *const right = expression->right;
8431 type_t *const orig_type_left = left->base.type;
8432 type_t *const orig_type_right = right->base.type;
8433 type_t * type_left = skip_typeref(orig_type_left);
8434 type_t * type_right = skip_typeref(orig_type_right);
8436 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8437 /* TODO: improve error message */
8438 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8439 errorf(&expression->base.source_position,
8440 "operands of shift operation must have integer types");
8445 type_left = promote_integer(type_left);
8446 type_right = promote_integer(type_right);
8448 expression->left = create_implicit_cast(left, type_left);
8449 expression->right = create_implicit_cast(right, type_right);
8450 expression->base.type = type_left;
8453 static void semantic_add(binary_expression_t *expression)
8455 expression_t *const left = expression->left;
8456 expression_t *const right = expression->right;
8457 type_t *const orig_type_left = left->base.type;
8458 type_t *const orig_type_right = right->base.type;
8459 type_t *const type_left = skip_typeref(orig_type_left);
8460 type_t *const type_right = skip_typeref(orig_type_right);
8463 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8464 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8465 expression->left = create_implicit_cast(left, arithmetic_type);
8466 expression->right = create_implicit_cast(right, arithmetic_type);
8467 expression->base.type = arithmetic_type;
8469 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8470 check_pointer_arithmetic(&expression->base.source_position,
8471 type_left, orig_type_left);
8472 expression->base.type = type_left;
8473 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8474 check_pointer_arithmetic(&expression->base.source_position,
8475 type_right, orig_type_right);
8476 expression->base.type = type_right;
8477 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8478 errorf(&expression->base.source_position,
8479 "invalid operands to binary + ('%T', '%T')",
8480 orig_type_left, orig_type_right);
8484 static void semantic_sub(binary_expression_t *expression)
8486 expression_t *const left = expression->left;
8487 expression_t *const right = expression->right;
8488 type_t *const orig_type_left = left->base.type;
8489 type_t *const orig_type_right = right->base.type;
8490 type_t *const type_left = skip_typeref(orig_type_left);
8491 type_t *const type_right = skip_typeref(orig_type_right);
8492 source_position_t const *const pos = &expression->base.source_position;
8495 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8496 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8497 expression->left = create_implicit_cast(left, arithmetic_type);
8498 expression->right = create_implicit_cast(right, arithmetic_type);
8499 expression->base.type = arithmetic_type;
8501 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8502 check_pointer_arithmetic(&expression->base.source_position,
8503 type_left, orig_type_left);
8504 expression->base.type = type_left;
8505 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8506 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8507 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8508 if (!types_compatible(unqual_left, unqual_right)) {
8510 "subtracting pointers to incompatible types '%T' and '%T'",
8511 orig_type_left, orig_type_right);
8512 } else if (!is_type_object(unqual_left)) {
8513 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8514 errorf(pos, "subtracting pointers to non-object types '%T'",
8516 } else if (warning.other) {
8517 warningf(pos, "subtracting pointers to void");
8520 expression->base.type = type_ptrdiff_t;
8521 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8522 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8523 orig_type_left, orig_type_right);
8527 static void warn_string_literal_address(expression_t const* expr)
8529 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8530 expr = expr->unary.value;
8531 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8533 expr = expr->unary.value;
8536 if (expr->kind == EXPR_STRING_LITERAL ||
8537 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8538 warningf(&expr->base.source_position,
8539 "comparison with string literal results in unspecified behaviour");
8544 * Check the semantics of comparison expressions.
8546 * @param expression The expression to check.
8548 static void semantic_comparison(binary_expression_t *expression)
8550 expression_t *left = expression->left;
8551 expression_t *right = expression->right;
8553 if (warning.address) {
8554 warn_string_literal_address(left);
8555 warn_string_literal_address(right);
8557 expression_t const* const func_left = get_reference_address(left);
8558 if (func_left != NULL && is_null_pointer_constant(right)) {
8559 warningf(&expression->base.source_position,
8560 "the address of '%Y' will never be NULL",
8561 func_left->reference.entity->base.symbol);
8564 expression_t const* const func_right = get_reference_address(right);
8565 if (func_right != NULL && is_null_pointer_constant(right)) {
8566 warningf(&expression->base.source_position,
8567 "the address of '%Y' will never be NULL",
8568 func_right->reference.entity->base.symbol);
8572 type_t *orig_type_left = left->base.type;
8573 type_t *orig_type_right = right->base.type;
8574 type_t *type_left = skip_typeref(orig_type_left);
8575 type_t *type_right = skip_typeref(orig_type_right);
8577 /* TODO non-arithmetic types */
8578 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8579 /* test for signed vs unsigned compares */
8580 if (warning.sign_compare &&
8581 (expression->base.kind != EXPR_BINARY_EQUAL &&
8582 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8583 (is_type_signed(type_left) != is_type_signed(type_right))) {
8585 /* check if 1 of the operands is a constant, in this case we just
8586 * check wether we can safely represent the resulting constant in
8587 * the type of the other operand. */
8588 expression_t *const_expr = NULL;
8589 expression_t *other_expr = NULL;
8591 if (is_constant_expression(left)) {
8594 } else if (is_constant_expression(right)) {
8599 if (const_expr != NULL) {
8600 type_t *other_type = skip_typeref(other_expr->base.type);
8601 long val = fold_constant(const_expr);
8602 /* TODO: check if val can be represented by other_type */
8606 warningf(&expression->base.source_position,
8607 "comparison between signed and unsigned");
8609 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8610 expression->left = create_implicit_cast(left, arithmetic_type);
8611 expression->right = create_implicit_cast(right, arithmetic_type);
8612 expression->base.type = arithmetic_type;
8613 if (warning.float_equal &&
8614 (expression->base.kind == EXPR_BINARY_EQUAL ||
8615 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8616 is_type_float(arithmetic_type)) {
8617 warningf(&expression->base.source_position,
8618 "comparing floating point with == or != is unsafe");
8620 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8621 /* TODO check compatibility */
8622 } else if (is_type_pointer(type_left)) {
8623 expression->right = create_implicit_cast(right, type_left);
8624 } else if (is_type_pointer(type_right)) {
8625 expression->left = create_implicit_cast(left, type_right);
8626 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8627 type_error_incompatible("invalid operands in comparison",
8628 &expression->base.source_position,
8629 type_left, type_right);
8631 expression->base.type = type_int;
8635 * Checks if a compound type has constant fields.
8637 static bool has_const_fields(const compound_type_t *type)
8639 compound_t *compound = type->compound;
8640 entity_t *entry = compound->members.entities;
8642 for (; entry != NULL; entry = entry->base.next) {
8643 if (!is_declaration(entry))
8646 const type_t *decl_type = skip_typeref(entry->declaration.type);
8647 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8654 static bool is_valid_assignment_lhs(expression_t const* const left)
8656 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8657 type_t *const type_left = skip_typeref(orig_type_left);
8659 if (!is_lvalue(left)) {
8660 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8665 if (is_type_array(type_left)) {
8666 errorf(HERE, "cannot assign to arrays ('%E')", left);
8669 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8670 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8674 if (is_type_incomplete(type_left)) {
8675 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8676 left, orig_type_left);
8679 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8680 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8681 left, orig_type_left);
8688 static void semantic_arithmetic_assign(binary_expression_t *expression)
8690 expression_t *left = expression->left;
8691 expression_t *right = expression->right;
8692 type_t *orig_type_left = left->base.type;
8693 type_t *orig_type_right = right->base.type;
8695 if (!is_valid_assignment_lhs(left))
8698 type_t *type_left = skip_typeref(orig_type_left);
8699 type_t *type_right = skip_typeref(orig_type_right);
8701 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8702 /* TODO: improve error message */
8703 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8704 errorf(&expression->base.source_position,
8705 "operation needs arithmetic types");
8710 /* combined instructions are tricky. We can't create an implicit cast on
8711 * the left side, because we need the uncasted form for the store.
8712 * The ast2firm pass has to know that left_type must be right_type
8713 * for the arithmetic operation and create a cast by itself */
8714 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8715 expression->right = create_implicit_cast(right, arithmetic_type);
8716 expression->base.type = type_left;
8719 static void semantic_divmod_assign(binary_expression_t *expression)
8721 semantic_arithmetic_assign(expression);
8722 warn_div_by_zero(expression);
8725 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8727 expression_t *const left = expression->left;
8728 expression_t *const right = expression->right;
8729 type_t *const orig_type_left = left->base.type;
8730 type_t *const orig_type_right = right->base.type;
8731 type_t *const type_left = skip_typeref(orig_type_left);
8732 type_t *const type_right = skip_typeref(orig_type_right);
8734 if (!is_valid_assignment_lhs(left))
8737 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8738 /* combined instructions are tricky. We can't create an implicit cast on
8739 * the left side, because we need the uncasted form for the store.
8740 * The ast2firm pass has to know that left_type must be right_type
8741 * for the arithmetic operation and create a cast by itself */
8742 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8743 expression->right = create_implicit_cast(right, arithmetic_type);
8744 expression->base.type = type_left;
8745 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8746 check_pointer_arithmetic(&expression->base.source_position,
8747 type_left, orig_type_left);
8748 expression->base.type = type_left;
8749 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8750 errorf(&expression->base.source_position,
8751 "incompatible types '%T' and '%T' in assignment",
8752 orig_type_left, orig_type_right);
8757 * Check the semantic restrictions of a logical expression.
8759 static void semantic_logical_op(binary_expression_t *expression)
8761 expression_t *const left = expression->left;
8762 expression_t *const right = expression->right;
8763 type_t *const orig_type_left = left->base.type;
8764 type_t *const orig_type_right = right->base.type;
8765 type_t *const type_left = skip_typeref(orig_type_left);
8766 type_t *const type_right = skip_typeref(orig_type_right);
8768 warn_function_address_as_bool(left);
8769 warn_function_address_as_bool(right);
8771 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8772 /* TODO: improve error message */
8773 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8774 errorf(&expression->base.source_position,
8775 "operation needs scalar types");
8780 expression->base.type = type_int;
8784 * Check the semantic restrictions of a binary assign expression.
8786 static void semantic_binexpr_assign(binary_expression_t *expression)
8788 expression_t *left = expression->left;
8789 type_t *orig_type_left = left->base.type;
8791 if (!is_valid_assignment_lhs(left))
8794 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8795 report_assign_error(error, orig_type_left, expression->right,
8796 "assignment", &left->base.source_position);
8797 expression->right = create_implicit_cast(expression->right, orig_type_left);
8798 expression->base.type = orig_type_left;
8802 * Determine if the outermost operation (or parts thereof) of the given
8803 * expression has no effect in order to generate a warning about this fact.
8804 * Therefore in some cases this only examines some of the operands of the
8805 * expression (see comments in the function and examples below).
8807 * f() + 23; // warning, because + has no effect
8808 * x || f(); // no warning, because x controls execution of f()
8809 * x ? y : f(); // warning, because y has no effect
8810 * (void)x; // no warning to be able to suppress the warning
8811 * This function can NOT be used for an "expression has definitely no effect"-
8813 static bool expression_has_effect(const expression_t *const expr)
8815 switch (expr->kind) {
8816 case EXPR_UNKNOWN: break;
8817 case EXPR_INVALID: return true; /* do NOT warn */
8818 case EXPR_REFERENCE: return false;
8819 case EXPR_REFERENCE_ENUM_VALUE: return false;
8820 /* suppress the warning for microsoft __noop operations */
8821 case EXPR_CONST: return expr->conste.is_ms_noop;
8822 case EXPR_CHARACTER_CONSTANT: return false;
8823 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8824 case EXPR_STRING_LITERAL: return false;
8825 case EXPR_WIDE_STRING_LITERAL: return false;
8826 case EXPR_LABEL_ADDRESS: return false;
8829 const call_expression_t *const call = &expr->call;
8830 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8833 switch (call->function->builtin_symbol.symbol->ID) {
8834 case T___builtin_va_end: return true;
8835 default: return false;
8839 /* Generate the warning if either the left or right hand side of a
8840 * conditional expression has no effect */
8841 case EXPR_CONDITIONAL: {
8842 const conditional_expression_t *const cond = &expr->conditional;
8844 expression_has_effect(cond->true_expression) &&
8845 expression_has_effect(cond->false_expression);
8848 case EXPR_SELECT: return false;
8849 case EXPR_ARRAY_ACCESS: return false;
8850 case EXPR_SIZEOF: return false;
8851 case EXPR_CLASSIFY_TYPE: return false;
8852 case EXPR_ALIGNOF: return false;
8854 case EXPR_FUNCNAME: return false;
8855 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8856 case EXPR_BUILTIN_CONSTANT_P: return false;
8857 case EXPR_BUILTIN_PREFETCH: return true;
8858 case EXPR_OFFSETOF: return false;
8859 case EXPR_VA_START: return true;
8860 case EXPR_VA_ARG: return true;
8861 case EXPR_STATEMENT: return true; // TODO
8862 case EXPR_COMPOUND_LITERAL: return false;
8864 case EXPR_UNARY_NEGATE: return false;
8865 case EXPR_UNARY_PLUS: return false;
8866 case EXPR_UNARY_BITWISE_NEGATE: return false;
8867 case EXPR_UNARY_NOT: return false;
8868 case EXPR_UNARY_DEREFERENCE: return false;
8869 case EXPR_UNARY_TAKE_ADDRESS: return false;
8870 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8871 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8872 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8873 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8875 /* Treat void casts as if they have an effect in order to being able to
8876 * suppress the warning */
8877 case EXPR_UNARY_CAST: {
8878 type_t *const type = skip_typeref(expr->base.type);
8879 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8882 case EXPR_UNARY_CAST_IMPLICIT: return true;
8883 case EXPR_UNARY_ASSUME: return true;
8884 case EXPR_UNARY_DELETE: return true;
8885 case EXPR_UNARY_DELETE_ARRAY: return true;
8886 case EXPR_UNARY_THROW: return true;
8888 case EXPR_BINARY_ADD: return false;
8889 case EXPR_BINARY_SUB: return false;
8890 case EXPR_BINARY_MUL: return false;
8891 case EXPR_BINARY_DIV: return false;
8892 case EXPR_BINARY_MOD: return false;
8893 case EXPR_BINARY_EQUAL: return false;
8894 case EXPR_BINARY_NOTEQUAL: return false;
8895 case EXPR_BINARY_LESS: return false;
8896 case EXPR_BINARY_LESSEQUAL: return false;
8897 case EXPR_BINARY_GREATER: return false;
8898 case EXPR_BINARY_GREATEREQUAL: return false;
8899 case EXPR_BINARY_BITWISE_AND: return false;
8900 case EXPR_BINARY_BITWISE_OR: return false;
8901 case EXPR_BINARY_BITWISE_XOR: return false;
8902 case EXPR_BINARY_SHIFTLEFT: return false;
8903 case EXPR_BINARY_SHIFTRIGHT: return false;
8904 case EXPR_BINARY_ASSIGN: return true;
8905 case EXPR_BINARY_MUL_ASSIGN: return true;
8906 case EXPR_BINARY_DIV_ASSIGN: return true;
8907 case EXPR_BINARY_MOD_ASSIGN: return true;
8908 case EXPR_BINARY_ADD_ASSIGN: return true;
8909 case EXPR_BINARY_SUB_ASSIGN: return true;
8910 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8911 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8912 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8913 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8914 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8916 /* Only examine the right hand side of && and ||, because the left hand
8917 * side already has the effect of controlling the execution of the right
8919 case EXPR_BINARY_LOGICAL_AND:
8920 case EXPR_BINARY_LOGICAL_OR:
8921 /* Only examine the right hand side of a comma expression, because the left
8922 * hand side has a separate warning */
8923 case EXPR_BINARY_COMMA:
8924 return expression_has_effect(expr->binary.right);
8926 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8927 case EXPR_BINARY_ISGREATER: return false;
8928 case EXPR_BINARY_ISGREATEREQUAL: return false;
8929 case EXPR_BINARY_ISLESS: return false;
8930 case EXPR_BINARY_ISLESSEQUAL: return false;
8931 case EXPR_BINARY_ISLESSGREATER: return false;
8932 case EXPR_BINARY_ISUNORDERED: return false;
8935 internal_errorf(HERE, "unexpected expression");
8938 static void semantic_comma(binary_expression_t *expression)
8940 if (warning.unused_value) {
8941 const expression_t *const left = expression->left;
8942 if (!expression_has_effect(left)) {
8943 warningf(&left->base.source_position,
8944 "left-hand operand of comma expression has no effect");
8947 expression->base.type = expression->right->base.type;
8951 * @param prec_r precedence of the right operand
8953 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8954 static expression_t *parse_##binexpression_type(expression_t *left) \
8956 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8957 binexpr->binary.left = left; \
8960 expression_t *right = parse_sub_expression(prec_r); \
8962 binexpr->binary.right = right; \
8963 sfunc(&binexpr->binary); \
8968 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8969 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8970 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8971 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8972 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8973 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8974 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8975 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8976 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8977 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8978 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8979 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8980 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8981 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8982 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8983 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8984 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8985 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8986 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8987 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8988 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8989 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8990 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8991 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8992 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8993 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8994 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8995 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8996 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8997 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9000 static expression_t *parse_sub_expression(precedence_t precedence)
9002 if (token.type < 0) {
9003 return expected_expression_error();
9006 expression_parser_function_t *parser
9007 = &expression_parsers[token.type];
9008 source_position_t source_position = token.source_position;
9011 if (parser->parser != NULL) {
9012 left = parser->parser();
9014 left = parse_primary_expression();
9016 assert(left != NULL);
9017 left->base.source_position = source_position;
9020 if (token.type < 0) {
9021 return expected_expression_error();
9024 parser = &expression_parsers[token.type];
9025 if (parser->infix_parser == NULL)
9027 if (parser->infix_precedence < precedence)
9030 left = parser->infix_parser(left);
9032 assert(left != NULL);
9033 assert(left->kind != EXPR_UNKNOWN);
9034 left->base.source_position = source_position;
9041 * Parse an expression.
9043 static expression_t *parse_expression(void)
9045 return parse_sub_expression(PREC_EXPRESSION);
9049 * Register a parser for a prefix-like operator.
9051 * @param parser the parser function
9052 * @param token_type the token type of the prefix token
9054 static void register_expression_parser(parse_expression_function parser,
9057 expression_parser_function_t *entry = &expression_parsers[token_type];
9059 if (entry->parser != NULL) {
9060 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9061 panic("trying to register multiple expression parsers for a token");
9063 entry->parser = parser;
9067 * Register a parser for an infix operator with given precedence.
9069 * @param parser the parser function
9070 * @param token_type the token type of the infix operator
9071 * @param precedence the precedence of the operator
9073 static void register_infix_parser(parse_expression_infix_function parser,
9074 int token_type, unsigned precedence)
9076 expression_parser_function_t *entry = &expression_parsers[token_type];
9078 if (entry->infix_parser != NULL) {
9079 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9080 panic("trying to register multiple infix expression parsers for a "
9083 entry->infix_parser = parser;
9084 entry->infix_precedence = precedence;
9088 * Initialize the expression parsers.
9090 static void init_expression_parsers(void)
9092 memset(&expression_parsers, 0, sizeof(expression_parsers));
9094 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9095 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9096 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9097 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9098 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9099 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9100 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9101 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9102 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9103 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9104 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9105 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9106 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9107 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9108 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9109 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9110 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9111 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9112 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9113 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9114 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9115 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9116 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9117 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9118 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9119 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9120 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9121 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9122 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9123 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9124 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9125 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9126 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9127 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9128 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9129 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9130 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9132 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9133 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9134 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9135 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9136 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9137 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9138 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9139 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9140 register_expression_parser(parse_sizeof, T_sizeof);
9141 register_expression_parser(parse_alignof, T___alignof__);
9142 register_expression_parser(parse_extension, T___extension__);
9143 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9144 register_expression_parser(parse_delete, T_delete);
9145 register_expression_parser(parse_throw, T_throw);
9149 * Parse a asm statement arguments specification.
9151 static asm_argument_t *parse_asm_arguments(bool is_out)
9153 asm_argument_t *result = NULL;
9154 asm_argument_t *last = NULL;
9156 while (token.type == T_STRING_LITERAL || token.type == '[') {
9157 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9158 memset(argument, 0, sizeof(argument[0]));
9160 if (token.type == '[') {
9162 if (token.type != T_IDENTIFIER) {
9163 parse_error_expected("while parsing asm argument",
9164 T_IDENTIFIER, NULL);
9167 argument->symbol = token.v.symbol;
9172 argument->constraints = parse_string_literals();
9174 add_anchor_token(')');
9175 expression_t *expression = parse_expression();
9176 rem_anchor_token(')');
9178 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9179 * change size or type representation (e.g. int -> long is ok, but
9180 * int -> float is not) */
9181 if (expression->kind == EXPR_UNARY_CAST) {
9182 type_t *const type = expression->base.type;
9183 type_kind_t const kind = type->kind;
9184 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9187 if (kind == TYPE_ATOMIC) {
9188 atomic_type_kind_t const akind = type->atomic.akind;
9189 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9190 size = get_atomic_type_size(akind);
9192 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9193 size = get_atomic_type_size(get_intptr_kind());
9197 expression_t *const value = expression->unary.value;
9198 type_t *const value_type = value->base.type;
9199 type_kind_t const value_kind = value_type->kind;
9201 unsigned value_flags;
9202 unsigned value_size;
9203 if (value_kind == TYPE_ATOMIC) {
9204 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9205 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9206 value_size = get_atomic_type_size(value_akind);
9207 } else if (value_kind == TYPE_POINTER) {
9208 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9209 value_size = get_atomic_type_size(get_intptr_kind());
9214 if (value_flags != flags || value_size != size)
9218 } while (expression->kind == EXPR_UNARY_CAST);
9222 if (!is_lvalue(expression)) {
9223 errorf(&expression->base.source_position,
9224 "asm output argument is not an lvalue");
9227 if (argument->constraints.begin[0] == '+')
9228 mark_vars_read(expression, NULL);
9230 mark_vars_read(expression, NULL);
9232 argument->expression = expression;
9235 set_address_taken(expression, true);
9238 last->next = argument;
9244 if (token.type != ',')
9255 * Parse a asm statement clobber specification.
9257 static asm_clobber_t *parse_asm_clobbers(void)
9259 asm_clobber_t *result = NULL;
9260 asm_clobber_t *last = NULL;
9262 while(token.type == T_STRING_LITERAL) {
9263 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9264 clobber->clobber = parse_string_literals();
9267 last->next = clobber;
9273 if (token.type != ',')
9282 * Parse an asm statement.
9284 static statement_t *parse_asm_statement(void)
9286 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9287 asm_statement_t *asm_statement = &statement->asms;
9291 if (token.type == T_volatile) {
9293 asm_statement->is_volatile = true;
9297 add_anchor_token(')');
9298 add_anchor_token(':');
9299 asm_statement->asm_text = parse_string_literals();
9301 if (token.type != ':') {
9302 rem_anchor_token(':');
9307 asm_statement->outputs = parse_asm_arguments(true);
9308 if (token.type != ':') {
9309 rem_anchor_token(':');
9314 asm_statement->inputs = parse_asm_arguments(false);
9315 if (token.type != ':') {
9316 rem_anchor_token(':');
9319 rem_anchor_token(':');
9322 asm_statement->clobbers = parse_asm_clobbers();
9325 rem_anchor_token(')');
9329 if (asm_statement->outputs == NULL) {
9330 /* GCC: An 'asm' instruction without any output operands will be treated
9331 * identically to a volatile 'asm' instruction. */
9332 asm_statement->is_volatile = true;
9337 return create_invalid_statement();
9341 * Parse a case statement.
9343 static statement_t *parse_case_statement(void)
9345 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9346 source_position_t *const pos = &statement->base.source_position;
9350 expression_t *const expression = parse_expression();
9351 statement->case_label.expression = expression;
9352 if (!is_constant_expression(expression)) {
9353 /* This check does not prevent the error message in all cases of an
9354 * prior error while parsing the expression. At least it catches the
9355 * common case of a mistyped enum entry. */
9356 if (is_type_valid(skip_typeref(expression->base.type))) {
9357 errorf(pos, "case label does not reduce to an integer constant");
9359 statement->case_label.is_bad = true;
9361 long const val = fold_constant(expression);
9362 statement->case_label.first_case = val;
9363 statement->case_label.last_case = val;
9367 if (token.type == T_DOTDOTDOT) {
9369 expression_t *const end_range = parse_expression();
9370 statement->case_label.end_range = end_range;
9371 if (!is_constant_expression(end_range)) {
9372 /* This check does not prevent the error message in all cases of an
9373 * prior error while parsing the expression. At least it catches the
9374 * common case of a mistyped enum entry. */
9375 if (is_type_valid(skip_typeref(end_range->base.type))) {
9376 errorf(pos, "case range does not reduce to an integer constant");
9378 statement->case_label.is_bad = true;
9380 long const val = fold_constant(end_range);
9381 statement->case_label.last_case = val;
9383 if (warning.other && val < statement->case_label.first_case) {
9384 statement->case_label.is_empty_range = true;
9385 warningf(pos, "empty range specified");
9391 PUSH_PARENT(statement);
9395 if (current_switch != NULL) {
9396 if (! statement->case_label.is_bad) {
9397 /* Check for duplicate case values */
9398 case_label_statement_t *c = &statement->case_label;
9399 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9400 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9403 if (c->last_case < l->first_case || c->first_case > l->last_case)
9406 errorf(pos, "duplicate case value (previously used %P)",
9407 &l->base.source_position);
9411 /* link all cases into the switch statement */
9412 if (current_switch->last_case == NULL) {
9413 current_switch->first_case = &statement->case_label;
9415 current_switch->last_case->next = &statement->case_label;
9417 current_switch->last_case = &statement->case_label;
9419 errorf(pos, "case label not within a switch statement");
9422 statement_t *const inner_stmt = parse_statement();
9423 statement->case_label.statement = inner_stmt;
9424 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9425 errorf(&inner_stmt->base.source_position, "declaration after case label");
9432 return create_invalid_statement();
9436 * Parse a default statement.
9438 static statement_t *parse_default_statement(void)
9440 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9444 PUSH_PARENT(statement);
9447 if (current_switch != NULL) {
9448 const case_label_statement_t *def_label = current_switch->default_label;
9449 if (def_label != NULL) {
9450 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9451 &def_label->base.source_position);
9453 current_switch->default_label = &statement->case_label;
9455 /* link all cases into the switch statement */
9456 if (current_switch->last_case == NULL) {
9457 current_switch->first_case = &statement->case_label;
9459 current_switch->last_case->next = &statement->case_label;
9461 current_switch->last_case = &statement->case_label;
9464 errorf(&statement->base.source_position,
9465 "'default' label not within a switch statement");
9468 statement_t *const inner_stmt = parse_statement();
9469 statement->case_label.statement = inner_stmt;
9470 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9471 errorf(&inner_stmt->base.source_position, "declaration after default label");
9478 return create_invalid_statement();
9482 * Parse a label statement.
9484 static statement_t *parse_label_statement(void)
9486 assert(token.type == T_IDENTIFIER);
9487 symbol_t *symbol = token.v.symbol;
9488 label_t *label = get_label(symbol);
9490 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9491 statement->label.label = label;
9495 PUSH_PARENT(statement);
9497 /* if statement is already set then the label is defined twice,
9498 * otherwise it was just mentioned in a goto/local label declaration so far
9500 if (label->statement != NULL) {
9501 errorf(HERE, "duplicate label '%Y' (declared %P)",
9502 symbol, &label->base.source_position);
9504 label->base.source_position = token.source_position;
9505 label->statement = statement;
9510 if (token.type == '}') {
9511 /* TODO only warn? */
9512 if (warning.other && false) {
9513 warningf(HERE, "label at end of compound statement");
9514 statement->label.statement = create_empty_statement();
9516 errorf(HERE, "label at end of compound statement");
9517 statement->label.statement = create_invalid_statement();
9519 } else if (token.type == ';') {
9520 /* Eat an empty statement here, to avoid the warning about an empty
9521 * statement after a label. label:; is commonly used to have a label
9522 * before a closing brace. */
9523 statement->label.statement = create_empty_statement();
9526 statement_t *const inner_stmt = parse_statement();
9527 statement->label.statement = inner_stmt;
9528 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9529 errorf(&inner_stmt->base.source_position, "declaration after label");
9533 /* remember the labels in a list for later checking */
9534 if (label_last == NULL) {
9535 label_first = &statement->label;
9537 label_last->next = &statement->label;
9539 label_last = &statement->label;
9546 * Parse an if statement.
9548 static statement_t *parse_if(void)
9550 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9554 PUSH_PARENT(statement);
9556 add_anchor_token('{');
9559 add_anchor_token(')');
9560 expression_t *const expr = parse_expression();
9561 statement->ifs.condition = expr;
9562 mark_vars_read(expr, NULL);
9563 rem_anchor_token(')');
9567 rem_anchor_token('{');
9569 add_anchor_token(T_else);
9570 statement->ifs.true_statement = parse_statement();
9571 rem_anchor_token(T_else);
9573 if (token.type == T_else) {
9575 statement->ifs.false_statement = parse_statement();
9583 * Check that all enums are handled in a switch.
9585 * @param statement the switch statement to check
9587 static void check_enum_cases(const switch_statement_t *statement) {
9588 const type_t *type = skip_typeref(statement->expression->base.type);
9589 if (! is_type_enum(type))
9591 const enum_type_t *enumt = &type->enumt;
9593 /* if we have a default, no warnings */
9594 if (statement->default_label != NULL)
9597 /* FIXME: calculation of value should be done while parsing */
9598 /* TODO: quadratic algorithm here. Change to an n log n one */
9599 long last_value = -1;
9600 const entity_t *entry = enumt->enume->base.next;
9601 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9602 entry = entry->base.next) {
9603 const expression_t *expression = entry->enum_value.value;
9604 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9606 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9607 if (l->expression == NULL)
9609 if (l->first_case <= value && value <= l->last_case) {
9615 warningf(&statement->base.source_position,
9616 "enumeration value '%Y' not handled in switch",
9617 entry->base.symbol);
9624 * Parse a switch statement.
9626 static statement_t *parse_switch(void)
9628 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9632 PUSH_PARENT(statement);
9635 add_anchor_token(')');
9636 expression_t *const expr = parse_expression();
9637 mark_vars_read(expr, NULL);
9638 type_t * type = skip_typeref(expr->base.type);
9639 if (is_type_integer(type)) {
9640 type = promote_integer(type);
9641 if (warning.traditional) {
9642 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9643 warningf(&expr->base.source_position,
9644 "'%T' switch expression not converted to '%T' in ISO C",
9648 } else if (is_type_valid(type)) {
9649 errorf(&expr->base.source_position,
9650 "switch quantity is not an integer, but '%T'", type);
9651 type = type_error_type;
9653 statement->switchs.expression = create_implicit_cast(expr, type);
9655 rem_anchor_token(')');
9657 switch_statement_t *rem = current_switch;
9658 current_switch = &statement->switchs;
9659 statement->switchs.body = parse_statement();
9660 current_switch = rem;
9662 if (warning.switch_default &&
9663 statement->switchs.default_label == NULL) {
9664 warningf(&statement->base.source_position, "switch has no default case");
9666 if (warning.switch_enum)
9667 check_enum_cases(&statement->switchs);
9673 return create_invalid_statement();
9676 static statement_t *parse_loop_body(statement_t *const loop)
9678 statement_t *const rem = current_loop;
9679 current_loop = loop;
9681 statement_t *const body = parse_statement();
9688 * Parse a while statement.
9690 static statement_t *parse_while(void)
9692 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9696 PUSH_PARENT(statement);
9699 add_anchor_token(')');
9700 expression_t *const cond = parse_expression();
9701 statement->whiles.condition = cond;
9702 mark_vars_read(cond, NULL);
9703 rem_anchor_token(')');
9706 statement->whiles.body = parse_loop_body(statement);
9712 return create_invalid_statement();
9716 * Parse a do statement.
9718 static statement_t *parse_do(void)
9720 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9724 PUSH_PARENT(statement);
9726 add_anchor_token(T_while);
9727 statement->do_while.body = parse_loop_body(statement);
9728 rem_anchor_token(T_while);
9732 add_anchor_token(')');
9733 expression_t *const cond = parse_expression();
9734 statement->do_while.condition = cond;
9735 mark_vars_read(cond, NULL);
9736 rem_anchor_token(')');
9744 return create_invalid_statement();
9748 * Parse a for statement.
9750 static statement_t *parse_for(void)
9752 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9756 PUSH_PARENT(statement);
9758 size_t const top = environment_top();
9759 scope_push(&statement->fors.scope);
9762 add_anchor_token(')');
9764 if (token.type != ';') {
9765 if (is_declaration_specifier(&token, false)) {
9766 parse_declaration(record_entity);
9768 add_anchor_token(';');
9769 expression_t *const init = parse_expression();
9770 statement->fors.initialisation = init;
9771 mark_vars_read(init, VAR_ANY);
9772 if (warning.unused_value && !expression_has_effect(init)) {
9773 warningf(&init->base.source_position,
9774 "initialisation of 'for'-statement has no effect");
9776 rem_anchor_token(';');
9783 if (token.type != ';') {
9784 add_anchor_token(';');
9785 expression_t *const cond = parse_expression();
9786 statement->fors.condition = cond;
9787 mark_vars_read(cond, NULL);
9788 rem_anchor_token(';');
9791 if (token.type != ')') {
9792 expression_t *const step = parse_expression();
9793 statement->fors.step = step;
9794 mark_vars_read(step, VAR_ANY);
9795 if (warning.unused_value && !expression_has_effect(step)) {
9796 warningf(&step->base.source_position,
9797 "step of 'for'-statement has no effect");
9801 rem_anchor_token(')');
9802 statement->fors.body = parse_loop_body(statement);
9804 assert(scope == &statement->fors.scope);
9806 environment_pop_to(top);
9813 rem_anchor_token(')');
9814 assert(scope == &statement->fors.scope);
9816 environment_pop_to(top);
9818 return create_invalid_statement();
9822 * Parse a goto statement.
9824 static statement_t *parse_goto(void)
9826 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9829 if (GNU_MODE && token.type == '*') {
9831 expression_t *expression = parse_expression();
9832 mark_vars_read(expression, NULL);
9834 /* Argh: although documentation say the expression must be of type void *,
9835 * gcc excepts anything that can be casted into void * without error */
9836 type_t *type = expression->base.type;
9838 if (type != type_error_type) {
9839 if (!is_type_pointer(type) && !is_type_integer(type)) {
9840 errorf(&expression->base.source_position,
9841 "cannot convert to a pointer type");
9842 } else if (warning.other && type != type_void_ptr) {
9843 warningf(&expression->base.source_position,
9844 "type of computed goto expression should be 'void*' not '%T'", type);
9846 expression = create_implicit_cast(expression, type_void_ptr);
9849 statement->gotos.expression = expression;
9851 if (token.type != T_IDENTIFIER) {
9853 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9855 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9859 symbol_t *symbol = token.v.symbol;
9862 statement->gotos.label = get_label(symbol);
9865 /* remember the goto's in a list for later checking */
9866 if (goto_last == NULL) {
9867 goto_first = &statement->gotos;
9869 goto_last->next = &statement->gotos;
9871 goto_last = &statement->gotos;
9877 return create_invalid_statement();
9881 * Parse a continue statement.
9883 static statement_t *parse_continue(void)
9885 if (current_loop == NULL) {
9886 errorf(HERE, "continue statement not within loop");
9889 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9899 * Parse a break statement.
9901 static statement_t *parse_break(void)
9903 if (current_switch == NULL && current_loop == NULL) {
9904 errorf(HERE, "break statement not within loop or switch");
9907 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9917 * Parse a __leave statement.
9919 static statement_t *parse_leave_statement(void)
9921 if (current_try == NULL) {
9922 errorf(HERE, "__leave statement not within __try");
9925 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9935 * Check if a given entity represents a local variable.
9937 static bool is_local_variable(const entity_t *entity)
9939 if (entity->kind != ENTITY_VARIABLE)
9942 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9943 case STORAGE_CLASS_AUTO:
9944 case STORAGE_CLASS_REGISTER: {
9945 const type_t *type = skip_typeref(entity->declaration.type);
9946 if (is_type_function(type)) {
9958 * Check if a given expression represents a local variable.
9960 static bool expression_is_local_variable(const expression_t *expression)
9962 if (expression->base.kind != EXPR_REFERENCE) {
9965 const entity_t *entity = expression->reference.entity;
9966 return is_local_variable(entity);
9970 * Check if a given expression represents a local variable and
9971 * return its declaration then, else return NULL.
9973 entity_t *expression_is_variable(const expression_t *expression)
9975 if (expression->base.kind != EXPR_REFERENCE) {
9978 entity_t *entity = expression->reference.entity;
9979 if (entity->kind != ENTITY_VARIABLE)
9986 * Parse a return statement.
9988 static statement_t *parse_return(void)
9992 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9994 expression_t *return_value = NULL;
9995 if (token.type != ';') {
9996 return_value = parse_expression();
9997 mark_vars_read(return_value, NULL);
10000 const type_t *const func_type = current_function->base.type;
10001 assert(is_type_function(func_type));
10002 type_t *const return_type = skip_typeref(func_type->function.return_type);
10004 if (return_value != NULL) {
10005 type_t *return_value_type = skip_typeref(return_value->base.type);
10007 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10008 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10009 if (warning.other) {
10010 warningf(&statement->base.source_position,
10011 "'return' with a value, in function returning void");
10013 return_value = NULL;
10015 assign_error_t error = semantic_assign(return_type, return_value);
10016 report_assign_error(error, return_type, return_value, "'return'",
10017 &statement->base.source_position);
10018 return_value = create_implicit_cast(return_value, return_type);
10020 /* check for returning address of a local var */
10021 if (warning.other && return_value != NULL
10022 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10023 const expression_t *expression = return_value->unary.value;
10024 if (expression_is_local_variable(expression)) {
10025 warningf(&statement->base.source_position,
10026 "function returns address of local variable");
10029 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10030 warningf(&statement->base.source_position,
10031 "'return' without value, in function returning non-void");
10033 statement->returns.value = return_value;
10042 * Parse a declaration statement.
10044 static statement_t *parse_declaration_statement(void)
10046 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10048 entity_t *before = scope->last_entity;
10050 parse_external_declaration();
10052 parse_declaration(record_entity);
10054 if (before == NULL) {
10055 statement->declaration.declarations_begin = scope->entities;
10057 statement->declaration.declarations_begin = before->base.next;
10059 statement->declaration.declarations_end = scope->last_entity;
10065 * Parse an expression statement, ie. expr ';'.
10067 static statement_t *parse_expression_statement(void)
10069 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10071 expression_t *const expr = parse_expression();
10072 statement->expression.expression = expr;
10073 mark_vars_read(expr, VAR_ANY);
10082 * Parse a microsoft __try { } __finally { } or
10083 * __try{ } __except() { }
10085 static statement_t *parse_ms_try_statment(void)
10087 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10090 PUSH_PARENT(statement);
10092 ms_try_statement_t *rem = current_try;
10093 current_try = &statement->ms_try;
10094 statement->ms_try.try_statement = parse_compound_statement(false);
10099 if (token.type == T___except) {
10102 add_anchor_token(')');
10103 expression_t *const expr = parse_expression();
10104 mark_vars_read(expr, NULL);
10105 type_t * type = skip_typeref(expr->base.type);
10106 if (is_type_integer(type)) {
10107 type = promote_integer(type);
10108 } else if (is_type_valid(type)) {
10109 errorf(&expr->base.source_position,
10110 "__expect expression is not an integer, but '%T'", type);
10111 type = type_error_type;
10113 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10114 rem_anchor_token(')');
10116 statement->ms_try.final_statement = parse_compound_statement(false);
10117 } else if (token.type == T__finally) {
10119 statement->ms_try.final_statement = parse_compound_statement(false);
10121 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10122 return create_invalid_statement();
10126 return create_invalid_statement();
10129 static statement_t *parse_empty_statement(void)
10131 if (warning.empty_statement) {
10132 warningf(HERE, "statement is empty");
10134 statement_t *const statement = create_empty_statement();
10139 static statement_t *parse_local_label_declaration(void)
10141 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10145 entity_t *begin = NULL, *end = NULL;
10148 if (token.type != T_IDENTIFIER) {
10149 parse_error_expected("while parsing local label declaration",
10150 T_IDENTIFIER, NULL);
10153 symbol_t *symbol = token.v.symbol;
10154 entity_t *entity = get_entity(symbol, NAMESPACE_LOCAL_LABEL);
10155 if (entity != NULL && entity->base.parent_scope == scope) {
10156 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10157 symbol, &entity->base.source_position);
10159 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10161 entity->base.parent_scope = scope;
10162 entity->base.namespc = NAMESPACE_LOCAL_LABEL;
10163 entity->base.source_position = token.source_position;
10164 entity->base.symbol = symbol;
10167 end->base.next = entity;
10172 local_label_push(entity);
10176 if (token.type != ',')
10182 statement->declaration.declarations_begin = begin;
10183 statement->declaration.declarations_end = end;
10188 * Parse a statement.
10189 * There's also parse_statement() which additionally checks for
10190 * "statement has no effect" warnings
10192 static statement_t *intern_parse_statement(void)
10194 statement_t *statement = NULL;
10196 /* declaration or statement */
10197 add_anchor_token(';');
10198 switch (token.type) {
10199 case T_IDENTIFIER: {
10200 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10201 if (la1_type == ':') {
10202 statement = parse_label_statement();
10203 } else if (is_typedef_symbol(token.v.symbol)) {
10204 statement = parse_declaration_statement();
10206 /* it's an identifier, the grammar says this must be an
10207 * expression statement. However it is common that users mistype
10208 * declaration types, so we guess a bit here to improve robustness
10209 * for incorrect programs */
10210 switch (la1_type) {
10212 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10213 goto expression_statment;
10218 statement = parse_declaration_statement();
10222 expression_statment:
10223 statement = parse_expression_statement();
10230 case T___extension__:
10231 /* This can be a prefix to a declaration or an expression statement.
10232 * We simply eat it now and parse the rest with tail recursion. */
10235 } while (token.type == T___extension__);
10236 bool old_gcc_extension = in_gcc_extension;
10237 in_gcc_extension = true;
10238 statement = parse_statement();
10239 in_gcc_extension = old_gcc_extension;
10243 statement = parse_declaration_statement();
10247 statement = parse_local_label_declaration();
10250 case ';': statement = parse_empty_statement(); break;
10251 case '{': statement = parse_compound_statement(false); break;
10252 case T___leave: statement = parse_leave_statement(); break;
10253 case T___try: statement = parse_ms_try_statment(); break;
10254 case T_asm: statement = parse_asm_statement(); break;
10255 case T_break: statement = parse_break(); break;
10256 case T_case: statement = parse_case_statement(); break;
10257 case T_continue: statement = parse_continue(); break;
10258 case T_default: statement = parse_default_statement(); break;
10259 case T_do: statement = parse_do(); break;
10260 case T_for: statement = parse_for(); break;
10261 case T_goto: statement = parse_goto(); break;
10262 case T_if: statement = parse_if(); break;
10263 case T_return: statement = parse_return(); break;
10264 case T_switch: statement = parse_switch(); break;
10265 case T_while: statement = parse_while(); break;
10268 statement = parse_expression_statement();
10272 errorf(HERE, "unexpected token %K while parsing statement", &token);
10273 statement = create_invalid_statement();
10278 rem_anchor_token(';');
10280 assert(statement != NULL
10281 && statement->base.source_position.input_name != NULL);
10287 * parse a statement and emits "statement has no effect" warning if needed
10288 * (This is really a wrapper around intern_parse_statement with check for 1
10289 * single warning. It is needed, because for statement expressions we have
10290 * to avoid the warning on the last statement)
10292 static statement_t *parse_statement(void)
10294 statement_t *statement = intern_parse_statement();
10296 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10297 expression_t *expression = statement->expression.expression;
10298 if (!expression_has_effect(expression)) {
10299 warningf(&expression->base.source_position,
10300 "statement has no effect");
10308 * Parse a compound statement.
10310 static statement_t *parse_compound_statement(bool inside_expression_statement)
10312 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10314 PUSH_PARENT(statement);
10317 add_anchor_token('}');
10319 size_t const top = environment_top();
10320 size_t const top_local = local_label_top();
10321 scope_push(&statement->compound.scope);
10323 statement_t **anchor = &statement->compound.statements;
10324 bool only_decls_so_far = true;
10325 while (token.type != '}') {
10326 if (token.type == T_EOF) {
10327 errorf(&statement->base.source_position,
10328 "EOF while parsing compound statement");
10331 statement_t *sub_statement = intern_parse_statement();
10332 if (is_invalid_statement(sub_statement)) {
10333 /* an error occurred. if we are at an anchor, return */
10339 if (warning.declaration_after_statement) {
10340 if (sub_statement->kind != STATEMENT_DECLARATION) {
10341 only_decls_so_far = false;
10342 } else if (!only_decls_so_far) {
10343 warningf(&sub_statement->base.source_position,
10344 "ISO C90 forbids mixed declarations and code");
10348 *anchor = sub_statement;
10350 while (sub_statement->base.next != NULL)
10351 sub_statement = sub_statement->base.next;
10353 anchor = &sub_statement->base.next;
10357 /* look over all statements again to produce no effect warnings */
10358 if (warning.unused_value) {
10359 statement_t *sub_statement = statement->compound.statements;
10360 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10361 if (sub_statement->kind != STATEMENT_EXPRESSION)
10363 /* don't emit a warning for the last expression in an expression
10364 * statement as it has always an effect */
10365 if (inside_expression_statement && sub_statement->base.next == NULL)
10368 expression_t *expression = sub_statement->expression.expression;
10369 if (!expression_has_effect(expression)) {
10370 warningf(&expression->base.source_position,
10371 "statement has no effect");
10377 rem_anchor_token('}');
10378 assert(scope == &statement->compound.scope);
10380 environment_pop_to(top);
10381 local_label_pop_to(top_local);
10388 * Initialize builtin types.
10390 static void initialize_builtin_types(void)
10392 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
10393 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
10394 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
10395 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
10396 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
10397 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
10398 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
10399 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
10401 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
10402 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
10403 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
10404 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
10406 /* const version of wchar_t */
10407 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF);
10408 type_const_wchar_t->typedeft.typedefe = type_wchar_t->typedeft.typedefe;
10409 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
10411 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
10415 * Check for unused global static functions and variables
10417 static void check_unused_globals(void)
10419 if (!warning.unused_function && !warning.unused_variable)
10422 for (const entity_t *entity = file_scope->entities; entity != NULL;
10423 entity = entity->base.next) {
10424 if (!is_declaration(entity))
10427 const declaration_t *declaration = &entity->declaration;
10428 if (declaration->used ||
10429 declaration->modifiers & DM_UNUSED ||
10430 declaration->modifiers & DM_USED ||
10431 declaration->storage_class != STORAGE_CLASS_STATIC)
10434 type_t *const type = declaration->type;
10436 if (entity->kind == ENTITY_FUNCTION) {
10437 /* inhibit warning for static inline functions */
10438 if (entity->function.is_inline)
10441 s = entity->function.statement != NULL ? "defined" : "declared";
10446 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10447 type, declaration->base.symbol, s);
10451 static void parse_global_asm(void)
10453 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10458 statement->asms.asm_text = parse_string_literals();
10459 statement->base.next = unit->global_asm;
10460 unit->global_asm = statement;
10469 * Parse a translation unit.
10471 static void parse_translation_unit(void)
10473 add_anchor_token(T_EOF);
10476 unsigned char token_anchor_copy[T_LAST_TOKEN];
10477 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10481 bool anchor_leak = false;
10482 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10483 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10485 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10486 anchor_leak = true;
10489 if (in_gcc_extension) {
10490 errorf(HERE, "Leaked __extension__");
10491 anchor_leak = true;
10498 switch (token.type) {
10501 case T___extension__:
10502 parse_external_declaration();
10506 parse_global_asm();
10510 rem_anchor_token(T_EOF);
10514 if (!strict_mode) {
10516 warningf(HERE, "stray ';' outside of function");
10523 errorf(HERE, "stray %K outside of function", &token);
10524 if (token.type == '(' || token.type == '{' || token.type == '[')
10525 eat_until_matching_token(token.type);
10535 * @return the translation unit or NULL if errors occurred.
10537 void start_parsing(void)
10539 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10540 label_stack = NEW_ARR_F(stack_entry_t, 0);
10541 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10542 diagnostic_count = 0;
10546 type_set_output(stderr);
10547 ast_set_output(stderr);
10549 assert(unit == NULL);
10550 unit = allocate_ast_zero(sizeof(unit[0]));
10552 assert(file_scope == NULL);
10553 file_scope = &unit->scope;
10555 assert(scope == NULL);
10556 scope_push(&unit->scope);
10558 initialize_builtin_types();
10561 translation_unit_t *finish_parsing(void)
10563 /* do NOT use scope_pop() here, this will crash, will it by hand */
10564 assert(scope == &unit->scope);
10567 assert(file_scope == &unit->scope);
10568 check_unused_globals();
10571 DEL_ARR_F(environment_stack);
10572 DEL_ARR_F(label_stack);
10573 DEL_ARR_F(local_label_stack);
10575 translation_unit_t *result = unit;
10582 lookahead_bufpos = 0;
10583 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10586 parse_translation_unit();
10590 * Initialize the parser.
10592 void init_parser(void)
10594 sym_anonymous = symbol_table_insert("<anonymous>");
10596 if (c_mode & _MS) {
10597 /* add predefined symbols for extended-decl-modifier */
10598 sym_align = symbol_table_insert("align");
10599 sym_allocate = symbol_table_insert("allocate");
10600 sym_dllimport = symbol_table_insert("dllimport");
10601 sym_dllexport = symbol_table_insert("dllexport");
10602 sym_naked = symbol_table_insert("naked");
10603 sym_noinline = symbol_table_insert("noinline");
10604 sym_noreturn = symbol_table_insert("noreturn");
10605 sym_nothrow = symbol_table_insert("nothrow");
10606 sym_novtable = symbol_table_insert("novtable");
10607 sym_property = symbol_table_insert("property");
10608 sym_get = symbol_table_insert("get");
10609 sym_put = symbol_table_insert("put");
10610 sym_selectany = symbol_table_insert("selectany");
10611 sym_thread = symbol_table_insert("thread");
10612 sym_uuid = symbol_table_insert("uuid");
10613 sym_deprecated = symbol_table_insert("deprecated");
10614 sym_restrict = symbol_table_insert("restrict");
10615 sym_noalias = symbol_table_insert("noalias");
10617 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10619 init_expression_parsers();
10620 obstack_init(&temp_obst);
10622 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10623 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10627 * Terminate the parser.
10629 void exit_parser(void)
10631 obstack_free(&temp_obst, NULL);