2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 2
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool have_arguments; /**< True, if this attribute has arguments. */
68 atomic_type_kind_t akind;
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
81 decl_modifiers_t modifiers; /**< declaration modifiers */
82 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
83 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
84 symbol_t *get_property_sym; /**< the name of the get property if set. */
85 symbol_t *put_property_sym; /**< the name of the put property if set. */
87 variable_t *based_variable; /**< Microsoft __based variable. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
101 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
103 /** The current token. */
104 static token_t token;
105 /** The lookahead ring-buffer. */
106 static token_t lookahead_buffer[MAX_LOOKAHEAD];
107 /** Position of the next token in the lookahead buffer. */
108 static int lookahead_bufpos;
109 static stack_entry_t *environment_stack = NULL;
110 static stack_entry_t *label_stack = NULL;
111 static scope_t *file_scope = NULL;
112 static scope_t *current_scope = NULL;
113 /** Point to the current function declaration if inside a function. */
114 static function_t *current_function = NULL;
115 static entity_t *current_init_decl = NULL;
116 static switch_statement_t *current_switch = NULL;
117 static statement_t *current_loop = NULL;
118 static statement_t *current_parent = NULL;
119 static ms_try_statement_t *current_try = NULL;
120 static linkage_kind_t current_linkage = LINKAGE_INVALID;
121 static goto_statement_t *goto_first = NULL;
122 static goto_statement_t **goto_anchor = NULL;
123 static label_statement_t *label_first = NULL;
124 static label_statement_t **label_anchor = NULL;
125 /** current translation unit. */
126 static translation_unit_t *unit = NULL;
127 /** true if we are in a type property context (evaluation only for type. */
128 static bool in_type_prop = false;
129 /** true in we are in a __extension__ context. */
130 static bool in_gcc_extension = false;
131 static struct obstack temp_obst;
132 static entity_t *anonymous_entity;
135 #define PUSH_PARENT(stmt) \
136 statement_t *const prev_parent = current_parent; \
137 ((void)(current_parent = (stmt)))
138 #define POP_PARENT ((void)(current_parent = prev_parent))
140 /** special symbol used for anonymous entities. */
141 static const symbol_t *sym_anonymous = NULL;
143 /* symbols for Microsoft extended-decl-modifier */
144 static const symbol_t *sym_align = NULL;
145 static const symbol_t *sym_allocate = NULL;
146 static const symbol_t *sym_dllimport = NULL;
147 static const symbol_t *sym_dllexport = NULL;
148 static const symbol_t *sym_naked = NULL;
149 static const symbol_t *sym_noinline = NULL;
150 static const symbol_t *sym_noreturn = NULL;
151 static const symbol_t *sym_nothrow = NULL;
152 static const symbol_t *sym_novtable = NULL;
153 static const symbol_t *sym_property = NULL;
154 static const symbol_t *sym_get = NULL;
155 static const symbol_t *sym_put = NULL;
156 static const symbol_t *sym_selectany = NULL;
157 static const symbol_t *sym_thread = NULL;
158 static const symbol_t *sym_uuid = NULL;
159 static const symbol_t *sym_deprecated = NULL;
160 static const symbol_t *sym_restrict = NULL;
161 static const symbol_t *sym_noalias = NULL;
163 /** The token anchor set */
164 static unsigned char token_anchor_set[T_LAST_TOKEN];
166 /** The current source position. */
167 #define HERE (&token.source_position)
169 /** true if we are in GCC mode. */
170 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
172 static type_t *type_valist;
174 static statement_t *parse_compound_statement(bool inside_expression_statement);
175 static statement_t *parse_statement(void);
177 static expression_t *parse_sub_expression(precedence_t);
178 static expression_t *parse_expression(void);
179 static type_t *parse_typename(void);
180 static void parse_externals(void);
181 static void parse_external(void);
183 static void parse_compound_type_entries(compound_t *compound_declaration);
184 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
185 bool may_be_abstract,
186 bool create_compound_member);
187 static entity_t *record_entity(entity_t *entity, bool is_definition);
189 static void semantic_comparison(binary_expression_t *expression);
191 #define STORAGE_CLASSES \
199 #define STORAGE_CLASSES_NO_EXTERN \
206 #define TYPE_QUALIFIERS \
211 case T__forceinline: \
212 case T___attribute__:
214 #define COMPLEX_SPECIFIERS \
216 #define IMAGINARY_SPECIFIERS \
219 #define TYPE_SPECIFIERS \
221 case T___builtin_va_list: \
240 #define DECLARATION_START \
245 #define DECLARATION_START_NO_EXTERN \
246 STORAGE_CLASSES_NO_EXTERN \
250 #define TYPENAME_START \
254 #define EXPRESSION_START \
263 case T_CHARACTER_CONSTANT: \
264 case T_FLOATINGPOINT: \
268 case T_STRING_LITERAL: \
269 case T_WIDE_CHARACTER_CONSTANT: \
270 case T_WIDE_STRING_LITERAL: \
271 case T___FUNCDNAME__: \
272 case T___FUNCSIG__: \
273 case T___FUNCTION__: \
274 case T___PRETTY_FUNCTION__: \
275 case T___alignof__: \
276 case T___builtin_alloca: \
277 case T___builtin_classify_type: \
278 case T___builtin_constant_p: \
279 case T___builtin_expect: \
280 case T___builtin_huge_val: \
281 case T___builtin_inf: \
282 case T___builtin_inff: \
283 case T___builtin_infl: \
284 case T___builtin_isgreater: \
285 case T___builtin_isgreaterequal: \
286 case T___builtin_isless: \
287 case T___builtin_islessequal: \
288 case T___builtin_islessgreater: \
289 case T___builtin_isunordered: \
290 case T___builtin_nan: \
291 case T___builtin_nanf: \
292 case T___builtin_nanl: \
293 case T___builtin_offsetof: \
294 case T___builtin_prefetch: \
295 case T___builtin_va_arg: \
296 case T___builtin_va_end: \
297 case T___builtin_va_start: \
308 * Allocate an AST node with given size and
309 * initialize all fields with zero.
311 static void *allocate_ast_zero(size_t size)
313 void *res = allocate_ast(size);
314 memset(res, 0, size);
318 static size_t get_entity_struct_size(entity_kind_t kind)
320 static const size_t sizes[] = {
321 [ENTITY_VARIABLE] = sizeof(variable_t),
322 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
323 [ENTITY_FUNCTION] = sizeof(function_t),
324 [ENTITY_TYPEDEF] = sizeof(typedef_t),
325 [ENTITY_STRUCT] = sizeof(compound_t),
326 [ENTITY_UNION] = sizeof(compound_t),
327 [ENTITY_ENUM] = sizeof(enum_t),
328 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
329 [ENTITY_LABEL] = sizeof(label_t),
330 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
331 [ENTITY_NAMESPACE] = sizeof(namespace_t)
333 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
334 assert(sizes[kind] != 0);
338 static entity_t *allocate_entity_zero(entity_kind_t kind)
340 size_t size = get_entity_struct_size(kind);
341 entity_t *entity = allocate_ast_zero(size);
347 * Returns the size of a statement node.
349 * @param kind the statement kind
351 static size_t get_statement_struct_size(statement_kind_t kind)
353 static const size_t sizes[] = {
354 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
355 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
356 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
357 [STATEMENT_RETURN] = sizeof(return_statement_t),
358 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
359 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
360 [STATEMENT_IF] = sizeof(if_statement_t),
361 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
362 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
363 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
364 [STATEMENT_BREAK] = sizeof(statement_base_t),
365 [STATEMENT_GOTO] = sizeof(goto_statement_t),
366 [STATEMENT_LABEL] = sizeof(label_statement_t),
367 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
368 [STATEMENT_WHILE] = sizeof(while_statement_t),
369 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
370 [STATEMENT_FOR] = sizeof(for_statement_t),
371 [STATEMENT_ASM] = sizeof(asm_statement_t),
372 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
373 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
375 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
376 assert(sizes[kind] != 0);
381 * Returns the size of an expression node.
383 * @param kind the expression kind
385 static size_t get_expression_struct_size(expression_kind_t kind)
387 static const size_t sizes[] = {
388 [EXPR_INVALID] = sizeof(expression_base_t),
389 [EXPR_REFERENCE] = sizeof(reference_expression_t),
390 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
391 [EXPR_CONST] = sizeof(const_expression_t),
392 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
393 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
394 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
395 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
396 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
397 [EXPR_CALL] = sizeof(call_expression_t),
398 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
399 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
400 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
401 [EXPR_SELECT] = sizeof(select_expression_t),
402 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
403 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
404 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
405 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
406 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
407 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
408 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
409 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
410 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
411 [EXPR_VA_START] = sizeof(va_start_expression_t),
412 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
413 [EXPR_STATEMENT] = sizeof(statement_expression_t),
414 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
416 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
417 return sizes[EXPR_UNARY_FIRST];
419 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
420 return sizes[EXPR_BINARY_FIRST];
422 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
423 assert(sizes[kind] != 0);
428 * Allocate a statement node of given kind and initialize all
431 static statement_t *allocate_statement_zero(statement_kind_t kind)
433 size_t size = get_statement_struct_size(kind);
434 statement_t *res = allocate_ast_zero(size);
436 res->base.kind = kind;
437 res->base.parent = current_parent;
438 res->base.source_position = token.source_position;
443 * Allocate an expression node of given kind and initialize all
446 static expression_t *allocate_expression_zero(expression_kind_t kind)
448 size_t size = get_expression_struct_size(kind);
449 expression_t *res = allocate_ast_zero(size);
451 res->base.kind = kind;
452 res->base.type = type_error_type;
453 res->base.source_position = token.source_position;
458 * Creates a new invalid expression.
460 static expression_t *create_invalid_expression(void)
462 return allocate_expression_zero(EXPR_INVALID);
466 * Creates a new invalid statement.
468 static statement_t *create_invalid_statement(void)
470 return allocate_statement_zero(STATEMENT_INVALID);
474 * Allocate a new empty statement.
476 static statement_t *create_empty_statement(void)
478 return allocate_statement_zero(STATEMENT_EMPTY);
482 * Returns the size of a type node.
484 * @param kind the type kind
486 static size_t get_type_struct_size(type_kind_t kind)
488 static const size_t sizes[] = {
489 [TYPE_ATOMIC] = sizeof(atomic_type_t),
490 [TYPE_COMPLEX] = sizeof(complex_type_t),
491 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
492 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
493 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
494 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
495 [TYPE_ENUM] = sizeof(enum_type_t),
496 [TYPE_FUNCTION] = sizeof(function_type_t),
497 [TYPE_POINTER] = sizeof(pointer_type_t),
498 [TYPE_ARRAY] = sizeof(array_type_t),
499 [TYPE_BUILTIN] = sizeof(builtin_type_t),
500 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
501 [TYPE_TYPEOF] = sizeof(typeof_type_t),
503 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
504 assert(kind <= TYPE_TYPEOF);
505 assert(sizes[kind] != 0);
510 * Allocate a type node of given kind and initialize all
513 * @param kind type kind to allocate
515 static type_t *allocate_type_zero(type_kind_t kind)
517 size_t size = get_type_struct_size(kind);
518 type_t *res = obstack_alloc(type_obst, size);
519 memset(res, 0, size);
520 res->base.kind = kind;
526 * Returns the size of an initializer node.
528 * @param kind the initializer kind
530 static size_t get_initializer_size(initializer_kind_t kind)
532 static const size_t sizes[] = {
533 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
534 [INITIALIZER_STRING] = sizeof(initializer_string_t),
535 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
536 [INITIALIZER_LIST] = sizeof(initializer_list_t),
537 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
539 assert(kind < sizeof(sizes) / sizeof(*sizes));
540 assert(sizes[kind] != 0);
545 * Allocate an initializer node of given kind and initialize all
548 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
550 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
557 * Free a type from the type obstack.
559 static void free_type(void *type)
561 obstack_free(type_obst, type);
565 * Returns the index of the top element of the environment stack.
567 static size_t environment_top(void)
569 return ARR_LEN(environment_stack);
573 * Returns the index of the top element of the global label stack.
575 static size_t label_top(void)
577 return ARR_LEN(label_stack);
581 * Return the next token.
583 static inline void next_token(void)
585 token = lookahead_buffer[lookahead_bufpos];
586 lookahead_buffer[lookahead_bufpos] = lexer_token;
589 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
592 print_token(stderr, &token);
593 fprintf(stderr, "\n");
598 * Return the next token with a given lookahead.
600 static inline const token_t *look_ahead(int num)
602 assert(num > 0 && num <= MAX_LOOKAHEAD);
603 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
604 return &lookahead_buffer[pos];
608 * Adds a token to the token anchor set (a multi-set).
610 static void add_anchor_token(int token_type)
612 assert(0 <= token_type && token_type < T_LAST_TOKEN);
613 ++token_anchor_set[token_type];
616 static int save_and_reset_anchor_state(int token_type)
618 assert(0 <= token_type && token_type < T_LAST_TOKEN);
619 int count = token_anchor_set[token_type];
620 token_anchor_set[token_type] = 0;
624 static void restore_anchor_state(int token_type, int count)
626 assert(0 <= token_type && token_type < T_LAST_TOKEN);
627 token_anchor_set[token_type] = count;
631 * Remove a token from the token anchor set (a multi-set).
633 static void rem_anchor_token(int token_type)
635 assert(0 <= token_type && token_type < T_LAST_TOKEN);
636 assert(token_anchor_set[token_type] != 0);
637 --token_anchor_set[token_type];
640 static bool at_anchor(void)
644 return token_anchor_set[token.type];
648 * Eat tokens until a matching token is found.
650 static void eat_until_matching_token(int type)
654 case '(': end_token = ')'; break;
655 case '{': end_token = '}'; break;
656 case '[': end_token = ']'; break;
657 default: end_token = type; break;
660 unsigned parenthesis_count = 0;
661 unsigned brace_count = 0;
662 unsigned bracket_count = 0;
663 while (token.type != end_token ||
664 parenthesis_count != 0 ||
666 bracket_count != 0) {
667 switch (token.type) {
669 case '(': ++parenthesis_count; break;
670 case '{': ++brace_count; break;
671 case '[': ++bracket_count; break;
674 if (parenthesis_count > 0)
684 if (bracket_count > 0)
687 if (token.type == end_token &&
688 parenthesis_count == 0 &&
702 * Eat input tokens until an anchor is found.
704 static void eat_until_anchor(void)
706 while (token_anchor_set[token.type] == 0) {
707 if (token.type == '(' || token.type == '{' || token.type == '[')
708 eat_until_matching_token(token.type);
713 static void eat_block(void)
715 eat_until_matching_token('{');
716 if (token.type == '}')
720 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
723 * Report a parse error because an expected token was not found.
726 #if defined __GNUC__ && __GNUC__ >= 4
727 __attribute__((sentinel))
729 void parse_error_expected(const char *message, ...)
731 if (message != NULL) {
732 errorf(HERE, "%s", message);
735 va_start(ap, message);
736 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
741 * Report a type error.
743 static void type_error(const char *msg, const source_position_t *source_position,
746 errorf(source_position, "%s, but found type '%T'", msg, type);
750 * Report an incompatible type.
752 static void type_error_incompatible(const char *msg,
753 const source_position_t *source_position, type_t *type1, type_t *type2)
755 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
760 * Expect the the current token is the expected token.
761 * If not, generate an error, eat the current statement,
762 * and goto the end_error label.
764 #define expect(expected) \
766 if (UNLIKELY(token.type != (expected))) { \
767 parse_error_expected(NULL, (expected), NULL); \
768 add_anchor_token(expected); \
769 eat_until_anchor(); \
770 if (token.type == expected) \
772 rem_anchor_token(expected); \
778 static void scope_push(scope_t *new_scope)
780 if (current_scope != NULL) {
781 new_scope->depth = current_scope->depth + 1;
783 new_scope->parent = current_scope;
784 current_scope = new_scope;
787 static void scope_pop(void)
789 current_scope = current_scope->parent;
793 * Search an entity by its symbol in a given namespace.
795 static entity_t *get_entity(const symbol_t *const symbol,
796 namespace_tag_t namespc)
798 entity_t *entity = symbol->entity;
799 for (; entity != NULL; entity = entity->base.symbol_next) {
800 if (entity->base.namespc == namespc)
808 * pushs an entity on the environment stack and links the corresponding symbol
811 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
813 symbol_t *symbol = entity->base.symbol;
814 entity_namespace_t namespc = entity->base.namespc;
815 assert(namespc != NAMESPACE_INVALID);
817 /* replace/add entity into entity list of the symbol */
820 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
825 /* replace an entry? */
826 if (iter->base.namespc == namespc) {
827 entity->base.symbol_next = iter->base.symbol_next;
833 /* remember old declaration */
835 entry.symbol = symbol;
836 entry.old_entity = iter;
837 entry.namespc = namespc;
838 ARR_APP1(stack_entry_t, *stack_ptr, entry);
842 * Push an entity on the environment stack.
844 static void environment_push(entity_t *entity)
846 assert(entity->base.source_position.input_name != NULL);
847 assert(entity->base.parent_scope != NULL);
848 stack_push(&environment_stack, entity);
852 * Push a declaration on the global label stack.
854 * @param declaration the declaration
856 static void label_push(entity_t *label)
858 /* we abuse the parameters scope as parent for the labels */
859 label->base.parent_scope = ¤t_function->parameters;
860 stack_push(&label_stack, label);
864 * pops symbols from the environment stack until @p new_top is the top element
866 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
868 stack_entry_t *stack = *stack_ptr;
869 size_t top = ARR_LEN(stack);
872 assert(new_top <= top);
876 for (i = top; i > new_top; --i) {
877 stack_entry_t *entry = &stack[i - 1];
879 entity_t *old_entity = entry->old_entity;
880 symbol_t *symbol = entry->symbol;
881 entity_namespace_t namespc = entry->namespc;
883 /* replace with old_entity/remove */
886 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
888 assert(iter != NULL);
889 /* replace an entry? */
890 if (iter->base.namespc == namespc)
894 /* restore definition from outer scopes (if there was one) */
895 if (old_entity != NULL) {
896 old_entity->base.symbol_next = iter->base.symbol_next;
897 *anchor = old_entity;
899 /* remove entry from list */
900 *anchor = iter->base.symbol_next;
904 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
908 * Pop all entries from the environment stack until the new_top
911 * @param new_top the new stack top
913 static void environment_pop_to(size_t new_top)
915 stack_pop_to(&environment_stack, new_top);
919 * Pop all entries from the global label stack until the new_top
922 * @param new_top the new stack top
924 static void label_pop_to(size_t new_top)
926 stack_pop_to(&label_stack, new_top);
929 static int get_akind_rank(atomic_type_kind_t akind)
934 static int get_rank(const type_t *type)
936 assert(!is_typeref(type));
937 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
938 * and esp. footnote 108). However we can't fold constants (yet), so we
939 * can't decide whether unsigned int is possible, while int always works.
940 * (unsigned int would be preferable when possible... for stuff like
941 * struct { enum { ... } bla : 4; } ) */
942 if (type->kind == TYPE_ENUM)
943 return get_akind_rank(ATOMIC_TYPE_INT);
945 assert(type->kind == TYPE_ATOMIC);
946 return get_akind_rank(type->atomic.akind);
949 static type_t *promote_integer(type_t *type)
951 if (type->kind == TYPE_BITFIELD)
952 type = type->bitfield.base_type;
954 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
961 * Create a cast expression.
963 * @param expression the expression to cast
964 * @param dest_type the destination type
966 static expression_t *create_cast_expression(expression_t *expression,
969 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
971 cast->unary.value = expression;
972 cast->base.type = dest_type;
978 * Check if a given expression represents the 0 pointer constant.
980 static bool is_null_pointer_constant(const expression_t *expression)
982 /* skip void* cast */
983 if (expression->kind == EXPR_UNARY_CAST
984 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
985 expression = expression->unary.value;
988 /* TODO: not correct yet, should be any constant integer expression
989 * which evaluates to 0 */
990 if (expression->kind != EXPR_CONST)
993 type_t *const type = skip_typeref(expression->base.type);
994 if (!is_type_integer(type))
997 return expression->conste.v.int_value == 0;
1001 * Create an implicit cast expression.
1003 * @param expression the expression to cast
1004 * @param dest_type the destination type
1006 static expression_t *create_implicit_cast(expression_t *expression,
1009 type_t *const source_type = expression->base.type;
1011 if (source_type == dest_type)
1014 return create_cast_expression(expression, dest_type);
1017 typedef enum assign_error_t {
1019 ASSIGN_ERROR_INCOMPATIBLE,
1020 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1021 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1022 ASSIGN_WARNING_POINTER_FROM_INT,
1023 ASSIGN_WARNING_INT_FROM_POINTER
1026 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1027 const expression_t *const right,
1028 const char *context,
1029 const source_position_t *source_position)
1031 type_t *const orig_type_right = right->base.type;
1032 type_t *const type_left = skip_typeref(orig_type_left);
1033 type_t *const type_right = skip_typeref(orig_type_right);
1036 case ASSIGN_SUCCESS:
1038 case ASSIGN_ERROR_INCOMPATIBLE:
1039 errorf(source_position,
1040 "destination type '%T' in %s is incompatible with type '%T'",
1041 orig_type_left, context, orig_type_right);
1044 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1045 if (warning.other) {
1046 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1047 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1049 /* the left type has all qualifiers from the right type */
1050 unsigned missing_qualifiers
1051 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1052 warningf(source_position,
1053 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1054 orig_type_left, context, orig_type_right, missing_qualifiers);
1059 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1060 if (warning.other) {
1061 warningf(source_position,
1062 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1063 orig_type_left, context, right, orig_type_right);
1067 case ASSIGN_WARNING_POINTER_FROM_INT:
1068 if (warning.other) {
1069 warningf(source_position,
1070 "%s makes pointer '%T' from integer '%T' without a cast",
1071 context, orig_type_left, orig_type_right);
1075 case ASSIGN_WARNING_INT_FROM_POINTER:
1076 if (warning.other) {
1077 warningf(source_position,
1078 "%s makes integer '%T' from pointer '%T' without a cast",
1079 context, orig_type_left, orig_type_right);
1084 panic("invalid error value");
1088 /** Implements the rules from § 6.5.16.1 */
1089 static assign_error_t semantic_assign(type_t *orig_type_left,
1090 const expression_t *const right)
1092 type_t *const orig_type_right = right->base.type;
1093 type_t *const type_left = skip_typeref(orig_type_left);
1094 type_t *const type_right = skip_typeref(orig_type_right);
1096 if (is_type_pointer(type_left)) {
1097 if (is_null_pointer_constant(right)) {
1098 return ASSIGN_SUCCESS;
1099 } else if (is_type_pointer(type_right)) {
1100 type_t *points_to_left
1101 = skip_typeref(type_left->pointer.points_to);
1102 type_t *points_to_right
1103 = skip_typeref(type_right->pointer.points_to);
1104 assign_error_t res = ASSIGN_SUCCESS;
1106 /* the left type has all qualifiers from the right type */
1107 unsigned missing_qualifiers
1108 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1109 if (missing_qualifiers != 0) {
1110 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1113 points_to_left = get_unqualified_type(points_to_left);
1114 points_to_right = get_unqualified_type(points_to_right);
1116 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1119 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1120 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1121 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1124 if (!types_compatible(points_to_left, points_to_right)) {
1125 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1129 } else if (is_type_integer(type_right)) {
1130 return ASSIGN_WARNING_POINTER_FROM_INT;
1132 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1133 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1134 && is_type_pointer(type_right))) {
1135 return ASSIGN_SUCCESS;
1136 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1137 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1138 type_t *const unqual_type_left = get_unqualified_type(type_left);
1139 type_t *const unqual_type_right = get_unqualified_type(type_right);
1140 if (types_compatible(unqual_type_left, unqual_type_right)) {
1141 return ASSIGN_SUCCESS;
1143 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1144 return ASSIGN_WARNING_INT_FROM_POINTER;
1147 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1148 return ASSIGN_SUCCESS;
1150 return ASSIGN_ERROR_INCOMPATIBLE;
1153 static expression_t *parse_constant_expression(void)
1155 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1157 if (!is_constant_expression(result)) {
1158 errorf(&result->base.source_position,
1159 "expression '%E' is not constant\n", result);
1165 static expression_t *parse_assignment_expression(void)
1167 return parse_sub_expression(PREC_ASSIGNMENT);
1170 static string_t parse_string_literals(void)
1172 assert(token.type == T_STRING_LITERAL);
1173 string_t result = token.v.string;
1177 while (token.type == T_STRING_LITERAL) {
1178 result = concat_strings(&result, &token.v.string);
1185 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1186 [GNU_AK_CONST] = "const",
1187 [GNU_AK_VOLATILE] = "volatile",
1188 [GNU_AK_CDECL] = "cdecl",
1189 [GNU_AK_STDCALL] = "stdcall",
1190 [GNU_AK_FASTCALL] = "fastcall",
1191 [GNU_AK_DEPRECATED] = "deprecated",
1192 [GNU_AK_NOINLINE] = "noinline",
1193 [GNU_AK_NORETURN] = "noreturn",
1194 [GNU_AK_NAKED] = "naked",
1195 [GNU_AK_PURE] = "pure",
1196 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1197 [GNU_AK_MALLOC] = "malloc",
1198 [GNU_AK_WEAK] = "weak",
1199 [GNU_AK_CONSTRUCTOR] = "constructor",
1200 [GNU_AK_DESTRUCTOR] = "destructor",
1201 [GNU_AK_NOTHROW] = "nothrow",
1202 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1203 [GNU_AK_COMMON] = "common",
1204 [GNU_AK_NOCOMMON] = "nocommon",
1205 [GNU_AK_PACKED] = "packed",
1206 [GNU_AK_SHARED] = "shared",
1207 [GNU_AK_NOTSHARED] = "notshared",
1208 [GNU_AK_USED] = "used",
1209 [GNU_AK_UNUSED] = "unused",
1210 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1211 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1212 [GNU_AK_LONGCALL] = "longcall",
1213 [GNU_AK_SHORTCALL] = "shortcall",
1214 [GNU_AK_LONG_CALL] = "long_call",
1215 [GNU_AK_SHORT_CALL] = "short_call",
1216 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1217 [GNU_AK_INTERRUPT] = "interrupt",
1218 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1219 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1220 [GNU_AK_NESTING] = "nesting",
1221 [GNU_AK_NEAR] = "near",
1222 [GNU_AK_FAR] = "far",
1223 [GNU_AK_SIGNAL] = "signal",
1224 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1225 [GNU_AK_TINY_DATA] = "tiny_data",
1226 [GNU_AK_SAVEALL] = "saveall",
1227 [GNU_AK_FLATTEN] = "flatten",
1228 [GNU_AK_SSEREGPARM] = "sseregparm",
1229 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1230 [GNU_AK_RETURN_TWICE] = "return_twice",
1231 [GNU_AK_MAY_ALIAS] = "may_alias",
1232 [GNU_AK_MS_STRUCT] = "ms_struct",
1233 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1234 [GNU_AK_DLLIMPORT] = "dllimport",
1235 [GNU_AK_DLLEXPORT] = "dllexport",
1236 [GNU_AK_ALIGNED] = "aligned",
1237 [GNU_AK_ALIAS] = "alias",
1238 [GNU_AK_SECTION] = "section",
1239 [GNU_AK_FORMAT] = "format",
1240 [GNU_AK_FORMAT_ARG] = "format_arg",
1241 [GNU_AK_WEAKREF] = "weakref",
1242 [GNU_AK_NONNULL] = "nonnull",
1243 [GNU_AK_TLS_MODEL] = "tls_model",
1244 [GNU_AK_VISIBILITY] = "visibility",
1245 [GNU_AK_REGPARM] = "regparm",
1246 [GNU_AK_MODE] = "mode",
1247 [GNU_AK_MODEL] = "model",
1248 [GNU_AK_TRAP_EXIT] = "trap_exit",
1249 [GNU_AK_SP_SWITCH] = "sp_switch",
1250 [GNU_AK_SENTINEL] = "sentinel"
1254 * compare two string, ignoring double underscores on the second.
1256 static int strcmp_underscore(const char *s1, const char *s2)
1258 if (s2[0] == '_' && s2[1] == '_') {
1259 size_t len2 = strlen(s2);
1260 size_t len1 = strlen(s1);
1261 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1262 return strncmp(s1, s2+2, len2-4);
1266 return strcmp(s1, s2);
1270 * Allocate a new gnu temporal attribute.
1272 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1274 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1275 attribute->kind = kind;
1276 attribute->next = NULL;
1277 attribute->invalid = false;
1278 attribute->have_arguments = false;
1284 * parse one constant expression argument.
1286 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1288 expression_t *expression;
1289 add_anchor_token(')');
1290 expression = parse_constant_expression();
1291 rem_anchor_token(')');
1293 attribute->u.argument = fold_constant(expression);
1296 attribute->invalid = true;
1300 * parse a list of constant expressions arguments.
1302 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1304 argument_list_t **list = &attribute->u.arguments;
1305 argument_list_t *entry;
1306 expression_t *expression;
1307 add_anchor_token(')');
1308 add_anchor_token(',');
1310 expression = parse_constant_expression();
1311 entry = obstack_alloc(&temp_obst, sizeof(entry));
1312 entry->argument = fold_constant(expression);
1315 list = &entry->next;
1316 if (token.type != ',')
1320 rem_anchor_token(',');
1321 rem_anchor_token(')');
1325 attribute->invalid = true;
1329 * parse one string literal argument.
1331 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1334 add_anchor_token('(');
1335 if (token.type != T_STRING_LITERAL) {
1336 parse_error_expected("while parsing attribute directive",
1337 T_STRING_LITERAL, NULL);
1340 *string = parse_string_literals();
1341 rem_anchor_token('(');
1345 attribute->invalid = true;
1349 * parse one tls model.
1351 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1353 static const char *const tls_models[] = {
1359 string_t string = { NULL, 0 };
1360 parse_gnu_attribute_string_arg(attribute, &string);
1361 if (string.begin != NULL) {
1362 for (size_t i = 0; i < 4; ++i) {
1363 if (strcmp(tls_models[i], string.begin) == 0) {
1364 attribute->u.value = i;
1368 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1370 attribute->invalid = true;
1374 * parse one tls model.
1376 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1378 static const char *const visibilities[] = {
1384 string_t string = { NULL, 0 };
1385 parse_gnu_attribute_string_arg(attribute, &string);
1386 if (string.begin != NULL) {
1387 for (size_t i = 0; i < 4; ++i) {
1388 if (strcmp(visibilities[i], string.begin) == 0) {
1389 attribute->u.value = i;
1393 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1395 attribute->invalid = true;
1399 * parse one (code) model.
1401 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1403 static const char *const visibilities[] = {
1408 string_t string = { NULL, 0 };
1409 parse_gnu_attribute_string_arg(attribute, &string);
1410 if (string.begin != NULL) {
1411 for (int i = 0; i < 3; ++i) {
1412 if (strcmp(visibilities[i], string.begin) == 0) {
1413 attribute->u.value = i;
1417 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1419 attribute->invalid = true;
1422 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1424 /* TODO: find out what is allowed here... */
1426 /* at least: byte, word, pointer, list of machine modes
1427 * __XXX___ is interpreted as XXX */
1428 add_anchor_token(')');
1430 if (token.type != T_IDENTIFIER) {
1431 expect(T_IDENTIFIER);
1434 /* This isn't really correct, the backend should provide a list of machine
1435 * specific modes (according to gcc philosophy that is...) */
1436 const char *symbol_str = token.v.symbol->string;
1437 if (strcmp_underscore("QI", symbol_str) == 0 ||
1438 strcmp_underscore("byte", symbol_str) == 0) {
1439 attribute->u.akind = ATOMIC_TYPE_CHAR;
1440 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1441 attribute->u.akind = ATOMIC_TYPE_SHORT;
1442 } else if (strcmp_underscore("SI", symbol_str) == 0
1443 || strcmp_underscore("word", symbol_str) == 0
1444 || strcmp_underscore("pointer", symbol_str) == 0) {
1445 attribute->u.akind = ATOMIC_TYPE_INT;
1446 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1447 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1450 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1451 attribute->invalid = true;
1455 rem_anchor_token(')');
1459 attribute->invalid = true;
1463 * parse one interrupt argument.
1465 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1467 static const char *const interrupts[] = {
1474 string_t string = { NULL, 0 };
1475 parse_gnu_attribute_string_arg(attribute, &string);
1476 if (string.begin != NULL) {
1477 for (size_t i = 0; i < 5; ++i) {
1478 if (strcmp(interrupts[i], string.begin) == 0) {
1479 attribute->u.value = i;
1483 errorf(HERE, "'%s' is not an interrupt", string.begin);
1485 attribute->invalid = true;
1489 * parse ( identifier, const expression, const expression )
1491 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1493 static const char *const format_names[] = {
1501 if (token.type != T_IDENTIFIER) {
1502 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1505 const char *name = token.v.symbol->string;
1506 for (i = 0; i < 4; ++i) {
1507 if (strcmp_underscore(format_names[i], name) == 0)
1511 if (warning.attribute)
1512 warningf(HERE, "'%s' is an unrecognized format function type", name);
1517 add_anchor_token(')');
1518 add_anchor_token(',');
1519 parse_constant_expression();
1520 rem_anchor_token(',');
1521 rem_anchor_token(')');
1524 add_anchor_token(')');
1525 parse_constant_expression();
1526 rem_anchor_token(')');
1530 attribute->u.value = true;
1533 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1535 if (!attribute->have_arguments)
1538 /* should have no arguments */
1539 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1540 eat_until_matching_token('(');
1541 /* we have already consumed '(', so we stop before ')', eat it */
1543 attribute->invalid = true;
1547 * Parse one GNU attribute.
1549 * Note that attribute names can be specified WITH or WITHOUT
1550 * double underscores, ie const or __const__.
1552 * The following attributes are parsed without arguments
1577 * no_instrument_function
1578 * warn_unused_result
1595 * externally_visible
1603 * The following attributes are parsed with arguments
1604 * aligned( const expression )
1605 * alias( string literal )
1606 * section( string literal )
1607 * format( identifier, const expression, const expression )
1608 * format_arg( const expression )
1609 * tls_model( string literal )
1610 * visibility( string literal )
1611 * regparm( const expression )
1612 * model( string leteral )
1613 * trap_exit( const expression )
1614 * sp_switch( string literal )
1616 * The following attributes might have arguments
1617 * weak_ref( string literal )
1618 * non_null( const expression // ',' )
1619 * interrupt( string literal )
1620 * sentinel( constant expression )
1622 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1624 gnu_attribute_t *head = *attributes;
1625 gnu_attribute_t *last = *attributes;
1626 decl_modifiers_t modifiers = 0;
1627 gnu_attribute_t *attribute;
1629 eat(T___attribute__);
1633 if (token.type != ')') {
1634 /* find the end of the list */
1636 while (last->next != NULL)
1640 /* non-empty attribute list */
1643 if (token.type == T_const) {
1645 } else if (token.type == T_volatile) {
1647 } else if (token.type == T_cdecl) {
1648 /* __attribute__((cdecl)), WITH ms mode */
1650 } else if (token.type == T_IDENTIFIER) {
1651 const symbol_t *sym = token.v.symbol;
1654 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1661 for (i = 0; i < GNU_AK_LAST; ++i) {
1662 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1665 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1668 if (kind == GNU_AK_LAST) {
1669 if (warning.attribute)
1670 warningf(HERE, "'%s' attribute directive ignored", name);
1672 /* skip possible arguments */
1673 if (token.type == '(') {
1674 eat_until_matching_token(')');
1677 /* check for arguments */
1678 attribute = allocate_gnu_attribute(kind);
1679 if (token.type == '(') {
1681 if (token.type == ')') {
1682 /* empty args are allowed */
1685 attribute->have_arguments = true;
1689 case GNU_AK_VOLATILE:
1694 case GNU_AK_NOCOMMON:
1696 case GNU_AK_NOTSHARED:
1697 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1698 case GNU_AK_WARN_UNUSED_RESULT:
1699 case GNU_AK_LONGCALL:
1700 case GNU_AK_SHORTCALL:
1701 case GNU_AK_LONG_CALL:
1702 case GNU_AK_SHORT_CALL:
1703 case GNU_AK_FUNCTION_VECTOR:
1704 case GNU_AK_INTERRUPT_HANDLER:
1705 case GNU_AK_NMI_HANDLER:
1706 case GNU_AK_NESTING:
1710 case GNU_AK_EIGTHBIT_DATA:
1711 case GNU_AK_TINY_DATA:
1712 case GNU_AK_SAVEALL:
1713 case GNU_AK_FLATTEN:
1714 case GNU_AK_SSEREGPARM:
1715 case GNU_AK_EXTERNALLY_VISIBLE:
1716 case GNU_AK_RETURN_TWICE:
1717 case GNU_AK_MAY_ALIAS:
1718 case GNU_AK_MS_STRUCT:
1719 case GNU_AK_GCC_STRUCT:
1722 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1723 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1724 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1725 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1726 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1727 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1728 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1729 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1730 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1731 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1732 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1733 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1734 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1735 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1736 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1737 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1738 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1739 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1741 case GNU_AK_ALIGNED:
1742 /* __align__ may be used without an argument */
1743 if (attribute->have_arguments) {
1744 parse_gnu_attribute_const_arg(attribute);
1748 case GNU_AK_FORMAT_ARG:
1749 case GNU_AK_REGPARM:
1750 case GNU_AK_TRAP_EXIT:
1751 if (!attribute->have_arguments) {
1752 /* should have arguments */
1753 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1754 attribute->invalid = true;
1756 parse_gnu_attribute_const_arg(attribute);
1759 case GNU_AK_SECTION:
1760 case GNU_AK_SP_SWITCH:
1761 if (!attribute->have_arguments) {
1762 /* should have arguments */
1763 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1764 attribute->invalid = true;
1766 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1769 if (!attribute->have_arguments) {
1770 /* should have arguments */
1771 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1772 attribute->invalid = true;
1774 parse_gnu_attribute_format_args(attribute);
1776 case GNU_AK_WEAKREF:
1777 /* may have one string argument */
1778 if (attribute->have_arguments)
1779 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1781 case GNU_AK_NONNULL:
1782 if (attribute->have_arguments)
1783 parse_gnu_attribute_const_arg_list(attribute);
1785 case GNU_AK_TLS_MODEL:
1786 if (!attribute->have_arguments) {
1787 /* should have arguments */
1788 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1790 parse_gnu_attribute_tls_model_arg(attribute);
1792 case GNU_AK_VISIBILITY:
1793 if (!attribute->have_arguments) {
1794 /* should have arguments */
1795 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1797 parse_gnu_attribute_visibility_arg(attribute);
1800 if (!attribute->have_arguments) {
1801 /* should have arguments */
1802 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1804 parse_gnu_attribute_model_arg(attribute);
1808 if (!attribute->have_arguments) {
1809 /* should have arguments */
1810 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1812 parse_gnu_attribute_mode_arg(attribute);
1815 case GNU_AK_INTERRUPT:
1816 /* may have one string argument */
1817 if (attribute->have_arguments)
1818 parse_gnu_attribute_interrupt_arg(attribute);
1820 case GNU_AK_SENTINEL:
1821 /* may have one string argument */
1822 if (attribute->have_arguments)
1823 parse_gnu_attribute_const_arg(attribute);
1826 /* already handled */
1830 check_no_argument(attribute, name);
1833 if (attribute != NULL) {
1835 last->next = attribute;
1838 head = last = attribute;
1842 if (token.type != ',')
1856 * Parse GNU attributes.
1858 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1860 decl_modifiers_t modifiers = 0;
1863 switch (token.type) {
1864 case T___attribute__:
1865 modifiers |= parse_gnu_attribute(attributes);
1871 if (token.type != T_STRING_LITERAL) {
1872 parse_error_expected("while parsing assembler attribute",
1873 T_STRING_LITERAL, NULL);
1874 eat_until_matching_token('(');
1877 parse_string_literals();
1882 case T_cdecl: modifiers |= DM_CDECL; break;
1883 case T__fastcall: modifiers |= DM_FASTCALL; break;
1884 case T__stdcall: modifiers |= DM_STDCALL; break;
1887 /* TODO record modifier */
1889 warningf(HERE, "Ignoring declaration modifier %K", &token);
1893 default: return modifiers;
1900 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1902 static variable_t *determine_lhs_var(expression_t *const expr,
1903 variable_t *lhs_var)
1905 switch (expr->kind) {
1906 case EXPR_REFERENCE: {
1907 entity_t *const entity = expr->reference.entity;
1908 /* we should only find variables as lavlues... */
1909 if (entity->base.kind != ENTITY_VARIABLE)
1912 return &entity->variable;
1915 case EXPR_ARRAY_ACCESS: {
1916 expression_t *const ref = expr->array_access.array_ref;
1917 variable_t * var = NULL;
1918 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1919 var = determine_lhs_var(ref, lhs_var);
1922 mark_vars_read(expr->select.compound, lhs_var);
1924 mark_vars_read(expr->array_access.index, lhs_var);
1929 if (is_type_compound(skip_typeref(expr->base.type))) {
1930 return determine_lhs_var(expr->select.compound, lhs_var);
1932 mark_vars_read(expr->select.compound, lhs_var);
1937 case EXPR_UNARY_DEREFERENCE: {
1938 expression_t *const val = expr->unary.value;
1939 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1941 return determine_lhs_var(val->unary.value, lhs_var);
1943 mark_vars_read(val, NULL);
1949 mark_vars_read(expr, NULL);
1954 #define VAR_ANY ((variable_t*)-1)
1957 * Mark declarations, which are read. This is used to deted variables, which
1961 * x is not marked as "read", because it is only read to calculate its own new
1965 * x and y are not detected as "not read", because multiple variables are
1968 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1970 switch (expr->kind) {
1971 case EXPR_REFERENCE: {
1972 entity_t *const entity = expr->reference.entity;
1973 if (entity->kind != ENTITY_VARIABLE)
1976 variable_t *variable = &entity->variable;
1977 if (lhs_var != variable && lhs_var != VAR_ANY) {
1978 variable->read = true;
1984 // TODO respect pure/const
1985 mark_vars_read(expr->call.function, NULL);
1986 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1987 mark_vars_read(arg->expression, NULL);
1991 case EXPR_CONDITIONAL:
1992 // TODO lhs_decl should depend on whether true/false have an effect
1993 mark_vars_read(expr->conditional.condition, NULL);
1994 if (expr->conditional.true_expression != NULL)
1995 mark_vars_read(expr->conditional.true_expression, lhs_var);
1996 mark_vars_read(expr->conditional.false_expression, lhs_var);
2000 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2002 mark_vars_read(expr->select.compound, lhs_var);
2005 case EXPR_ARRAY_ACCESS: {
2006 expression_t *const ref = expr->array_access.array_ref;
2007 mark_vars_read(ref, lhs_var);
2008 lhs_var = determine_lhs_var(ref, lhs_var);
2009 mark_vars_read(expr->array_access.index, lhs_var);
2014 mark_vars_read(expr->va_arge.ap, lhs_var);
2017 case EXPR_UNARY_CAST:
2018 /* Special case: Use void cast to mark a variable as "read" */
2019 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2024 case EXPR_UNARY_THROW:
2025 if (expr->unary.value == NULL)
2028 case EXPR_UNARY_DEREFERENCE:
2029 case EXPR_UNARY_DELETE:
2030 case EXPR_UNARY_DELETE_ARRAY:
2031 if (lhs_var == VAR_ANY)
2035 case EXPR_UNARY_NEGATE:
2036 case EXPR_UNARY_PLUS:
2037 case EXPR_UNARY_BITWISE_NEGATE:
2038 case EXPR_UNARY_NOT:
2039 case EXPR_UNARY_TAKE_ADDRESS:
2040 case EXPR_UNARY_POSTFIX_INCREMENT:
2041 case EXPR_UNARY_POSTFIX_DECREMENT:
2042 case EXPR_UNARY_PREFIX_INCREMENT:
2043 case EXPR_UNARY_PREFIX_DECREMENT:
2044 case EXPR_UNARY_CAST_IMPLICIT:
2045 case EXPR_UNARY_ASSUME:
2047 mark_vars_read(expr->unary.value, lhs_var);
2050 case EXPR_BINARY_ADD:
2051 case EXPR_BINARY_SUB:
2052 case EXPR_BINARY_MUL:
2053 case EXPR_BINARY_DIV:
2054 case EXPR_BINARY_MOD:
2055 case EXPR_BINARY_EQUAL:
2056 case EXPR_BINARY_NOTEQUAL:
2057 case EXPR_BINARY_LESS:
2058 case EXPR_BINARY_LESSEQUAL:
2059 case EXPR_BINARY_GREATER:
2060 case EXPR_BINARY_GREATEREQUAL:
2061 case EXPR_BINARY_BITWISE_AND:
2062 case EXPR_BINARY_BITWISE_OR:
2063 case EXPR_BINARY_BITWISE_XOR:
2064 case EXPR_BINARY_LOGICAL_AND:
2065 case EXPR_BINARY_LOGICAL_OR:
2066 case EXPR_BINARY_SHIFTLEFT:
2067 case EXPR_BINARY_SHIFTRIGHT:
2068 case EXPR_BINARY_COMMA:
2069 case EXPR_BINARY_ISGREATER:
2070 case EXPR_BINARY_ISGREATEREQUAL:
2071 case EXPR_BINARY_ISLESS:
2072 case EXPR_BINARY_ISLESSEQUAL:
2073 case EXPR_BINARY_ISLESSGREATER:
2074 case EXPR_BINARY_ISUNORDERED:
2075 mark_vars_read(expr->binary.left, lhs_var);
2076 mark_vars_read(expr->binary.right, lhs_var);
2079 case EXPR_BINARY_ASSIGN:
2080 case EXPR_BINARY_MUL_ASSIGN:
2081 case EXPR_BINARY_DIV_ASSIGN:
2082 case EXPR_BINARY_MOD_ASSIGN:
2083 case EXPR_BINARY_ADD_ASSIGN:
2084 case EXPR_BINARY_SUB_ASSIGN:
2085 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2086 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2087 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2088 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2089 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2090 if (lhs_var == VAR_ANY)
2092 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2093 mark_vars_read(expr->binary.right, lhs_var);
2098 determine_lhs_var(expr->va_starte.ap, lhs_var);
2104 case EXPR_CHARACTER_CONSTANT:
2105 case EXPR_WIDE_CHARACTER_CONSTANT:
2106 case EXPR_STRING_LITERAL:
2107 case EXPR_WIDE_STRING_LITERAL:
2108 case EXPR_COMPOUND_LITERAL: // TODO init?
2110 case EXPR_CLASSIFY_TYPE:
2113 case EXPR_BUILTIN_SYMBOL:
2114 case EXPR_BUILTIN_CONSTANT_P:
2115 case EXPR_BUILTIN_PREFETCH:
2117 case EXPR_STATEMENT: // TODO
2118 case EXPR_LABEL_ADDRESS:
2119 case EXPR_BINARY_BUILTIN_EXPECT:
2120 case EXPR_REFERENCE_ENUM_VALUE:
2124 panic("unhandled expression");
2127 static designator_t *parse_designation(void)
2129 designator_t *result = NULL;
2130 designator_t *last = NULL;
2133 designator_t *designator;
2134 switch (token.type) {
2136 designator = allocate_ast_zero(sizeof(designator[0]));
2137 designator->source_position = token.source_position;
2139 add_anchor_token(']');
2140 designator->array_index = parse_constant_expression();
2141 rem_anchor_token(']');
2145 designator = allocate_ast_zero(sizeof(designator[0]));
2146 designator->source_position = token.source_position;
2148 if (token.type != T_IDENTIFIER) {
2149 parse_error_expected("while parsing designator",
2150 T_IDENTIFIER, NULL);
2153 designator->symbol = token.v.symbol;
2161 assert(designator != NULL);
2163 last->next = designator;
2165 result = designator;
2173 static initializer_t *initializer_from_string(array_type_t *type,
2174 const string_t *const string)
2176 /* TODO: check len vs. size of array type */
2179 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2180 initializer->string.string = *string;
2185 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2186 wide_string_t *const string)
2188 /* TODO: check len vs. size of array type */
2191 initializer_t *const initializer =
2192 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2193 initializer->wide_string.string = *string;
2199 * Build an initializer from a given expression.
2201 static initializer_t *initializer_from_expression(type_t *orig_type,
2202 expression_t *expression)
2204 /* TODO check that expression is a constant expression */
2206 /* § 6.7.8.14/15 char array may be initialized by string literals */
2207 type_t *type = skip_typeref(orig_type);
2208 type_t *expr_type_orig = expression->base.type;
2209 type_t *expr_type = skip_typeref(expr_type_orig);
2210 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2211 array_type_t *const array_type = &type->array;
2212 type_t *const element_type = skip_typeref(array_type->element_type);
2214 if (element_type->kind == TYPE_ATOMIC) {
2215 atomic_type_kind_t akind = element_type->atomic.akind;
2216 switch (expression->kind) {
2217 case EXPR_STRING_LITERAL:
2218 if (akind == ATOMIC_TYPE_CHAR
2219 || akind == ATOMIC_TYPE_SCHAR
2220 || akind == ATOMIC_TYPE_UCHAR) {
2221 return initializer_from_string(array_type,
2222 &expression->string.value);
2225 case EXPR_WIDE_STRING_LITERAL: {
2226 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2227 if (get_unqualified_type(element_type) == bare_wchar_type) {
2228 return initializer_from_wide_string(array_type,
2229 &expression->wide_string.value);
2239 assign_error_t error = semantic_assign(type, expression);
2240 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2242 report_assign_error(error, type, expression, "initializer",
2243 &expression->base.source_position);
2245 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2247 if (type->kind == TYPE_BITFIELD) {
2248 type = type->bitfield.base_type;
2251 result->value.value = create_implicit_cast(expression, type);
2257 * Checks if a given expression can be used as an constant initializer.
2259 static bool is_initializer_constant(const expression_t *expression)
2261 return is_constant_expression(expression)
2262 || is_address_constant(expression);
2266 * Parses an scalar initializer.
2268 * § 6.7.8.11; eat {} without warning
2270 static initializer_t *parse_scalar_initializer(type_t *type,
2271 bool must_be_constant)
2273 /* there might be extra {} hierarchies */
2275 if (token.type == '{') {
2277 warningf(HERE, "extra curly braces around scalar initializer");
2281 } while (token.type == '{');
2284 expression_t *expression = parse_assignment_expression();
2285 mark_vars_read(expression, NULL);
2286 if (must_be_constant && !is_initializer_constant(expression)) {
2287 errorf(&expression->base.source_position,
2288 "Initialisation expression '%E' is not constant\n",
2292 initializer_t *initializer = initializer_from_expression(type, expression);
2294 if (initializer == NULL) {
2295 errorf(&expression->base.source_position,
2296 "expression '%E' (type '%T') doesn't match expected type '%T'",
2297 expression, expression->base.type, type);
2302 bool additional_warning_displayed = false;
2303 while (braces > 0) {
2304 if (token.type == ',') {
2307 if (token.type != '}') {
2308 if (!additional_warning_displayed && warning.other) {
2309 warningf(HERE, "additional elements in scalar initializer");
2310 additional_warning_displayed = true;
2321 * An entry in the type path.
2323 typedef struct type_path_entry_t type_path_entry_t;
2324 struct type_path_entry_t {
2325 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2327 size_t index; /**< For array types: the current index. */
2328 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2333 * A type path expression a position inside compound or array types.
2335 typedef struct type_path_t type_path_t;
2336 struct type_path_t {
2337 type_path_entry_t *path; /**< An flexible array containing the current path. */
2338 type_t *top_type; /**< type of the element the path points */
2339 size_t max_index; /**< largest index in outermost array */
2343 * Prints a type path for debugging.
2345 static __attribute__((unused)) void debug_print_type_path(
2346 const type_path_t *path)
2348 size_t len = ARR_LEN(path->path);
2350 for (size_t i = 0; i < len; ++i) {
2351 const type_path_entry_t *entry = & path->path[i];
2353 type_t *type = skip_typeref(entry->type);
2354 if (is_type_compound(type)) {
2355 /* in gcc mode structs can have no members */
2356 if (entry->v.compound_entry == NULL) {
2360 fprintf(stderr, ".%s",
2361 entry->v.compound_entry->base.symbol->string);
2362 } else if (is_type_array(type)) {
2363 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2365 fprintf(stderr, "-INVALID-");
2368 if (path->top_type != NULL) {
2369 fprintf(stderr, " (");
2370 print_type(path->top_type);
2371 fprintf(stderr, ")");
2376 * Return the top type path entry, ie. in a path
2377 * (type).a.b returns the b.
2379 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2381 size_t len = ARR_LEN(path->path);
2383 return &path->path[len-1];
2387 * Enlarge the type path by an (empty) element.
2389 static type_path_entry_t *append_to_type_path(type_path_t *path)
2391 size_t len = ARR_LEN(path->path);
2392 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2394 type_path_entry_t *result = & path->path[len];
2395 memset(result, 0, sizeof(result[0]));
2400 * Descending into a sub-type. Enter the scope of the current top_type.
2402 static void descend_into_subtype(type_path_t *path)
2404 type_t *orig_top_type = path->top_type;
2405 type_t *top_type = skip_typeref(orig_top_type);
2407 type_path_entry_t *top = append_to_type_path(path);
2408 top->type = top_type;
2410 if (is_type_compound(top_type)) {
2411 compound_t *compound = top_type->compound.compound;
2412 entity_t *entry = compound->members.entities;
2414 if (entry != NULL) {
2415 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2416 top->v.compound_entry = &entry->declaration;
2417 path->top_type = entry->declaration.type;
2419 path->top_type = NULL;
2421 } else if (is_type_array(top_type)) {
2423 path->top_type = top_type->array.element_type;
2425 assert(!is_type_valid(top_type));
2430 * Pop an entry from the given type path, ie. returning from
2431 * (type).a.b to (type).a
2433 static void ascend_from_subtype(type_path_t *path)
2435 type_path_entry_t *top = get_type_path_top(path);
2437 path->top_type = top->type;
2439 size_t len = ARR_LEN(path->path);
2440 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2444 * Pop entries from the given type path until the given
2445 * path level is reached.
2447 static void ascend_to(type_path_t *path, size_t top_path_level)
2449 size_t len = ARR_LEN(path->path);
2451 while (len > top_path_level) {
2452 ascend_from_subtype(path);
2453 len = ARR_LEN(path->path);
2457 static bool walk_designator(type_path_t *path, const designator_t *designator,
2458 bool used_in_offsetof)
2460 for (; designator != NULL; designator = designator->next) {
2461 type_path_entry_t *top = get_type_path_top(path);
2462 type_t *orig_type = top->type;
2464 type_t *type = skip_typeref(orig_type);
2466 if (designator->symbol != NULL) {
2467 symbol_t *symbol = designator->symbol;
2468 if (!is_type_compound(type)) {
2469 if (is_type_valid(type)) {
2470 errorf(&designator->source_position,
2471 "'.%Y' designator used for non-compound type '%T'",
2475 top->type = type_error_type;
2476 top->v.compound_entry = NULL;
2477 orig_type = type_error_type;
2479 compound_t *compound = type->compound.compound;
2480 entity_t *iter = compound->members.entities;
2481 for (; iter != NULL; iter = iter->base.next) {
2482 if (iter->base.symbol == symbol) {
2487 errorf(&designator->source_position,
2488 "'%T' has no member named '%Y'", orig_type, symbol);
2491 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2492 if (used_in_offsetof) {
2493 type_t *real_type = skip_typeref(iter->declaration.type);
2494 if (real_type->kind == TYPE_BITFIELD) {
2495 errorf(&designator->source_position,
2496 "offsetof designator '%Y' may not specify bitfield",
2502 top->type = orig_type;
2503 top->v.compound_entry = &iter->declaration;
2504 orig_type = iter->declaration.type;
2507 expression_t *array_index = designator->array_index;
2508 assert(designator->array_index != NULL);
2510 if (!is_type_array(type)) {
2511 if (is_type_valid(type)) {
2512 errorf(&designator->source_position,
2513 "[%E] designator used for non-array type '%T'",
2514 array_index, orig_type);
2519 long index = fold_constant(array_index);
2520 if (!used_in_offsetof) {
2522 errorf(&designator->source_position,
2523 "array index [%E] must be positive", array_index);
2524 } else if (type->array.size_constant) {
2525 long array_size = type->array.size;
2526 if (index >= array_size) {
2527 errorf(&designator->source_position,
2528 "designator [%E] (%d) exceeds array size %d",
2529 array_index, index, array_size);
2534 top->type = orig_type;
2535 top->v.index = (size_t) index;
2536 orig_type = type->array.element_type;
2538 path->top_type = orig_type;
2540 if (designator->next != NULL) {
2541 descend_into_subtype(path);
2550 static void advance_current_object(type_path_t *path, size_t top_path_level)
2552 type_path_entry_t *top = get_type_path_top(path);
2554 type_t *type = skip_typeref(top->type);
2555 if (is_type_union(type)) {
2556 /* in unions only the first element is initialized */
2557 top->v.compound_entry = NULL;
2558 } else if (is_type_struct(type)) {
2559 declaration_t *entry = top->v.compound_entry;
2561 entity_t *next_entity = entry->base.next;
2562 if (next_entity != NULL) {
2563 assert(is_declaration(next_entity));
2564 entry = &next_entity->declaration;
2569 top->v.compound_entry = entry;
2570 if (entry != NULL) {
2571 path->top_type = entry->type;
2574 } else if (is_type_array(type)) {
2575 assert(is_type_array(type));
2579 if (!type->array.size_constant || top->v.index < type->array.size) {
2583 assert(!is_type_valid(type));
2587 /* we're past the last member of the current sub-aggregate, try if we
2588 * can ascend in the type hierarchy and continue with another subobject */
2589 size_t len = ARR_LEN(path->path);
2591 if (len > top_path_level) {
2592 ascend_from_subtype(path);
2593 advance_current_object(path, top_path_level);
2595 path->top_type = NULL;
2600 * skip until token is found.
2602 static void skip_until(int type)
2604 while (token.type != type) {
2605 if (token.type == T_EOF)
2612 * skip any {...} blocks until a closing bracket is reached.
2614 static void skip_initializers(void)
2616 if (token.type == '{')
2619 while (token.type != '}') {
2620 if (token.type == T_EOF)
2622 if (token.type == '{') {
2630 static initializer_t *create_empty_initializer(void)
2632 static initializer_t empty_initializer
2633 = { .list = { { INITIALIZER_LIST }, 0 } };
2634 return &empty_initializer;
2638 * Parse a part of an initialiser for a struct or union,
2640 static initializer_t *parse_sub_initializer(type_path_t *path,
2641 type_t *outer_type, size_t top_path_level,
2642 parse_initializer_env_t *env)
2644 if (token.type == '}') {
2645 /* empty initializer */
2646 return create_empty_initializer();
2649 type_t *orig_type = path->top_type;
2650 type_t *type = NULL;
2652 if (orig_type == NULL) {
2653 /* We are initializing an empty compound. */
2655 type = skip_typeref(orig_type);
2658 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2661 designator_t *designator = NULL;
2662 if (token.type == '.' || token.type == '[') {
2663 designator = parse_designation();
2664 goto finish_designator;
2665 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2666 /* GNU-style designator ("identifier: value") */
2667 designator = allocate_ast_zero(sizeof(designator[0]));
2668 designator->source_position = token.source_position;
2669 designator->symbol = token.v.symbol;
2674 /* reset path to toplevel, evaluate designator from there */
2675 ascend_to(path, top_path_level);
2676 if (!walk_designator(path, designator, false)) {
2677 /* can't continue after designation error */
2681 initializer_t *designator_initializer
2682 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2683 designator_initializer->designator.designator = designator;
2684 ARR_APP1(initializer_t*, initializers, designator_initializer);
2686 orig_type = path->top_type;
2687 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2692 if (token.type == '{') {
2693 if (type != NULL && is_type_scalar(type)) {
2694 sub = parse_scalar_initializer(type, env->must_be_constant);
2698 if (env->entity != NULL) {
2700 "extra brace group at end of initializer for '%Y'",
2701 env->entity->base.symbol);
2703 errorf(HERE, "extra brace group at end of initializer");
2706 descend_into_subtype(path);
2708 add_anchor_token('}');
2709 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2711 rem_anchor_token('}');
2714 ascend_from_subtype(path);
2718 goto error_parse_next;
2722 /* must be an expression */
2723 expression_t *expression = parse_assignment_expression();
2725 if (env->must_be_constant && !is_initializer_constant(expression)) {
2726 errorf(&expression->base.source_position,
2727 "Initialisation expression '%E' is not constant\n",
2732 /* we are already outside, ... */
2733 type_t *const outer_type_skip = skip_typeref(outer_type);
2734 if (is_type_compound(outer_type_skip) &&
2735 !outer_type_skip->compound.compound->complete) {
2736 goto error_parse_next;
2741 /* handle { "string" } special case */
2742 if ((expression->kind == EXPR_STRING_LITERAL
2743 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2744 && outer_type != NULL) {
2745 sub = initializer_from_expression(outer_type, expression);
2747 if (token.type == ',') {
2750 if (token.type != '}' && warning.other) {
2751 warningf(HERE, "excessive elements in initializer for type '%T'",
2754 /* TODO: eat , ... */
2759 /* descend into subtypes until expression matches type */
2761 orig_type = path->top_type;
2762 type = skip_typeref(orig_type);
2764 sub = initializer_from_expression(orig_type, expression);
2768 if (!is_type_valid(type)) {
2771 if (is_type_scalar(type)) {
2772 errorf(&expression->base.source_position,
2773 "expression '%E' doesn't match expected type '%T'",
2774 expression, orig_type);
2778 descend_into_subtype(path);
2782 /* update largest index of top array */
2783 const type_path_entry_t *first = &path->path[0];
2784 type_t *first_type = first->type;
2785 first_type = skip_typeref(first_type);
2786 if (is_type_array(first_type)) {
2787 size_t index = first->v.index;
2788 if (index > path->max_index)
2789 path->max_index = index;
2793 /* append to initializers list */
2794 ARR_APP1(initializer_t*, initializers, sub);
2797 if (warning.other) {
2798 if (env->entity != NULL) {
2799 warningf(HERE, "excess elements in struct initializer for '%Y'",
2800 env->entity->base.symbol);
2802 warningf(HERE, "excess elements in struct initializer");
2808 if (token.type == '}') {
2812 if (token.type == '}') {
2817 /* advance to the next declaration if we are not at the end */
2818 advance_current_object(path, top_path_level);
2819 orig_type = path->top_type;
2820 if (orig_type != NULL)
2821 type = skip_typeref(orig_type);
2827 size_t len = ARR_LEN(initializers);
2828 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2829 initializer_t *result = allocate_ast_zero(size);
2830 result->kind = INITIALIZER_LIST;
2831 result->list.len = len;
2832 memcpy(&result->list.initializers, initializers,
2833 len * sizeof(initializers[0]));
2835 DEL_ARR_F(initializers);
2836 ascend_to(path, top_path_level+1);
2841 skip_initializers();
2842 DEL_ARR_F(initializers);
2843 ascend_to(path, top_path_level+1);
2848 * Parses an initializer. Parsers either a compound literal
2849 * (env->declaration == NULL) or an initializer of a declaration.
2851 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2853 type_t *type = skip_typeref(env->type);
2854 initializer_t *result = NULL;
2857 if (is_type_scalar(type)) {
2858 result = parse_scalar_initializer(type, env->must_be_constant);
2859 } else if (token.type == '{') {
2863 memset(&path, 0, sizeof(path));
2864 path.top_type = env->type;
2865 path.path = NEW_ARR_F(type_path_entry_t, 0);
2867 descend_into_subtype(&path);
2869 add_anchor_token('}');
2870 result = parse_sub_initializer(&path, env->type, 1, env);
2871 rem_anchor_token('}');
2873 max_index = path.max_index;
2874 DEL_ARR_F(path.path);
2878 /* parse_scalar_initializer() also works in this case: we simply
2879 * have an expression without {} around it */
2880 result = parse_scalar_initializer(type, env->must_be_constant);
2883 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2884 * the array type size */
2885 if (is_type_array(type) && type->array.size_expression == NULL
2886 && result != NULL) {
2888 switch (result->kind) {
2889 case INITIALIZER_LIST:
2890 size = max_index + 1;
2893 case INITIALIZER_STRING:
2894 size = result->string.string.size;
2897 case INITIALIZER_WIDE_STRING:
2898 size = result->wide_string.string.size;
2901 case INITIALIZER_DESIGNATOR:
2902 case INITIALIZER_VALUE:
2903 /* can happen for parse errors */
2908 internal_errorf(HERE, "invalid initializer type");
2911 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2912 cnst->base.type = type_size_t;
2913 cnst->conste.v.int_value = size;
2915 type_t *new_type = duplicate_type(type);
2917 new_type->array.size_expression = cnst;
2918 new_type->array.size_constant = true;
2919 new_type->array.has_implicit_size = true;
2920 new_type->array.size = size;
2921 env->type = new_type;
2929 static void append_entity(scope_t *scope, entity_t *entity)
2931 if (scope->last_entity != NULL) {
2932 scope->last_entity->base.next = entity;
2934 scope->entities = entity;
2936 scope->last_entity = entity;
2940 static compound_t *parse_compound_type_specifier(bool is_struct)
2942 gnu_attribute_t *attributes = NULL;
2943 decl_modifiers_t modifiers = 0;
2950 symbol_t *symbol = NULL;
2951 compound_t *compound = NULL;
2953 if (token.type == T___attribute__) {
2954 modifiers |= parse_attributes(&attributes);
2957 if (token.type == T_IDENTIFIER) {
2958 symbol = token.v.symbol;
2961 namespace_tag_t const namespc =
2962 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2963 entity_t *entity = get_entity(symbol, namespc);
2964 if (entity != NULL) {
2965 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2966 compound = &entity->compound;
2967 if (compound->base.parent_scope != current_scope &&
2968 (token.type == '{' || token.type == ';')) {
2969 /* we're in an inner scope and have a definition. Override
2970 existing definition in outer scope */
2972 } else if (compound->complete && token.type == '{') {
2973 assert(symbol != NULL);
2974 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2975 is_struct ? "struct" : "union", symbol,
2976 &compound->base.source_position);
2977 /* clear members in the hope to avoid further errors */
2978 compound->members.entities = NULL;
2981 } else if (token.type != '{') {
2983 parse_error_expected("while parsing struct type specifier",
2984 T_IDENTIFIER, '{', NULL);
2986 parse_error_expected("while parsing union type specifier",
2987 T_IDENTIFIER, '{', NULL);
2993 if (compound == NULL) {
2994 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2995 entity_t *entity = allocate_entity_zero(kind);
2996 compound = &entity->compound;
2998 compound->base.namespc =
2999 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3000 compound->base.source_position = token.source_position;
3001 compound->base.symbol = symbol;
3002 compound->base.parent_scope = current_scope;
3003 if (symbol != NULL) {
3004 environment_push(entity);
3006 append_entity(current_scope, entity);
3009 if (token.type == '{') {
3010 parse_compound_type_entries(compound);
3011 modifiers |= parse_attributes(&attributes);
3013 if (symbol == NULL) {
3014 assert(anonymous_entity == NULL);
3015 anonymous_entity = (entity_t*)compound;
3019 compound->modifiers |= modifiers;
3023 static void parse_enum_entries(type_t *const enum_type)
3027 if (token.type == '}') {
3028 errorf(HERE, "empty enum not allowed");
3033 add_anchor_token('}');
3035 if (token.type != T_IDENTIFIER) {
3036 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3038 rem_anchor_token('}');
3042 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3043 entity->enum_value.enum_type = enum_type;
3044 entity->base.symbol = token.v.symbol;
3045 entity->base.source_position = token.source_position;
3048 if (token.type == '=') {
3050 expression_t *value = parse_constant_expression();
3052 value = create_implicit_cast(value, enum_type);
3053 entity->enum_value.value = value;
3058 record_entity(entity, false);
3060 if (token.type != ',')
3063 } while (token.type != '}');
3064 rem_anchor_token('}');
3072 static type_t *parse_enum_specifier(void)
3074 gnu_attribute_t *attributes = NULL;
3079 if (token.type == T_IDENTIFIER) {
3080 symbol = token.v.symbol;
3083 entity = get_entity(symbol, NAMESPACE_ENUM);
3084 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3085 } else if (token.type != '{') {
3086 parse_error_expected("while parsing enum type specifier",
3087 T_IDENTIFIER, '{', NULL);
3094 if (entity == NULL) {
3095 entity = allocate_entity_zero(ENTITY_ENUM);
3096 entity->base.namespc = NAMESPACE_ENUM;
3097 entity->base.source_position = token.source_position;
3098 entity->base.symbol = symbol;
3099 entity->base.parent_scope = current_scope;
3102 type_t *const type = allocate_type_zero(TYPE_ENUM);
3103 type->enumt.enume = &entity->enume;
3105 if (token.type == '{') {
3106 if (entity->enume.complete) {
3107 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3108 symbol, &entity->base.source_position);
3110 if (symbol != NULL) {
3111 environment_push(entity);
3113 append_entity(current_scope, entity);
3114 entity->enume.complete = true;
3116 parse_enum_entries(type);
3117 parse_attributes(&attributes);
3119 if (symbol == NULL) {
3120 assert(anonymous_entity == NULL);
3121 anonymous_entity = entity;
3123 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3124 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3132 * if a symbol is a typedef to another type, return true
3134 static bool is_typedef_symbol(symbol_t *symbol)
3136 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3137 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3140 static type_t *parse_typeof(void)
3147 add_anchor_token(')');
3149 expression_t *expression = NULL;
3151 bool old_type_prop = in_type_prop;
3152 bool old_gcc_extension = in_gcc_extension;
3153 in_type_prop = true;
3155 while (token.type == T___extension__) {
3156 /* This can be a prefix to a typename or an expression. */
3158 in_gcc_extension = true;
3160 switch (token.type) {
3162 if (is_typedef_symbol(token.v.symbol)) {
3163 type = parse_typename();
3165 expression = parse_expression();
3166 type = expression->base.type;
3171 type = parse_typename();
3175 expression = parse_expression();
3176 type = expression->base.type;
3179 in_type_prop = old_type_prop;
3180 in_gcc_extension = old_gcc_extension;
3182 rem_anchor_token(')');
3185 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3186 typeof_type->typeoft.expression = expression;
3187 typeof_type->typeoft.typeof_type = type;
3194 typedef enum specifiers_t {
3195 SPECIFIER_SIGNED = 1 << 0,
3196 SPECIFIER_UNSIGNED = 1 << 1,
3197 SPECIFIER_LONG = 1 << 2,
3198 SPECIFIER_INT = 1 << 3,
3199 SPECIFIER_DOUBLE = 1 << 4,
3200 SPECIFIER_CHAR = 1 << 5,
3201 SPECIFIER_SHORT = 1 << 6,
3202 SPECIFIER_LONG_LONG = 1 << 7,
3203 SPECIFIER_FLOAT = 1 << 8,
3204 SPECIFIER_BOOL = 1 << 9,
3205 SPECIFIER_VOID = 1 << 10,
3206 SPECIFIER_INT8 = 1 << 11,
3207 SPECIFIER_INT16 = 1 << 12,
3208 SPECIFIER_INT32 = 1 << 13,
3209 SPECIFIER_INT64 = 1 << 14,
3210 SPECIFIER_INT128 = 1 << 15,
3211 SPECIFIER_COMPLEX = 1 << 16,
3212 SPECIFIER_IMAGINARY = 1 << 17,
3215 static type_t *create_builtin_type(symbol_t *const symbol,
3216 type_t *const real_type)
3218 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3219 type->builtin.symbol = symbol;
3220 type->builtin.real_type = real_type;
3222 type_t *result = typehash_insert(type);
3223 if (type != result) {
3230 static type_t *get_typedef_type(symbol_t *symbol)
3232 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3233 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3236 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3237 type->typedeft.typedefe = &entity->typedefe;
3243 * check for the allowed MS alignment values.
3245 static bool check_alignment_value(long long intvalue)
3247 if (intvalue < 1 || intvalue > 8192) {
3248 errorf(HERE, "illegal alignment value");
3251 unsigned v = (unsigned)intvalue;
3252 for (unsigned i = 1; i <= 8192; i += i) {
3256 errorf(HERE, "alignment must be power of two");
3260 #define DET_MOD(name, tag) do { \
3261 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3262 *modifiers |= tag; \
3265 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3267 decl_modifiers_t *modifiers = &specifiers->modifiers;
3270 if (token.type == T_restrict) {
3272 DET_MOD(restrict, DM_RESTRICT);
3274 } else if (token.type != T_IDENTIFIER)
3276 symbol_t *symbol = token.v.symbol;
3277 if (symbol == sym_align) {
3280 if (token.type != T_INTEGER)
3282 if (check_alignment_value(token.v.intvalue)) {
3283 if (specifiers->alignment != 0 && warning.other)
3284 warningf(HERE, "align used more than once");
3285 specifiers->alignment = (unsigned char)token.v.intvalue;
3289 } else if (symbol == sym_allocate) {
3292 if (token.type != T_IDENTIFIER)
3294 (void)token.v.symbol;
3296 } else if (symbol == sym_dllimport) {
3298 DET_MOD(dllimport, DM_DLLIMPORT);
3299 } else if (symbol == sym_dllexport) {
3301 DET_MOD(dllexport, DM_DLLEXPORT);
3302 } else if (symbol == sym_thread) {
3304 DET_MOD(thread, DM_THREAD);
3305 } else if (symbol == sym_naked) {
3307 DET_MOD(naked, DM_NAKED);
3308 } else if (symbol == sym_noinline) {
3310 DET_MOD(noinline, DM_NOINLINE);
3311 } else if (symbol == sym_noreturn) {
3313 DET_MOD(noreturn, DM_NORETURN);
3314 } else if (symbol == sym_nothrow) {
3316 DET_MOD(nothrow, DM_NOTHROW);
3317 } else if (symbol == sym_novtable) {
3319 DET_MOD(novtable, DM_NOVTABLE);
3320 } else if (symbol == sym_property) {
3324 bool is_get = false;
3325 if (token.type != T_IDENTIFIER)
3327 if (token.v.symbol == sym_get) {
3329 } else if (token.v.symbol == sym_put) {
3331 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3336 if (token.type != T_IDENTIFIER)
3339 if (specifiers->get_property_sym != NULL) {
3340 errorf(HERE, "get property name already specified");
3342 specifiers->get_property_sym = token.v.symbol;
3345 if (specifiers->put_property_sym != NULL) {
3346 errorf(HERE, "put property name already specified");
3348 specifiers->put_property_sym = token.v.symbol;
3352 if (token.type == ',') {
3359 } else if (symbol == sym_selectany) {
3361 DET_MOD(selectany, DM_SELECTANY);
3362 } else if (symbol == sym_uuid) {
3365 if (token.type != T_STRING_LITERAL)
3369 } else if (symbol == sym_deprecated) {
3371 if (specifiers->deprecated != 0 && warning.other)
3372 warningf(HERE, "deprecated used more than once");
3373 specifiers->deprecated = true;
3374 if (token.type == '(') {
3376 if (token.type == T_STRING_LITERAL) {
3377 specifiers->deprecated_string = token.v.string.begin;
3380 errorf(HERE, "string literal expected");
3384 } else if (symbol == sym_noalias) {
3386 DET_MOD(noalias, DM_NOALIAS);
3389 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3391 if (token.type == '(')
3395 if (token.type == ',')
3402 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3404 entity_t *entity = allocate_entity_zero(kind);
3405 entity->base.source_position = *HERE;
3406 entity->base.symbol = symbol;
3407 if (is_declaration(entity)) {
3408 entity->declaration.type = type_error_type;
3409 entity->declaration.implicit = true;
3410 } else if (kind == ENTITY_TYPEDEF) {
3411 entity->typedefe.type = type_error_type;
3413 record_entity(entity, false);
3417 static void parse_microsoft_based(declaration_specifiers_t *specifiers)
3419 if (token.type != T_IDENTIFIER) {
3420 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3423 symbol_t *symbol = token.v.symbol;
3424 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3426 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3427 errorf(HERE, "'%Y' is not a variable name.", symbol);
3428 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3430 variable_t *variable = &entity->variable;
3432 if (specifiers->based_variable != NULL) {
3433 errorf(HERE, "__based type qualifier specified more than once");
3435 specifiers->based_variable = variable;
3437 type_t *const type = variable->base.type;
3439 if (is_type_valid(type)) {
3440 if (! is_type_pointer(skip_typeref(type))) {
3441 errorf(HERE, "variable in __based modifier must have pointer type instead of %T", type);
3443 if (variable->base.base.parent_scope != file_scope) {
3444 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3452 * Finish the construction of a struct type by calculating
3453 * its size, offsets, alignment.
3455 static void finish_struct_type(compound_type_t *type)
3457 assert(type->compound != NULL);
3459 compound_t *compound = type->compound;
3460 if (!compound->complete)
3465 il_alignment_t alignment = 1;
3466 bool need_pad = false;
3468 entity_t *entry = compound->members.entities;
3469 for (; entry != NULL; entry = entry->base.next) {
3470 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3473 type_t *m_type = skip_typeref(entry->declaration.type);
3474 if (! is_type_valid(m_type)) {
3475 /* simply ignore errors here */
3478 il_alignment_t m_alignment = m_type->base.alignment;
3479 if (m_alignment > alignment)
3480 alignment = m_alignment;
3482 offset = (size + m_alignment - 1) & -m_alignment;
3486 entry->compound_member.offset = offset;
3487 size = offset + m_type->base.size;
3489 if (type->base.alignment != 0) {
3490 alignment = type->base.alignment;
3493 offset = (size + alignment - 1) & -alignment;
3497 if (warning.padded && need_pad) {
3498 warningf(&compound->base.source_position,
3499 "'%#T' needs padding", type, compound->base.symbol);
3501 if (warning.packed && !need_pad) {
3502 warningf(&compound->base.source_position,
3503 "superfluous packed attribute on '%#T'",
3504 type, compound->base.symbol);
3507 type->base.size = offset;
3508 type->base.alignment = alignment;
3512 * Finish the construction of an union type by calculating
3513 * its size and alignment.
3515 static void finish_union_type(compound_type_t *type)
3517 assert(type->compound != NULL);
3519 compound_t *compound = type->compound;
3520 if (! compound->complete)
3524 il_alignment_t alignment = 1;
3526 entity_t *entry = compound->members.entities;
3527 for (; entry != NULL; entry = entry->base.next) {
3528 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3531 type_t *m_type = skip_typeref(entry->declaration.type);
3532 if (! is_type_valid(m_type))
3535 entry->compound_member.offset = 0;
3536 if (m_type->base.size > size)
3537 size = m_type->base.size;
3538 if (m_type->base.alignment > alignment)
3539 alignment = m_type->base.alignment;
3541 if (type->base.alignment != 0) {
3542 alignment = type->base.alignment;
3544 size = (size + alignment - 1) & -alignment;
3545 type->base.size = size;
3546 type->base.alignment = alignment;
3549 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3551 type_t *type = NULL;
3552 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3553 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3554 unsigned type_specifiers = 0;
3555 bool newtype = false;
3556 bool saw_error = false;
3557 bool old_gcc_extension = in_gcc_extension;
3559 specifiers->source_position = token.source_position;
3562 specifiers->modifiers
3563 |= parse_attributes(&specifiers->gnu_attributes);
3564 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3565 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3567 switch (token.type) {
3570 #define MATCH_STORAGE_CLASS(token, class) \
3572 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3573 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3575 specifiers->storage_class = class; \
3579 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3580 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3581 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3582 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3583 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3588 add_anchor_token(')');
3589 parse_microsoft_extended_decl_modifier(specifiers);
3590 rem_anchor_token(')');
3597 add_anchor_token(')');
3598 parse_microsoft_based(specifiers);
3599 rem_anchor_token(')');
3604 switch (specifiers->storage_class) {
3605 case STORAGE_CLASS_NONE:
3606 specifiers->storage_class = STORAGE_CLASS_THREAD;
3609 case STORAGE_CLASS_EXTERN:
3610 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3613 case STORAGE_CLASS_STATIC:
3614 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3618 errorf(HERE, "multiple storage classes in declaration specifiers");
3624 /* type qualifiers */
3625 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3627 qualifiers |= qualifier; \
3631 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3632 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3633 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3634 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3635 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3636 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3637 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3638 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3640 case T___extension__:
3642 in_gcc_extension = true;
3645 /* type specifiers */
3646 #define MATCH_SPECIFIER(token, specifier, name) \
3648 if (type_specifiers & specifier) { \
3649 errorf(HERE, "multiple " name " type specifiers given"); \
3651 type_specifiers |= specifier; \
3656 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3657 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3658 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3659 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3660 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3661 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3662 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3663 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3664 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3665 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3666 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3667 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3668 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3669 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3670 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3671 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3672 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3674 case T__forceinline:
3675 /* only in microsoft mode */
3676 specifiers->modifiers |= DM_FORCEINLINE;
3681 specifiers->is_inline = true;
3685 if (type_specifiers & SPECIFIER_LONG_LONG) {
3686 errorf(HERE, "multiple type specifiers given");
3687 } else if (type_specifiers & SPECIFIER_LONG) {
3688 type_specifiers |= SPECIFIER_LONG_LONG;
3690 type_specifiers |= SPECIFIER_LONG;
3696 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3698 type->compound.compound = parse_compound_type_specifier(true);
3699 finish_struct_type(&type->compound);
3703 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3704 type->compound.compound = parse_compound_type_specifier(false);
3705 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3706 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3707 finish_union_type(&type->compound);
3711 type = parse_enum_specifier();
3714 type = parse_typeof();
3716 case T___builtin_va_list:
3717 type = duplicate_type(type_valist);
3721 case T_IDENTIFIER: {
3722 /* only parse identifier if we haven't found a type yet */
3723 if (type != NULL || type_specifiers != 0) {
3724 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3725 * declaration, so it doesn't generate errors about expecting '(' or
3727 switch (look_ahead(1)->type) {
3734 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3738 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3743 goto finish_specifiers;
3747 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3748 if (typedef_type == NULL) {
3749 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3750 * declaration, so it doesn't generate 'implicit int' followed by more
3751 * errors later on. */
3752 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3758 errorf(HERE, "%K does not name a type", &token);
3761 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3763 type = allocate_type_zero(TYPE_TYPEDEF);
3764 type->typedeft.typedefe = &entity->typedefe;
3768 if (la1_type == '&' || la1_type == '*')
3769 goto finish_specifiers;
3774 goto finish_specifiers;
3779 type = typedef_type;
3783 /* function specifier */
3785 goto finish_specifiers;
3790 in_gcc_extension = old_gcc_extension;
3792 if (type == NULL || (saw_error && type_specifiers != 0)) {
3793 atomic_type_kind_t atomic_type;
3795 /* match valid basic types */
3796 switch (type_specifiers) {
3797 case SPECIFIER_VOID:
3798 atomic_type = ATOMIC_TYPE_VOID;
3800 case SPECIFIER_CHAR:
3801 atomic_type = ATOMIC_TYPE_CHAR;
3803 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3804 atomic_type = ATOMIC_TYPE_SCHAR;
3806 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3807 atomic_type = ATOMIC_TYPE_UCHAR;
3809 case SPECIFIER_SHORT:
3810 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3811 case SPECIFIER_SHORT | SPECIFIER_INT:
3812 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3813 atomic_type = ATOMIC_TYPE_SHORT;
3815 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3816 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3817 atomic_type = ATOMIC_TYPE_USHORT;
3820 case SPECIFIER_SIGNED:
3821 case SPECIFIER_SIGNED | SPECIFIER_INT:
3822 atomic_type = ATOMIC_TYPE_INT;
3824 case SPECIFIER_UNSIGNED:
3825 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3826 atomic_type = ATOMIC_TYPE_UINT;
3828 case SPECIFIER_LONG:
3829 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3830 case SPECIFIER_LONG | SPECIFIER_INT:
3831 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3832 atomic_type = ATOMIC_TYPE_LONG;
3834 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3835 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3836 atomic_type = ATOMIC_TYPE_ULONG;
3839 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3840 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3841 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3842 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3844 atomic_type = ATOMIC_TYPE_LONGLONG;
3845 goto warn_about_long_long;
3847 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3848 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3850 atomic_type = ATOMIC_TYPE_ULONGLONG;
3851 warn_about_long_long:
3852 if (warning.long_long) {
3853 warningf(&specifiers->source_position,
3854 "ISO C90 does not support 'long long'");
3858 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3859 atomic_type = unsigned_int8_type_kind;
3862 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3863 atomic_type = unsigned_int16_type_kind;
3866 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3867 atomic_type = unsigned_int32_type_kind;
3870 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3871 atomic_type = unsigned_int64_type_kind;
3874 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3875 atomic_type = unsigned_int128_type_kind;
3878 case SPECIFIER_INT8:
3879 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3880 atomic_type = int8_type_kind;
3883 case SPECIFIER_INT16:
3884 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3885 atomic_type = int16_type_kind;
3888 case SPECIFIER_INT32:
3889 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3890 atomic_type = int32_type_kind;
3893 case SPECIFIER_INT64:
3894 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3895 atomic_type = int64_type_kind;
3898 case SPECIFIER_INT128:
3899 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3900 atomic_type = int128_type_kind;
3903 case SPECIFIER_FLOAT:
3904 atomic_type = ATOMIC_TYPE_FLOAT;
3906 case SPECIFIER_DOUBLE:
3907 atomic_type = ATOMIC_TYPE_DOUBLE;
3909 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3910 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3912 case SPECIFIER_BOOL:
3913 atomic_type = ATOMIC_TYPE_BOOL;
3915 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3916 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3917 atomic_type = ATOMIC_TYPE_FLOAT;
3919 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3920 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3921 atomic_type = ATOMIC_TYPE_DOUBLE;
3923 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3924 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3925 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3928 /* invalid specifier combination, give an error message */
3929 if (type_specifiers == 0) {
3933 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3934 if (!(c_mode & _CXX) && !strict_mode) {
3935 if (warning.implicit_int) {
3936 warningf(HERE, "no type specifiers in declaration, using 'int'");
3938 atomic_type = ATOMIC_TYPE_INT;
3941 errorf(HERE, "no type specifiers given in declaration");
3943 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3944 (type_specifiers & SPECIFIER_UNSIGNED)) {
3945 errorf(HERE, "signed and unsigned specifiers given");
3946 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3947 errorf(HERE, "only integer types can be signed or unsigned");
3949 errorf(HERE, "multiple datatypes in declaration");
3954 if (type_specifiers & SPECIFIER_COMPLEX) {
3955 type = allocate_type_zero(TYPE_COMPLEX);
3956 type->complex.akind = atomic_type;
3957 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3958 type = allocate_type_zero(TYPE_IMAGINARY);
3959 type->imaginary.akind = atomic_type;
3961 type = allocate_type_zero(TYPE_ATOMIC);
3962 type->atomic.akind = atomic_type;
3965 } else if (type_specifiers != 0) {
3966 errorf(HERE, "multiple datatypes in declaration");
3969 /* FIXME: check type qualifiers here */
3971 type->base.qualifiers = qualifiers;
3972 type->base.modifiers = modifiers;
3974 type_t *result = typehash_insert(type);
3975 if (newtype && result != type) {
3979 specifiers->type = result;
3983 specifiers->type = type_error_type;
3987 static type_qualifiers_t parse_type_qualifiers(void)
3989 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3992 switch (token.type) {
3993 /* type qualifiers */
3994 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3995 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3996 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3997 /* microsoft extended type modifiers */
3998 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3999 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4000 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4001 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4002 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4011 * Parses an K&R identifier list
4013 static void parse_identifier_list(scope_t *scope)
4016 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4017 entity->base.source_position = token.source_position;
4018 entity->base.namespc = NAMESPACE_NORMAL;
4019 entity->base.symbol = token.v.symbol;
4020 /* a K&R parameter has no type, yet */
4023 append_entity(scope, entity);
4025 if (token.type != ',') {
4029 } while (token.type == T_IDENTIFIER);
4032 static type_t *automatic_type_conversion(type_t *orig_type);
4034 static void semantic_parameter(declaration_t *declaration)
4036 /* TODO: improve error messages */
4037 source_position_t const* const pos = &declaration->base.source_position;
4040 switch (declaration->declared_storage_class) {
4041 /* Allowed storage classes */
4042 case STORAGE_CLASS_NONE:
4043 case STORAGE_CLASS_REGISTER:
4047 errorf(pos, "parameter may only have none or register storage class");
4051 type_t *const orig_type = declaration->type;
4052 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
4053 * sugar. Turn it into a pointer.
4054 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4055 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4057 type_t *const type = automatic_type_conversion(orig_type);
4058 declaration->type = type;
4060 if (is_type_incomplete(skip_typeref(type))) {
4061 errorf(pos, "parameter '%#T' is of incomplete type",
4062 orig_type, declaration->base.symbol);
4066 static entity_t *parse_parameter(void)
4068 declaration_specifiers_t specifiers;
4069 memset(&specifiers, 0, sizeof(specifiers));
4071 parse_declaration_specifiers(&specifiers);
4073 entity_t *entity = parse_declarator(&specifiers, true, false);
4074 anonymous_entity = NULL;
4079 * Parses function type parameters (and optionally creates variable_t entities
4080 * for them in a scope)
4082 static void parse_parameters(function_type_t *type, scope_t *scope)
4085 add_anchor_token(')');
4086 int saved_comma_state = save_and_reset_anchor_state(',');
4088 if (token.type == T_IDENTIFIER &&
4089 !is_typedef_symbol(token.v.symbol)) {
4090 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4091 if (la1_type == ',' || la1_type == ')') {
4092 type->kr_style_parameters = true;
4093 parse_identifier_list(scope);
4094 goto parameters_finished;
4098 if (token.type == ')') {
4099 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4100 if (!(c_mode & _CXX))
4101 type->unspecified_parameters = true;
4102 goto parameters_finished;
4105 function_parameter_t *parameter;
4106 function_parameter_t *last_parameter = NULL;
4109 switch (token.type) {
4112 type->variadic = true;
4113 goto parameters_finished;
4116 case T___extension__:
4119 entity_t *entity = parse_parameter();
4120 if (entity->kind == ENTITY_TYPEDEF) {
4121 errorf(&entity->base.source_position,
4122 "typedef not allowed as function parameter");
4125 assert(is_declaration(entity));
4127 /* func(void) is not a parameter */
4128 if (last_parameter == NULL
4129 && token.type == ')'
4130 && entity->base.symbol == NULL
4131 && skip_typeref(entity->declaration.type) == type_void) {
4132 goto parameters_finished;
4134 semantic_parameter(&entity->declaration);
4136 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4137 memset(parameter, 0, sizeof(parameter[0]));
4138 parameter->type = entity->declaration.type;
4140 if (scope != NULL) {
4141 append_entity(scope, entity);
4144 if (last_parameter != NULL) {
4145 last_parameter->next = parameter;
4147 type->parameters = parameter;
4149 last_parameter = parameter;
4154 goto parameters_finished;
4156 if (token.type != ',') {
4157 goto parameters_finished;
4163 parameters_finished:
4164 rem_anchor_token(')');
4168 restore_anchor_state(',', saved_comma_state);
4171 typedef enum construct_type_kind_t {
4174 CONSTRUCT_REFERENCE,
4177 } construct_type_kind_t;
4179 typedef struct construct_type_t construct_type_t;
4180 struct construct_type_t {
4181 construct_type_kind_t kind;
4182 construct_type_t *next;
4185 typedef struct parsed_pointer_t parsed_pointer_t;
4186 struct parsed_pointer_t {
4187 construct_type_t construct_type;
4188 type_qualifiers_t type_qualifiers;
4191 typedef struct parsed_reference_t parsed_reference_t;
4192 struct parsed_reference_t {
4193 construct_type_t construct_type;
4196 typedef struct construct_function_type_t construct_function_type_t;
4197 struct construct_function_type_t {
4198 construct_type_t construct_type;
4199 type_t *function_type;
4202 typedef struct parsed_array_t parsed_array_t;
4203 struct parsed_array_t {
4204 construct_type_t construct_type;
4205 type_qualifiers_t type_qualifiers;
4211 typedef struct construct_base_type_t construct_base_type_t;
4212 struct construct_base_type_t {
4213 construct_type_t construct_type;
4217 static construct_type_t *parse_pointer_declarator(void)
4221 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4222 memset(pointer, 0, sizeof(pointer[0]));
4223 pointer->construct_type.kind = CONSTRUCT_POINTER;
4224 pointer->type_qualifiers = parse_type_qualifiers();
4226 return (construct_type_t*) pointer;
4229 static construct_type_t *parse_reference_declarator(void)
4233 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4234 memset(reference, 0, sizeof(reference[0]));
4235 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4237 return (construct_type_t*)reference;
4240 static construct_type_t *parse_array_declarator(void)
4243 add_anchor_token(']');
4245 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4246 memset(array, 0, sizeof(array[0]));
4247 array->construct_type.kind = CONSTRUCT_ARRAY;
4249 if (token.type == T_static) {
4250 array->is_static = true;
4254 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4255 if (type_qualifiers != 0) {
4256 if (token.type == T_static) {
4257 array->is_static = true;
4261 array->type_qualifiers = type_qualifiers;
4263 if (token.type == '*' && look_ahead(1)->type == ']') {
4264 array->is_variable = true;
4266 } else if (token.type != ']') {
4267 array->size = parse_assignment_expression();
4270 rem_anchor_token(']');
4274 return (construct_type_t*) array;
4277 static construct_type_t *parse_function_declarator(scope_t *scope,
4278 decl_modifiers_t modifiers)
4280 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4281 function_type_t *ftype = &type->function;
4283 ftype->linkage = current_linkage;
4285 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4286 case DM_NONE: break;
4287 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4288 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4289 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4290 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4293 errorf(HERE, "multiple calling conventions in declaration");
4297 parse_parameters(ftype, scope);
4299 construct_function_type_t *construct_function_type =
4300 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4301 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4302 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4303 construct_function_type->function_type = type;
4305 return &construct_function_type->construct_type;
4308 typedef struct parse_declarator_env_t {
4309 decl_modifiers_t modifiers;
4311 source_position_t source_position;
4313 } parse_declarator_env_t;
4315 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4316 bool may_be_abstract)
4318 /* construct a single linked list of construct_type_t's which describe
4319 * how to construct the final declarator type */
4320 construct_type_t *first = NULL;
4321 construct_type_t *last = NULL;
4322 gnu_attribute_t *attributes = NULL;
4324 decl_modifiers_t modifiers = parse_attributes(&attributes);
4327 construct_type_t *type;
4328 switch (token.type) {
4330 if (!(c_mode & _CXX))
4331 errorf(HERE, "references are only available for C++");
4332 type = parse_reference_declarator();
4336 type = parse_pointer_declarator();
4340 goto ptr_operator_end;
4351 /* TODO: find out if this is correct */
4352 modifiers |= parse_attributes(&attributes);
4357 modifiers |= env->modifiers;
4358 env->modifiers = modifiers;
4361 construct_type_t *inner_types = NULL;
4363 switch (token.type) {
4366 errorf(HERE, "no identifier expected in typename");
4368 env->symbol = token.v.symbol;
4369 env->source_position = token.source_position;
4375 add_anchor_token(')');
4376 inner_types = parse_inner_declarator(env, may_be_abstract);
4377 if (inner_types != NULL) {
4378 /* All later declarators only modify the return type */
4381 rem_anchor_token(')');
4385 if (may_be_abstract)
4387 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4392 construct_type_t *p = last;
4395 construct_type_t *type;
4396 switch (token.type) {
4398 scope_t *scope = NULL;
4400 scope = &env->parameters;
4402 type = parse_function_declarator(scope, modifiers);
4406 type = parse_array_declarator();
4409 goto declarator_finished;
4412 /* insert in the middle of the list (behind p) */
4414 type->next = p->next;
4425 declarator_finished:
4426 /* append inner_types at the end of the list, we don't to set last anymore
4427 * as it's not needed anymore */
4429 assert(first == NULL);
4430 first = inner_types;
4432 last->next = inner_types;
4440 static void parse_declaration_attributes(entity_t *entity)
4442 gnu_attribute_t *attributes = NULL;
4443 decl_modifiers_t modifiers = parse_attributes(&attributes);
4449 if (entity->kind == ENTITY_TYPEDEF) {
4450 modifiers |= entity->typedefe.modifiers;
4451 type = entity->typedefe.type;
4453 assert(is_declaration(entity));
4454 modifiers |= entity->declaration.modifiers;
4455 type = entity->declaration.type;
4460 /* handle these strange/stupid mode attributes */
4461 gnu_attribute_t *attribute = attributes;
4462 for ( ; attribute != NULL; attribute = attribute->next) {
4463 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4466 atomic_type_kind_t akind = attribute->u.akind;
4467 if (!is_type_signed(type)) {
4469 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4470 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4471 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4472 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4474 panic("invalid akind in mode attribute");
4478 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4479 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4480 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4481 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4483 panic("invalid akind in mode attribute");
4487 type = make_atomic_type(akind, type->base.qualifiers);
4490 type_modifiers_t type_modifiers = type->base.modifiers;
4491 if (modifiers & DM_TRANSPARENT_UNION)
4492 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4494 if (type->base.modifiers != type_modifiers) {
4495 type_t *copy = duplicate_type(type);
4496 copy->base.modifiers = type_modifiers;
4498 type = typehash_insert(copy);
4500 obstack_free(type_obst, copy);
4504 if (entity->kind == ENTITY_TYPEDEF) {
4505 entity->typedefe.type = type;
4506 entity->typedefe.modifiers = modifiers;
4508 entity->declaration.type = type;
4509 entity->declaration.modifiers = modifiers;
4513 static type_t *construct_declarator_type(construct_type_t *construct_list,
4514 type_t *type, variable_t *variable)
4516 construct_type_t *iter = construct_list;
4517 for (; iter != NULL; iter = iter->next) {
4518 switch (iter->kind) {
4519 case CONSTRUCT_INVALID:
4520 internal_errorf(HERE, "invalid type construction found");
4521 case CONSTRUCT_FUNCTION: {
4522 construct_function_type_t *construct_function_type
4523 = (construct_function_type_t*) iter;
4525 type_t *function_type = construct_function_type->function_type;
4527 function_type->function.return_type = type;
4529 type_t *skipped_return_type = skip_typeref(type);
4531 if (is_type_function(skipped_return_type)) {
4532 errorf(HERE, "function returning function is not allowed");
4533 } else if (is_type_array(skipped_return_type)) {
4534 errorf(HERE, "function returning array is not allowed");
4536 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4538 "type qualifiers in return type of function type are meaningless");
4542 type = function_type;
4546 case CONSTRUCT_POINTER: {
4547 if (is_type_reference(skip_typeref(type)))
4548 errorf(HERE, "cannot declare a pointer to reference");
4550 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4551 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, variable);
4555 case CONSTRUCT_REFERENCE:
4556 if (is_type_reference(skip_typeref(type)))
4557 errorf(HERE, "cannot declare a reference to reference");
4559 type = make_reference_type(type);
4562 case CONSTRUCT_ARRAY: {
4563 if (is_type_reference(skip_typeref(type)))
4564 errorf(HERE, "cannot declare an array of references");
4566 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4567 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4569 expression_t *size_expression = parsed_array->size;
4570 if (size_expression != NULL) {
4572 = create_implicit_cast(size_expression, type_size_t);
4575 array_type->base.qualifiers = parsed_array->type_qualifiers;
4576 array_type->array.element_type = type;
4577 array_type->array.is_static = parsed_array->is_static;
4578 array_type->array.is_variable = parsed_array->is_variable;
4579 array_type->array.size_expression = size_expression;
4581 if (size_expression != NULL) {
4582 if (is_constant_expression(size_expression)) {
4583 array_type->array.size_constant = true;
4584 array_type->array.size
4585 = fold_constant(size_expression);
4587 array_type->array.is_vla = true;
4591 type_t *skipped_type = skip_typeref(type);
4593 if (is_type_incomplete(skipped_type)) {
4594 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4595 } else if (is_type_function(skipped_type)) {
4596 errorf(HERE, "array of functions is not allowed");
4603 type_t *hashed_type = typehash_insert(type);
4604 if (hashed_type != type) {
4605 /* the function type was constructed earlier freeing it here will
4606 * destroy other types... */
4607 if (iter->kind != CONSTRUCT_FUNCTION) {
4617 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4618 bool may_be_abstract,
4619 bool create_compound_member)
4621 parse_declarator_env_t env;
4622 memset(&env, 0, sizeof(env));
4623 env.modifiers = specifiers->modifiers;
4625 construct_type_t *construct_type
4626 = parse_inner_declarator(&env, may_be_abstract);
4627 type_t *type = construct_declarator_type(construct_type, specifiers->type, specifiers->based_variable);
4629 if (construct_type != NULL) {
4630 obstack_free(&temp_obst, construct_type);
4634 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4635 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4636 entity->base.symbol = env.symbol;
4637 entity->base.source_position = env.source_position;
4638 entity->typedefe.type = type;
4640 if (anonymous_entity != NULL) {
4641 if (is_type_compound(type)) {
4642 assert(anonymous_entity->compound.alias == NULL);
4643 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4644 anonymous_entity->kind == ENTITY_UNION);
4645 anonymous_entity->compound.alias = entity;
4646 anonymous_entity = NULL;
4647 } else if (is_type_enum(type)) {
4648 assert(anonymous_entity->enume.alias == NULL);
4649 assert(anonymous_entity->kind == ENTITY_ENUM);
4650 anonymous_entity->enume.alias = entity;
4651 anonymous_entity = NULL;
4655 if (create_compound_member) {
4656 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4657 } else if (is_type_function(skip_typeref(type))) {
4658 entity = allocate_entity_zero(ENTITY_FUNCTION);
4660 entity->function.is_inline = specifiers->is_inline;
4661 entity->function.parameters = env.parameters;
4663 entity = allocate_entity_zero(ENTITY_VARIABLE);
4665 entity->variable.get_property_sym = specifiers->get_property_sym;
4666 entity->variable.put_property_sym = specifiers->put_property_sym;
4667 if (specifiers->alignment != 0) {
4668 /* TODO: add checks here */
4669 entity->variable.alignment = specifiers->alignment;
4672 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4673 warningf(&env.source_position,
4674 "variable '%Y' declared 'inline'\n", env.symbol);
4678 entity->base.source_position = env.source_position;
4679 entity->base.symbol = env.symbol;
4680 entity->base.namespc = NAMESPACE_NORMAL;
4681 entity->declaration.type = type;
4682 entity->declaration.modifiers = env.modifiers;
4683 entity->declaration.deprecated_string = specifiers->deprecated_string;
4685 storage_class_t storage_class = specifiers->storage_class;
4686 entity->declaration.declared_storage_class = storage_class;
4688 if (storage_class == STORAGE_CLASS_NONE
4689 && current_scope != file_scope) {
4690 storage_class = STORAGE_CLASS_AUTO;
4692 entity->declaration.storage_class = storage_class;
4695 parse_declaration_attributes(entity);
4700 static type_t *parse_abstract_declarator(type_t *base_type)
4702 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4704 type_t *result = construct_declarator_type(construct_type, base_type, NULL);
4705 if (construct_type != NULL) {
4706 obstack_free(&temp_obst, construct_type);
4713 * Check if the declaration of main is suspicious. main should be a
4714 * function with external linkage, returning int, taking either zero
4715 * arguments, two, or three arguments of appropriate types, ie.
4717 * int main([ int argc, char **argv [, char **env ] ]).
4719 * @param decl the declaration to check
4720 * @param type the function type of the declaration
4722 static void check_type_of_main(const entity_t *entity)
4724 const source_position_t *pos = &entity->base.source_position;
4725 if (entity->kind != ENTITY_FUNCTION) {
4726 warningf(pos, "'main' is not a function");
4730 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4731 warningf(pos, "'main' is normally a non-static function");
4734 type_t *type = skip_typeref(entity->declaration.type);
4735 assert(is_type_function(type));
4737 function_type_t *func_type = &type->function;
4738 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4739 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4740 func_type->return_type);
4742 const function_parameter_t *parm = func_type->parameters;
4744 type_t *const first_type = parm->type;
4745 if (!types_compatible(skip_typeref(first_type), type_int)) {
4747 "first argument of 'main' should be 'int', but is '%T'",
4752 type_t *const second_type = parm->type;
4753 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4754 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4758 type_t *const third_type = parm->type;
4759 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4760 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4764 goto warn_arg_count;
4768 warningf(pos, "'main' takes only zero, two or three arguments");
4774 * Check if a symbol is the equal to "main".
4776 static bool is_sym_main(const symbol_t *const sym)
4778 return strcmp(sym->string, "main") == 0;
4781 static const char *get_entity_kind_name(entity_kind_t kind)
4783 switch ((entity_kind_tag_t) kind) {
4784 case ENTITY_FUNCTION: return "function";
4785 case ENTITY_VARIABLE: return "variable";
4786 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4787 case ENTITY_STRUCT: return "struct";
4788 case ENTITY_UNION: return "union";
4789 case ENTITY_ENUM: return "enum";
4790 case ENTITY_ENUM_VALUE: return "enum value";
4791 case ENTITY_LABEL: return "label";
4792 case ENTITY_LOCAL_LABEL: return "local label";
4793 case ENTITY_TYPEDEF: return "typedef";
4794 case ENTITY_NAMESPACE: return "namespace";
4795 case ENTITY_INVALID: break;
4798 panic("Invalid entity kind encountered in get_entity_kind_name");
4801 static void error_redefined_as_different_kind(const source_position_t *pos,
4802 const entity_t *old, entity_kind_t new_kind)
4804 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4805 get_entity_kind_name(old->kind), old->base.symbol,
4806 get_entity_kind_name(new_kind), &old->base.source_position);
4810 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4811 * for various problems that occur for multiple definitions
4813 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4815 const symbol_t *const symbol = entity->base.symbol;
4816 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4817 const source_position_t *pos = &entity->base.source_position;
4819 assert(symbol != NULL);
4820 entity_t *previous_entity = get_entity(symbol, namespc);
4821 /* pushing the same entity twice will break the stack structure */
4822 assert(previous_entity != entity);
4824 if (entity->kind == ENTITY_FUNCTION) {
4825 type_t *const orig_type = entity->declaration.type;
4826 type_t *const type = skip_typeref(orig_type);
4828 assert(is_type_function(type));
4829 if (type->function.unspecified_parameters &&
4830 warning.strict_prototypes &&
4831 previous_entity == NULL) {
4832 warningf(pos, "function declaration '%#T' is not a prototype",
4836 if (warning.main && current_scope == file_scope
4837 && is_sym_main(symbol)) {
4838 check_type_of_main(entity);
4842 if (is_declaration(entity)) {
4843 if (warning.nested_externs
4844 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4845 && current_scope != file_scope) {
4846 warningf(pos, "nested extern declaration of '%#T'",
4847 entity->declaration.type, symbol);
4851 if (previous_entity != NULL
4852 && previous_entity->base.parent_scope == ¤t_function->parameters
4853 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4855 assert(previous_entity->kind == ENTITY_VARIABLE);
4857 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4858 entity->declaration.type, symbol,
4859 previous_entity->declaration.type, symbol,
4860 &previous_entity->base.source_position);
4864 if (previous_entity != NULL
4865 && previous_entity->base.parent_scope == current_scope) {
4867 if (previous_entity->kind != entity->kind) {
4868 error_redefined_as_different_kind(pos, previous_entity,
4872 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4874 "redeclaration of enum entry '%Y' (declared %P)",
4875 symbol, &previous_entity->base.source_position);
4878 if (previous_entity->kind == ENTITY_TYPEDEF) {
4879 /* TODO: C++ allows this for exactly the same type */
4881 "redefinition of typedef '%Y' (declared %P)",
4882 symbol, &previous_entity->base.source_position);
4886 /* at this point we should have only VARIABLES or FUNCTIONS */
4887 assert(is_declaration(previous_entity) && is_declaration(entity));
4889 /* can happen for K&R style declarations */
4890 if (previous_entity->kind == ENTITY_VARIABLE
4891 && previous_entity->declaration.type == NULL
4892 && entity->kind == ENTITY_VARIABLE) {
4893 previous_entity->declaration.type = entity->declaration.type;
4894 previous_entity->declaration.storage_class
4895 = entity->declaration.storage_class;
4896 previous_entity->declaration.declared_storage_class
4897 = entity->declaration.declared_storage_class;
4898 previous_entity->declaration.modifiers
4899 = entity->declaration.modifiers;
4900 previous_entity->declaration.deprecated_string
4901 = entity->declaration.deprecated_string;
4903 assert(entity->declaration.type != NULL);
4905 declaration_t *const previous_declaration
4906 = &previous_entity->declaration;
4907 declaration_t *const declaration = &entity->declaration;
4908 type_t *const orig_type = entity->declaration.type;
4909 type_t *const type = skip_typeref(orig_type);
4911 type_t *prev_type = skip_typeref(previous_declaration->type);
4913 if (!types_compatible(type, prev_type)) {
4915 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4916 orig_type, symbol, previous_declaration->type, symbol,
4917 &previous_entity->base.source_position);
4919 unsigned old_storage_class = previous_declaration->storage_class;
4920 if (warning.redundant_decls && is_definition
4921 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4922 && !(previous_declaration->modifiers & DM_USED)
4923 && !previous_declaration->used) {
4924 warningf(&previous_entity->base.source_position,
4925 "unnecessary static forward declaration for '%#T'",
4926 previous_declaration->type, symbol);
4929 unsigned new_storage_class = declaration->storage_class;
4930 if (is_type_incomplete(prev_type)) {
4931 previous_declaration->type = type;
4935 /* pretend no storage class means extern for function
4936 * declarations (except if the previous declaration is neither
4937 * none nor extern) */
4938 if (entity->kind == ENTITY_FUNCTION) {
4939 if (prev_type->function.unspecified_parameters) {
4940 previous_declaration->type = type;
4944 switch (old_storage_class) {
4945 case STORAGE_CLASS_NONE:
4946 old_storage_class = STORAGE_CLASS_EXTERN;
4949 case STORAGE_CLASS_EXTERN:
4950 if (is_definition) {
4951 if (warning.missing_prototypes &&
4952 prev_type->function.unspecified_parameters &&
4953 !is_sym_main(symbol)) {
4954 warningf(pos, "no previous prototype for '%#T'",
4957 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4958 new_storage_class = STORAGE_CLASS_EXTERN;
4967 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4968 new_storage_class == STORAGE_CLASS_EXTERN) {
4969 warn_redundant_declaration:
4970 if (!is_definition &&
4971 warning.redundant_decls &&
4972 is_type_valid(prev_type) &&
4973 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4975 "redundant declaration for '%Y' (declared %P)",
4976 symbol, &previous_entity->base.source_position);
4978 } else if (current_function == NULL) {
4979 if (old_storage_class != STORAGE_CLASS_STATIC &&
4980 new_storage_class == STORAGE_CLASS_STATIC) {
4982 "static declaration of '%Y' follows non-static declaration (declared %P)",
4983 symbol, &previous_entity->base.source_position);
4984 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4985 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4986 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4988 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4990 goto error_redeclaration;
4991 goto warn_redundant_declaration;
4993 } else if (is_type_valid(prev_type)) {
4994 if (old_storage_class == new_storage_class) {
4995 error_redeclaration:
4996 errorf(pos, "redeclaration of '%Y' (declared %P)",
4997 symbol, &previous_entity->base.source_position);
5000 "redeclaration of '%Y' with different linkage (declared %P)",
5001 symbol, &previous_entity->base.source_position);
5006 previous_declaration->modifiers |= declaration->modifiers;
5007 if (entity->kind == ENTITY_FUNCTION) {
5008 previous_entity->function.is_inline |= entity->function.is_inline;
5010 return previous_entity;
5013 if (entity->kind == ENTITY_FUNCTION) {
5014 if (is_definition &&
5015 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5016 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5017 warningf(pos, "no previous prototype for '%#T'",
5018 entity->declaration.type, symbol);
5019 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5020 warningf(pos, "no previous declaration for '%#T'",
5021 entity->declaration.type, symbol);
5024 } else if (warning.missing_declarations
5025 && entity->kind == ENTITY_VARIABLE
5026 && current_scope == file_scope) {
5027 declaration_t *declaration = &entity->declaration;
5028 if (declaration->storage_class == STORAGE_CLASS_NONE ||
5029 declaration->storage_class == STORAGE_CLASS_THREAD) {
5030 warningf(pos, "no previous declaration for '%#T'",
5031 declaration->type, symbol);
5036 assert(entity->base.parent_scope == NULL);
5037 assert(current_scope != NULL);
5039 entity->base.parent_scope = current_scope;
5040 entity->base.namespc = NAMESPACE_NORMAL;
5041 environment_push(entity);
5042 append_entity(current_scope, entity);
5047 static void parser_error_multiple_definition(entity_t *entity,
5048 const source_position_t *source_position)
5050 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5051 entity->base.symbol, &entity->base.source_position);
5054 static bool is_declaration_specifier(const token_t *token,
5055 bool only_specifiers_qualifiers)
5057 switch (token->type) {
5062 return is_typedef_symbol(token->v.symbol);
5064 case T___extension__:
5066 return !only_specifiers_qualifiers;
5073 static void parse_init_declarator_rest(entity_t *entity)
5075 assert(is_declaration(entity));
5076 declaration_t *const declaration = &entity->declaration;
5080 type_t *orig_type = declaration->type;
5081 type_t *type = skip_typeref(orig_type);
5083 if (entity->kind == ENTITY_VARIABLE
5084 && entity->variable.initializer != NULL) {
5085 parser_error_multiple_definition(entity, HERE);
5088 bool must_be_constant = false;
5089 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5090 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5091 entity->base.parent_scope == file_scope) {
5092 must_be_constant = true;
5095 if (is_type_function(type)) {
5096 errorf(&entity->base.source_position,
5097 "function '%#T' is initialized like a variable",
5098 orig_type, entity->base.symbol);
5099 orig_type = type_error_type;
5102 parse_initializer_env_t env;
5103 env.type = orig_type;
5104 env.must_be_constant = must_be_constant;
5105 env.entity = entity;
5106 current_init_decl = entity;
5108 initializer_t *initializer = parse_initializer(&env);
5109 current_init_decl = NULL;
5111 if (entity->kind == ENTITY_VARIABLE) {
5112 /* § 6.7.5 (22) array initializers for arrays with unknown size
5113 * determine the array type size */
5114 declaration->type = env.type;
5115 entity->variable.initializer = initializer;
5119 /* parse rest of a declaration without any declarator */
5120 static void parse_anonymous_declaration_rest(
5121 const declaration_specifiers_t *specifiers)
5125 if (warning.other) {
5126 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5127 warningf(&specifiers->source_position,
5128 "useless storage class in empty declaration");
5131 type_t *type = specifiers->type;
5132 switch (type->kind) {
5133 case TYPE_COMPOUND_STRUCT:
5134 case TYPE_COMPOUND_UNION: {
5135 if (type->compound.compound->base.symbol == NULL) {
5136 warningf(&specifiers->source_position,
5137 "unnamed struct/union that defines no instances");
5146 warningf(&specifiers->source_position, "empty declaration");
5152 static void check_variable_type_complete(entity_t *ent)
5154 if (ent->kind != ENTITY_VARIABLE)
5157 declaration_t *decl = &ent->declaration;
5158 if (decl->storage_class == STORAGE_CLASS_EXTERN)
5161 type_t *type = decl->type;
5162 if (!is_type_incomplete(skip_typeref(type)))
5165 errorf(&ent->base.source_position,
5166 "variable '%#T' is of incomplete type", type, ent->base.symbol);
5170 static void parse_declaration_rest(entity_t *ndeclaration,
5171 const declaration_specifiers_t *specifiers,
5172 parsed_declaration_func finished_declaration)
5174 add_anchor_token(';');
5175 add_anchor_token(',');
5177 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5179 if (token.type == '=') {
5180 parse_init_declarator_rest(entity);
5183 check_variable_type_complete(entity);
5185 if (token.type != ',')
5189 add_anchor_token('=');
5190 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5191 rem_anchor_token('=');
5196 anonymous_entity = NULL;
5197 rem_anchor_token(';');
5198 rem_anchor_token(',');
5201 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5203 symbol_t *symbol = entity->base.symbol;
5204 if (symbol == NULL) {
5205 errorf(HERE, "anonymous declaration not valid as function parameter");
5209 assert(entity->base.namespc == NAMESPACE_NORMAL);
5210 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5211 if (previous_entity == NULL
5212 || previous_entity->base.parent_scope != current_scope) {
5213 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5218 if (is_definition) {
5219 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5222 return record_entity(entity, false);
5225 static void parse_declaration(parsed_declaration_func finished_declaration)
5227 declaration_specifiers_t specifiers;
5228 memset(&specifiers, 0, sizeof(specifiers));
5230 add_anchor_token(';');
5231 parse_declaration_specifiers(&specifiers);
5232 rem_anchor_token(';');
5234 if (token.type == ';') {
5235 parse_anonymous_declaration_rest(&specifiers);
5237 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5238 parse_declaration_rest(entity, &specifiers, finished_declaration);
5242 static type_t *get_default_promoted_type(type_t *orig_type)
5244 type_t *result = orig_type;
5246 type_t *type = skip_typeref(orig_type);
5247 if (is_type_integer(type)) {
5248 result = promote_integer(type);
5249 } else if (type == type_float) {
5250 result = type_double;
5256 static void parse_kr_declaration_list(entity_t *entity)
5258 if (entity->kind != ENTITY_FUNCTION)
5261 type_t *type = skip_typeref(entity->declaration.type);
5262 assert(is_type_function(type));
5263 if (!type->function.kr_style_parameters)
5267 add_anchor_token('{');
5269 /* push function parameters */
5270 size_t const top = environment_top();
5271 scope_push(&entity->function.parameters);
5273 entity_t *parameter = entity->function.parameters.entities;
5274 for ( ; parameter != NULL; parameter = parameter->base.next) {
5275 assert(parameter->base.parent_scope == NULL);
5276 parameter->base.parent_scope = current_scope;
5277 environment_push(parameter);
5280 /* parse declaration list */
5281 while (is_declaration_specifier(&token, false)) {
5282 parse_declaration(finished_kr_declaration);
5285 /* pop function parameters */
5286 assert(current_scope == &entity->function.parameters);
5288 environment_pop_to(top);
5290 /* update function type */
5291 type_t *new_type = duplicate_type(type);
5293 function_parameter_t *parameters = NULL;
5294 function_parameter_t *last_parameter = NULL;
5296 entity_t *parameter_declaration = entity->function.parameters.entities;
5297 for (; parameter_declaration != NULL;
5298 parameter_declaration = parameter_declaration->base.next) {
5299 type_t *parameter_type = parameter_declaration->declaration.type;
5300 if (parameter_type == NULL) {
5302 errorf(HERE, "no type specified for function parameter '%Y'",
5303 parameter_declaration->base.symbol);
5305 if (warning.implicit_int) {
5306 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5307 parameter_declaration->base.symbol);
5309 parameter_type = type_int;
5310 parameter_declaration->declaration.type = parameter_type;
5314 semantic_parameter(¶meter_declaration->declaration);
5315 parameter_type = parameter_declaration->declaration.type;
5318 * we need the default promoted types for the function type
5320 parameter_type = get_default_promoted_type(parameter_type);
5322 function_parameter_t *function_parameter
5323 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5324 memset(function_parameter, 0, sizeof(function_parameter[0]));
5326 function_parameter->type = parameter_type;
5327 if (last_parameter != NULL) {
5328 last_parameter->next = function_parameter;
5330 parameters = function_parameter;
5332 last_parameter = function_parameter;
5335 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5337 new_type->function.parameters = parameters;
5338 new_type->function.unspecified_parameters = true;
5340 type = typehash_insert(new_type);
5341 if (type != new_type) {
5342 obstack_free(type_obst, new_type);
5345 entity->declaration.type = type;
5347 rem_anchor_token('{');
5350 static bool first_err = true;
5353 * When called with first_err set, prints the name of the current function,
5356 static void print_in_function(void)
5360 diagnosticf("%s: In function '%Y':\n",
5361 current_function->base.base.source_position.input_name,
5362 current_function->base.base.symbol);
5367 * Check if all labels are defined in the current function.
5368 * Check if all labels are used in the current function.
5370 static void check_labels(void)
5372 for (const goto_statement_t *goto_statement = goto_first;
5373 goto_statement != NULL;
5374 goto_statement = goto_statement->next) {
5375 /* skip computed gotos */
5376 if (goto_statement->expression != NULL)
5379 label_t *label = goto_statement->label;
5382 if (label->base.source_position.input_name == NULL) {
5383 print_in_function();
5384 errorf(&goto_statement->base.source_position,
5385 "label '%Y' used but not defined", label->base.symbol);
5389 if (warning.unused_label) {
5390 for (const label_statement_t *label_statement = label_first;
5391 label_statement != NULL;
5392 label_statement = label_statement->next) {
5393 label_t *label = label_statement->label;
5395 if (! label->used) {
5396 print_in_function();
5397 warningf(&label_statement->base.source_position,
5398 "label '%Y' defined but not used", label->base.symbol);
5404 static void warn_unused_decl(entity_t *entity, entity_t *end,
5405 char const *const what)
5407 for (; entity != NULL; entity = entity->base.next) {
5408 if (!is_declaration(entity))
5411 declaration_t *declaration = &entity->declaration;
5412 if (declaration->implicit)
5415 if (!declaration->used) {
5416 print_in_function();
5417 warningf(&entity->base.source_position, "%s '%Y' is unused",
5418 what, entity->base.symbol);
5419 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5420 print_in_function();
5421 warningf(&entity->base.source_position, "%s '%Y' is never read",
5422 what, entity->base.symbol);
5430 static void check_unused_variables(statement_t *const stmt, void *const env)
5434 switch (stmt->kind) {
5435 case STATEMENT_DECLARATION: {
5436 declaration_statement_t const *const decls = &stmt->declaration;
5437 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5443 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5452 * Check declarations of current_function for unused entities.
5454 static void check_declarations(void)
5456 if (warning.unused_parameter) {
5457 const scope_t *scope = ¤t_function->parameters;
5459 /* do not issue unused warnings for main */
5460 if (!is_sym_main(current_function->base.base.symbol)) {
5461 warn_unused_decl(scope->entities, NULL, "parameter");
5464 if (warning.unused_variable) {
5465 walk_statements(current_function->statement, check_unused_variables,
5470 static int determine_truth(expression_t const* const cond)
5473 !is_constant_expression(cond) ? 0 :
5474 fold_constant(cond) != 0 ? 1 :
5478 static bool expression_returns(expression_t const *const expr)
5480 switch (expr->kind) {
5482 expression_t const *const func = expr->call.function;
5483 if (func->kind == EXPR_REFERENCE) {
5484 entity_t *entity = func->reference.entity;
5485 if (entity->kind == ENTITY_FUNCTION
5486 && entity->declaration.modifiers & DM_NORETURN)
5490 if (!expression_returns(func))
5493 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5494 if (!expression_returns(arg->expression))
5501 case EXPR_REFERENCE:
5502 case EXPR_REFERENCE_ENUM_VALUE:
5504 case EXPR_CHARACTER_CONSTANT:
5505 case EXPR_WIDE_CHARACTER_CONSTANT:
5506 case EXPR_STRING_LITERAL:
5507 case EXPR_WIDE_STRING_LITERAL:
5508 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5509 case EXPR_LABEL_ADDRESS:
5510 case EXPR_CLASSIFY_TYPE:
5511 case EXPR_SIZEOF: // TODO handle obscure VLA case
5514 case EXPR_BUILTIN_SYMBOL:
5515 case EXPR_BUILTIN_CONSTANT_P:
5516 case EXPR_BUILTIN_PREFETCH:
5519 case EXPR_STATEMENT: // TODO implement
5522 case EXPR_CONDITIONAL:
5523 // TODO handle constant expression
5525 expression_returns(expr->conditional.condition) && (
5526 expression_returns(expr->conditional.true_expression) ||
5527 expression_returns(expr->conditional.false_expression)
5531 return expression_returns(expr->select.compound);
5533 case EXPR_ARRAY_ACCESS:
5535 expression_returns(expr->array_access.array_ref) &&
5536 expression_returns(expr->array_access.index);
5539 return expression_returns(expr->va_starte.ap);
5542 return expression_returns(expr->va_arge.ap);
5544 EXPR_UNARY_CASES_MANDATORY
5545 return expression_returns(expr->unary.value);
5547 case EXPR_UNARY_THROW:
5551 // TODO handle constant lhs of && and ||
5553 expression_returns(expr->binary.left) &&
5554 expression_returns(expr->binary.right);
5560 panic("unhandled expression");
5563 static bool noreturn_candidate;
5565 static void check_reachable(statement_t *const stmt)
5567 if (stmt->base.reachable)
5569 if (stmt->kind != STATEMENT_DO_WHILE)
5570 stmt->base.reachable = true;
5572 statement_t *last = stmt;
5574 switch (stmt->kind) {
5575 case STATEMENT_INVALID:
5576 case STATEMENT_EMPTY:
5577 case STATEMENT_DECLARATION:
5578 case STATEMENT_LOCAL_LABEL:
5580 next = stmt->base.next;
5583 case STATEMENT_COMPOUND:
5584 next = stmt->compound.statements;
5587 case STATEMENT_RETURN:
5588 noreturn_candidate = false;
5591 case STATEMENT_IF: {
5592 if_statement_t const* const ifs = &stmt->ifs;
5593 int const val = determine_truth(ifs->condition);
5596 check_reachable(ifs->true_statement);
5601 if (ifs->false_statement != NULL) {
5602 check_reachable(ifs->false_statement);
5606 next = stmt->base.next;
5610 case STATEMENT_SWITCH: {
5611 switch_statement_t const *const switchs = &stmt->switchs;
5612 expression_t const *const expr = switchs->expression;
5614 if (is_constant_expression(expr)) {
5615 long const val = fold_constant(expr);
5616 case_label_statement_t * defaults = NULL;
5617 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5618 if (i->expression == NULL) {
5623 if (i->first_case <= val && val <= i->last_case) {
5624 check_reachable((statement_t*)i);
5629 if (defaults != NULL) {
5630 check_reachable((statement_t*)defaults);
5634 bool has_default = false;
5635 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5636 if (i->expression == NULL)
5639 check_reachable((statement_t*)i);
5646 next = stmt->base.next;
5650 case STATEMENT_EXPRESSION: {
5651 /* Check for noreturn function call */
5652 expression_t const *const expr = stmt->expression.expression;
5653 if (!expression_returns(expr))
5656 next = stmt->base.next;
5660 case STATEMENT_CONTINUE: {
5661 statement_t *parent = stmt;
5663 parent = parent->base.parent;
5664 if (parent == NULL) /* continue not within loop */
5668 switch (parent->kind) {
5669 case STATEMENT_WHILE: goto continue_while;
5670 case STATEMENT_DO_WHILE: goto continue_do_while;
5671 case STATEMENT_FOR: goto continue_for;
5678 case STATEMENT_BREAK: {
5679 statement_t *parent = stmt;
5681 parent = parent->base.parent;
5682 if (parent == NULL) /* break not within loop/switch */
5685 switch (parent->kind) {
5686 case STATEMENT_SWITCH:
5687 case STATEMENT_WHILE:
5688 case STATEMENT_DO_WHILE:
5691 next = parent->base.next;
5692 goto found_break_parent;
5701 case STATEMENT_GOTO:
5702 if (stmt->gotos.expression) {
5703 statement_t *parent = stmt->base.parent;
5704 if (parent == NULL) /* top level goto */
5708 next = stmt->gotos.label->statement;
5709 if (next == NULL) /* missing label */
5714 case STATEMENT_LABEL:
5715 next = stmt->label.statement;
5718 case STATEMENT_CASE_LABEL:
5719 next = stmt->case_label.statement;
5722 case STATEMENT_WHILE: {
5723 while_statement_t const *const whiles = &stmt->whiles;
5724 int const val = determine_truth(whiles->condition);
5727 check_reachable(whiles->body);
5732 next = stmt->base.next;
5736 case STATEMENT_DO_WHILE:
5737 next = stmt->do_while.body;
5740 case STATEMENT_FOR: {
5741 for_statement_t *const fors = &stmt->fors;
5743 if (fors->condition_reachable)
5745 fors->condition_reachable = true;
5747 expression_t const *const cond = fors->condition;
5749 cond == NULL ? 1 : determine_truth(cond);
5752 check_reachable(fors->body);
5757 next = stmt->base.next;
5761 case STATEMENT_MS_TRY: {
5762 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5763 check_reachable(ms_try->try_statement);
5764 next = ms_try->final_statement;
5768 case STATEMENT_LEAVE: {
5769 statement_t *parent = stmt;
5771 parent = parent->base.parent;
5772 if (parent == NULL) /* __leave not within __try */
5775 if (parent->kind == STATEMENT_MS_TRY) {
5777 next = parent->ms_try.final_statement;
5785 while (next == NULL) {
5786 next = last->base.parent;
5788 noreturn_candidate = false;
5790 type_t *const type = current_function->base.type;
5791 assert(is_type_function(type));
5792 type_t *const ret = skip_typeref(type->function.return_type);
5793 if (warning.return_type &&
5794 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5795 is_type_valid(ret) &&
5796 !is_sym_main(current_function->base.base.symbol)) {
5797 warningf(&stmt->base.source_position,
5798 "control reaches end of non-void function");
5803 switch (next->kind) {
5804 case STATEMENT_INVALID:
5805 case STATEMENT_EMPTY:
5806 case STATEMENT_DECLARATION:
5807 case STATEMENT_LOCAL_LABEL:
5808 case STATEMENT_EXPRESSION:
5810 case STATEMENT_RETURN:
5811 case STATEMENT_CONTINUE:
5812 case STATEMENT_BREAK:
5813 case STATEMENT_GOTO:
5814 case STATEMENT_LEAVE:
5815 panic("invalid control flow in function");
5817 case STATEMENT_COMPOUND:
5819 case STATEMENT_SWITCH:
5820 case STATEMENT_LABEL:
5821 case STATEMENT_CASE_LABEL:
5823 next = next->base.next;
5826 case STATEMENT_WHILE: {
5828 if (next->base.reachable)
5830 next->base.reachable = true;
5832 while_statement_t const *const whiles = &next->whiles;
5833 int const val = determine_truth(whiles->condition);
5836 check_reachable(whiles->body);
5842 next = next->base.next;
5846 case STATEMENT_DO_WHILE: {
5848 if (next->base.reachable)
5850 next->base.reachable = true;
5852 do_while_statement_t const *const dw = &next->do_while;
5853 int const val = determine_truth(dw->condition);
5856 check_reachable(dw->body);
5862 next = next->base.next;
5866 case STATEMENT_FOR: {
5868 for_statement_t *const fors = &next->fors;
5870 fors->step_reachable = true;
5872 if (fors->condition_reachable)
5874 fors->condition_reachable = true;
5876 expression_t const *const cond = fors->condition;
5878 cond == NULL ? 1 : determine_truth(cond);
5881 check_reachable(fors->body);
5887 next = next->base.next;
5891 case STATEMENT_MS_TRY:
5893 next = next->ms_try.final_statement;
5898 check_reachable(next);
5901 static void check_unreachable(statement_t* const stmt, void *const env)
5905 switch (stmt->kind) {
5906 case STATEMENT_DO_WHILE:
5907 if (!stmt->base.reachable) {
5908 expression_t const *const cond = stmt->do_while.condition;
5909 if (determine_truth(cond) >= 0) {
5910 warningf(&cond->base.source_position,
5911 "condition of do-while-loop is unreachable");
5916 case STATEMENT_FOR: {
5917 for_statement_t const* const fors = &stmt->fors;
5919 // if init and step are unreachable, cond is unreachable, too
5920 if (!stmt->base.reachable && !fors->step_reachable) {
5921 warningf(&stmt->base.source_position, "statement is unreachable");
5923 if (!stmt->base.reachable && fors->initialisation != NULL) {
5924 warningf(&fors->initialisation->base.source_position,
5925 "initialisation of for-statement is unreachable");
5928 if (!fors->condition_reachable && fors->condition != NULL) {
5929 warningf(&fors->condition->base.source_position,
5930 "condition of for-statement is unreachable");
5933 if (!fors->step_reachable && fors->step != NULL) {
5934 warningf(&fors->step->base.source_position,
5935 "step of for-statement is unreachable");
5941 case STATEMENT_COMPOUND:
5942 if (stmt->compound.statements != NULL)
5947 if (!stmt->base.reachable)
5948 warningf(&stmt->base.source_position, "statement is unreachable");
5953 static void parse_external_declaration(void)
5955 /* function-definitions and declarations both start with declaration
5957 declaration_specifiers_t specifiers;
5958 memset(&specifiers, 0, sizeof(specifiers));
5960 add_anchor_token(';');
5961 parse_declaration_specifiers(&specifiers);
5962 rem_anchor_token(';');
5964 /* must be a declaration */
5965 if (token.type == ';') {
5966 parse_anonymous_declaration_rest(&specifiers);
5970 add_anchor_token(',');
5971 add_anchor_token('=');
5972 add_anchor_token(';');
5973 add_anchor_token('{');
5975 /* declarator is common to both function-definitions and declarations */
5976 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5978 rem_anchor_token('{');
5979 rem_anchor_token(';');
5980 rem_anchor_token('=');
5981 rem_anchor_token(',');
5983 /* must be a declaration */
5984 switch (token.type) {
5988 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
5992 /* must be a function definition */
5993 parse_kr_declaration_list(ndeclaration);
5995 if (token.type != '{') {
5996 parse_error_expected("while parsing function definition", '{', NULL);
5997 eat_until_matching_token(';');
6001 assert(is_declaration(ndeclaration));
6002 type_t *type = skip_typeref(ndeclaration->declaration.type);
6004 if (!is_type_function(type)) {
6005 if (is_type_valid(type)) {
6006 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6007 type, ndeclaration->base.symbol);
6013 if (warning.aggregate_return &&
6014 is_type_compound(skip_typeref(type->function.return_type))) {
6015 warningf(HERE, "function '%Y' returns an aggregate",
6016 ndeclaration->base.symbol);
6018 if (warning.traditional && !type->function.unspecified_parameters) {
6019 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6020 ndeclaration->base.symbol);
6022 if (warning.old_style_definition && type->function.unspecified_parameters) {
6023 warningf(HERE, "old-style function definition '%Y'",
6024 ndeclaration->base.symbol);
6027 /* § 6.7.5.3 (14) a function definition with () means no
6028 * parameters (and not unspecified parameters) */
6029 if (type->function.unspecified_parameters
6030 && type->function.parameters == NULL
6031 && !type->function.kr_style_parameters) {
6032 type_t *duplicate = duplicate_type(type);
6033 duplicate->function.unspecified_parameters = false;
6035 type = typehash_insert(duplicate);
6036 if (type != duplicate) {
6037 obstack_free(type_obst, duplicate);
6039 ndeclaration->declaration.type = type;
6042 entity_t *const entity = record_entity(ndeclaration, true);
6043 assert(entity->kind == ENTITY_FUNCTION);
6044 assert(ndeclaration->kind == ENTITY_FUNCTION);
6046 function_t *function = &entity->function;
6047 if (ndeclaration != entity) {
6048 function->parameters = ndeclaration->function.parameters;
6050 assert(is_declaration(entity));
6051 type = skip_typeref(entity->declaration.type);
6053 /* push function parameters and switch scope */
6054 size_t const top = environment_top();
6055 scope_push(&function->parameters);
6057 entity_t *parameter = function->parameters.entities;
6058 for (; parameter != NULL; parameter = parameter->base.next) {
6059 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6060 parameter->base.parent_scope = current_scope;
6062 assert(parameter->base.parent_scope == NULL
6063 || parameter->base.parent_scope == current_scope);
6064 parameter->base.parent_scope = current_scope;
6065 if (parameter->base.symbol == NULL) {
6066 errorf(¶meter->base.source_position, "parameter name omitted");
6069 environment_push(parameter);
6072 if (function->statement != NULL) {
6073 parser_error_multiple_definition(entity, HERE);
6076 /* parse function body */
6077 int label_stack_top = label_top();
6078 function_t *old_current_function = current_function;
6079 current_function = function;
6080 current_parent = NULL;
6083 goto_anchor = &goto_first;
6085 label_anchor = &label_first;
6087 statement_t *const body = parse_compound_statement(false);
6088 function->statement = body;
6091 check_declarations();
6092 if (warning.return_type ||
6093 warning.unreachable_code ||
6094 (warning.missing_noreturn
6095 && !(function->base.modifiers & DM_NORETURN))) {
6096 noreturn_candidate = true;
6097 check_reachable(body);
6098 if (warning.unreachable_code)
6099 walk_statements(body, check_unreachable, NULL);
6100 if (warning.missing_noreturn &&
6101 noreturn_candidate &&
6102 !(function->base.modifiers & DM_NORETURN)) {
6103 warningf(&body->base.source_position,
6104 "function '%#T' is candidate for attribute 'noreturn'",
6105 type, entity->base.symbol);
6109 assert(current_parent == NULL);
6110 assert(current_function == function);
6111 current_function = old_current_function;
6112 label_pop_to(label_stack_top);
6115 assert(current_scope == &function->parameters);
6117 environment_pop_to(top);
6120 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6121 source_position_t *source_position,
6122 const symbol_t *symbol)
6124 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6126 type->bitfield.base_type = base_type;
6127 type->bitfield.size_expression = size;
6130 type_t *skipped_type = skip_typeref(base_type);
6131 if (!is_type_integer(skipped_type)) {
6132 errorf(HERE, "bitfield base type '%T' is not an integer type",
6136 bit_size = skipped_type->base.size * 8;
6139 if (is_constant_expression(size)) {
6140 long v = fold_constant(size);
6143 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6144 } else if (v == 0) {
6145 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6146 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6147 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6149 type->bitfield.bit_size = v;
6156 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6158 entity_t *iter = compound->members.entities;
6159 for (; iter != NULL; iter = iter->base.next) {
6160 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6163 if (iter->base.symbol == symbol) {
6165 } else if (iter->base.symbol == NULL) {
6166 type_t *type = skip_typeref(iter->declaration.type);
6167 if (is_type_compound(type)) {
6169 = find_compound_entry(type->compound.compound, symbol);
6180 static void parse_compound_declarators(compound_t *compound,
6181 const declaration_specifiers_t *specifiers)
6186 if (token.type == ':') {
6187 source_position_t source_position = *HERE;
6190 type_t *base_type = specifiers->type;
6191 expression_t *size = parse_constant_expression();
6193 type_t *type = make_bitfield_type(base_type, size,
6194 &source_position, sym_anonymous);
6196 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6197 entity->base.namespc = NAMESPACE_NORMAL;
6198 entity->base.source_position = source_position;
6199 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6200 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6201 entity->declaration.modifiers = specifiers->modifiers;
6202 entity->declaration.type = type;
6204 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6205 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6207 if (token.type == ':') {
6208 source_position_t source_position = *HERE;
6210 expression_t *size = parse_constant_expression();
6212 type_t *type = entity->declaration.type;
6213 type_t *bitfield_type = make_bitfield_type(type, size,
6214 &source_position, entity->base.symbol);
6215 entity->declaration.type = bitfield_type;
6219 /* make sure we don't define a symbol multiple times */
6220 symbol_t *symbol = entity->base.symbol;
6221 if (symbol != NULL) {
6222 entity_t *prev = find_compound_entry(compound, symbol);
6225 errorf(&entity->base.source_position,
6226 "multiple declarations of symbol '%Y' (declared %P)",
6227 symbol, &prev->base.source_position);
6231 append_entity(&compound->members, entity);
6233 type_t *orig_type = entity->declaration.type;
6234 type_t *type = skip_typeref(orig_type);
6235 if (is_type_function(type)) {
6236 errorf(&entity->base.source_position,
6237 "compound member '%Y' must not have function type '%T'",
6238 entity->base.symbol, orig_type);
6239 } else if (is_type_incomplete(type)) {
6240 /* §6.7.2.1:16 flexible array member */
6241 if (is_type_array(type) &&
6242 token.type == ';' &&
6243 look_ahead(1)->type == '}') {
6244 compound->has_flexible_member = true;
6246 errorf(&entity->base.source_position,
6247 "compound member '%Y' has incomplete type '%T'",
6248 entity->base.symbol, orig_type);
6252 if (token.type != ',')
6259 anonymous_entity = NULL;
6262 static void parse_compound_type_entries(compound_t *compound)
6265 add_anchor_token('}');
6267 while (token.type != '}') {
6268 if (token.type == T_EOF) {
6269 errorf(HERE, "EOF while parsing struct");
6272 declaration_specifiers_t specifiers;
6273 memset(&specifiers, 0, sizeof(specifiers));
6274 parse_declaration_specifiers(&specifiers);
6276 parse_compound_declarators(compound, &specifiers);
6278 rem_anchor_token('}');
6282 compound->complete = true;
6285 static type_t *parse_typename(void)
6287 declaration_specifiers_t specifiers;
6288 memset(&specifiers, 0, sizeof(specifiers));
6289 parse_declaration_specifiers(&specifiers);
6290 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6291 /* TODO: improve error message, user does probably not know what a
6292 * storage class is...
6294 errorf(HERE, "typename may not have a storage class");
6297 type_t *result = parse_abstract_declarator(specifiers.type);
6305 typedef expression_t* (*parse_expression_function)(void);
6306 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6308 typedef struct expression_parser_function_t expression_parser_function_t;
6309 struct expression_parser_function_t {
6310 parse_expression_function parser;
6311 unsigned infix_precedence;
6312 parse_expression_infix_function infix_parser;
6315 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6318 * Prints an error message if an expression was expected but not read
6320 static expression_t *expected_expression_error(void)
6322 /* skip the error message if the error token was read */
6323 if (token.type != T_ERROR) {
6324 errorf(HERE, "expected expression, got token '%K'", &token);
6328 return create_invalid_expression();
6332 * Parse a string constant.
6334 static expression_t *parse_string_const(void)
6337 if (token.type == T_STRING_LITERAL) {
6338 string_t res = token.v.string;
6340 while (token.type == T_STRING_LITERAL) {
6341 res = concat_strings(&res, &token.v.string);
6344 if (token.type != T_WIDE_STRING_LITERAL) {
6345 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6346 /* note: that we use type_char_ptr here, which is already the
6347 * automatic converted type. revert_automatic_type_conversion
6348 * will construct the array type */
6349 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6350 cnst->string.value = res;
6354 wres = concat_string_wide_string(&res, &token.v.wide_string);
6356 wres = token.v.wide_string;
6361 switch (token.type) {
6362 case T_WIDE_STRING_LITERAL:
6363 wres = concat_wide_strings(&wres, &token.v.wide_string);
6366 case T_STRING_LITERAL:
6367 wres = concat_wide_string_string(&wres, &token.v.string);
6371 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6372 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6373 cnst->wide_string.value = wres;
6382 * Parse a boolean constant.
6384 static expression_t *parse_bool_const(bool value)
6386 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6387 cnst->base.type = type_bool;
6388 cnst->conste.v.int_value = value;
6396 * Parse an integer constant.
6398 static expression_t *parse_int_const(void)
6400 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6401 cnst->base.type = token.datatype;
6402 cnst->conste.v.int_value = token.v.intvalue;
6410 * Parse a character constant.
6412 static expression_t *parse_character_constant(void)
6414 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6415 cnst->base.type = token.datatype;
6416 cnst->conste.v.character = token.v.string;
6418 if (cnst->conste.v.character.size != 1) {
6420 errorf(HERE, "more than 1 character in character constant");
6421 } else if (warning.multichar) {
6422 warningf(HERE, "multi-character character constant");
6431 * Parse a wide character constant.
6433 static expression_t *parse_wide_character_constant(void)
6435 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6436 cnst->base.type = token.datatype;
6437 cnst->conste.v.wide_character = token.v.wide_string;
6439 if (cnst->conste.v.wide_character.size != 1) {
6441 errorf(HERE, "more than 1 character in character constant");
6442 } else if (warning.multichar) {
6443 warningf(HERE, "multi-character character constant");
6452 * Parse a float constant.
6454 static expression_t *parse_float_const(void)
6456 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6457 cnst->base.type = token.datatype;
6458 cnst->conste.v.float_value = token.v.floatvalue;
6465 static entity_t *create_implicit_function(symbol_t *symbol,
6466 const source_position_t *source_position)
6468 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6469 ntype->function.return_type = type_int;
6470 ntype->function.unspecified_parameters = true;
6472 type_t *type = typehash_insert(ntype);
6473 if (type != ntype) {
6477 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6478 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6479 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6480 entity->declaration.type = type;
6481 entity->declaration.implicit = true;
6482 entity->base.symbol = symbol;
6483 entity->base.source_position = *source_position;
6485 bool strict_prototypes_old = warning.strict_prototypes;
6486 warning.strict_prototypes = false;
6487 record_entity(entity, false);
6488 warning.strict_prototypes = strict_prototypes_old;
6494 * Creates a return_type (func)(argument_type) function type if not
6497 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6498 type_t *argument_type2)
6500 function_parameter_t *parameter2
6501 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6502 memset(parameter2, 0, sizeof(parameter2[0]));
6503 parameter2->type = argument_type2;
6505 function_parameter_t *parameter1
6506 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6507 memset(parameter1, 0, sizeof(parameter1[0]));
6508 parameter1->type = argument_type1;
6509 parameter1->next = parameter2;
6511 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6512 type->function.return_type = return_type;
6513 type->function.parameters = parameter1;
6515 type_t *result = typehash_insert(type);
6516 if (result != type) {
6524 * Creates a return_type (func)(argument_type) function type if not
6527 * @param return_type the return type
6528 * @param argument_type the argument type
6530 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6532 function_parameter_t *parameter
6533 = obstack_alloc(type_obst, sizeof(parameter[0]));
6534 memset(parameter, 0, sizeof(parameter[0]));
6535 parameter->type = argument_type;
6537 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6538 type->function.return_type = return_type;
6539 type->function.parameters = parameter;
6541 type_t *result = typehash_insert(type);
6542 if (result != type) {
6549 static type_t *make_function_0_type(type_t *return_type)
6551 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6552 type->function.return_type = return_type;
6553 type->function.parameters = NULL;
6555 type_t *result = typehash_insert(type);
6556 if (result != type) {
6564 * Creates a function type for some function like builtins.
6566 * @param symbol the symbol describing the builtin
6568 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6570 switch (symbol->ID) {
6571 case T___builtin_alloca:
6572 return make_function_1_type(type_void_ptr, type_size_t);
6573 case T___builtin_huge_val:
6574 return make_function_0_type(type_double);
6575 case T___builtin_inf:
6576 return make_function_0_type(type_double);
6577 case T___builtin_inff:
6578 return make_function_0_type(type_float);
6579 case T___builtin_infl:
6580 return make_function_0_type(type_long_double);
6581 case T___builtin_nan:
6582 return make_function_1_type(type_double, type_char_ptr);
6583 case T___builtin_nanf:
6584 return make_function_1_type(type_float, type_char_ptr);
6585 case T___builtin_nanl:
6586 return make_function_1_type(type_long_double, type_char_ptr);
6587 case T___builtin_va_end:
6588 return make_function_1_type(type_void, type_valist);
6589 case T___builtin_expect:
6590 return make_function_2_type(type_long, type_long, type_long);
6592 internal_errorf(HERE, "not implemented builtin symbol found");
6597 * Performs automatic type cast as described in § 6.3.2.1.
6599 * @param orig_type the original type
6601 static type_t *automatic_type_conversion(type_t *orig_type)
6603 type_t *type = skip_typeref(orig_type);
6604 if (is_type_array(type)) {
6605 array_type_t *array_type = &type->array;
6606 type_t *element_type = array_type->element_type;
6607 unsigned qualifiers = array_type->base.qualifiers;
6609 return make_pointer_type(element_type, qualifiers);
6612 if (is_type_function(type)) {
6613 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6620 * reverts the automatic casts of array to pointer types and function
6621 * to function-pointer types as defined § 6.3.2.1
6623 type_t *revert_automatic_type_conversion(const expression_t *expression)
6625 switch (expression->kind) {
6626 case EXPR_REFERENCE: {
6627 entity_t *entity = expression->reference.entity;
6628 if (is_declaration(entity)) {
6629 return entity->declaration.type;
6630 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6631 return entity->enum_value.enum_type;
6633 panic("no declaration or enum in reference");
6638 entity_t *entity = expression->select.compound_entry;
6639 assert(is_declaration(entity));
6640 type_t *type = entity->declaration.type;
6641 return get_qualified_type(type,
6642 expression->base.type->base.qualifiers);
6645 case EXPR_UNARY_DEREFERENCE: {
6646 const expression_t *const value = expression->unary.value;
6647 type_t *const type = skip_typeref(value->base.type);
6648 assert(is_type_pointer(type));
6649 return type->pointer.points_to;
6652 case EXPR_BUILTIN_SYMBOL:
6653 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6655 case EXPR_ARRAY_ACCESS: {
6656 const expression_t *array_ref = expression->array_access.array_ref;
6657 type_t *type_left = skip_typeref(array_ref->base.type);
6658 if (!is_type_valid(type_left))
6660 assert(is_type_pointer(type_left));
6661 return type_left->pointer.points_to;
6664 case EXPR_STRING_LITERAL: {
6665 size_t size = expression->string.value.size;
6666 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6669 case EXPR_WIDE_STRING_LITERAL: {
6670 size_t size = expression->wide_string.value.size;
6671 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6674 case EXPR_COMPOUND_LITERAL:
6675 return expression->compound_literal.type;
6680 return expression->base.type;
6683 static expression_t *parse_reference(void)
6685 symbol_t *const symbol = token.v.symbol;
6687 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6689 if (entity == NULL) {
6690 if (!strict_mode && look_ahead(1)->type == '(') {
6691 /* an implicitly declared function */
6692 if (warning.implicit_function_declaration) {
6693 warningf(HERE, "implicit declaration of function '%Y'",
6697 entity = create_implicit_function(symbol, HERE);
6699 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6700 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6706 if (is_declaration(entity)) {
6707 orig_type = entity->declaration.type;
6708 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6709 orig_type = entity->enum_value.enum_type;
6710 } else if (entity->kind == ENTITY_TYPEDEF) {
6711 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6714 return create_invalid_expression();
6716 panic("expected declaration or enum value in reference");
6719 /* we always do the auto-type conversions; the & and sizeof parser contains
6720 * code to revert this! */
6721 type_t *type = automatic_type_conversion(orig_type);
6723 expression_kind_t kind = EXPR_REFERENCE;
6724 if (entity->kind == ENTITY_ENUM_VALUE)
6725 kind = EXPR_REFERENCE_ENUM_VALUE;
6727 expression_t *expression = allocate_expression_zero(kind);
6728 expression->reference.entity = entity;
6729 expression->base.type = type;
6731 /* this declaration is used */
6732 if (is_declaration(entity)) {
6733 entity->declaration.used = true;
6736 if (entity->base.parent_scope != file_scope
6737 && entity->base.parent_scope->depth < current_function->parameters.depth
6738 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6739 if (entity->kind == ENTITY_VARIABLE) {
6740 /* access of a variable from an outer function */
6741 entity->variable.address_taken = true;
6743 current_function->need_closure = true;
6746 /* check for deprecated functions */
6747 if (warning.deprecated_declarations
6748 && is_declaration(entity)
6749 && entity->declaration.modifiers & DM_DEPRECATED) {
6750 declaration_t *declaration = &entity->declaration;
6752 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6753 "function" : "variable";
6755 if (declaration->deprecated_string != NULL) {
6756 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6757 prefix, entity->base.symbol, &entity->base.source_position,
6758 declaration->deprecated_string);
6760 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6761 entity->base.symbol, &entity->base.source_position);
6765 if (warning.init_self && entity == current_init_decl && !in_type_prop
6766 && entity->kind == ENTITY_VARIABLE) {
6767 current_init_decl = NULL;
6768 warningf(HERE, "variable '%#T' is initialized by itself",
6769 entity->declaration.type, entity->base.symbol);
6776 static bool semantic_cast(expression_t *cast)
6778 expression_t *expression = cast->unary.value;
6779 type_t *orig_dest_type = cast->base.type;
6780 type_t *orig_type_right = expression->base.type;
6781 type_t const *dst_type = skip_typeref(orig_dest_type);
6782 type_t const *src_type = skip_typeref(orig_type_right);
6783 source_position_t const *pos = &cast->base.source_position;
6785 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6786 if (dst_type == type_void)
6789 /* only integer and pointer can be casted to pointer */
6790 if (is_type_pointer(dst_type) &&
6791 !is_type_pointer(src_type) &&
6792 !is_type_integer(src_type) &&
6793 is_type_valid(src_type)) {
6794 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6798 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6799 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6803 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6804 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6808 if (warning.cast_qual &&
6809 is_type_pointer(src_type) &&
6810 is_type_pointer(dst_type)) {
6811 type_t *src = skip_typeref(src_type->pointer.points_to);
6812 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6813 unsigned missing_qualifiers =
6814 src->base.qualifiers & ~dst->base.qualifiers;
6815 if (missing_qualifiers != 0) {
6817 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6818 missing_qualifiers, orig_type_right);
6824 static expression_t *parse_compound_literal(type_t *type)
6826 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6828 parse_initializer_env_t env;
6831 env.must_be_constant = false;
6832 initializer_t *initializer = parse_initializer(&env);
6835 expression->compound_literal.initializer = initializer;
6836 expression->compound_literal.type = type;
6837 expression->base.type = automatic_type_conversion(type);
6843 * Parse a cast expression.
6845 static expression_t *parse_cast(void)
6847 add_anchor_token(')');
6849 source_position_t source_position = token.source_position;
6851 type_t *type = parse_typename();
6853 rem_anchor_token(')');
6856 if (token.type == '{') {
6857 return parse_compound_literal(type);
6860 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6861 cast->base.source_position = source_position;
6863 expression_t *value = parse_sub_expression(PREC_CAST);
6864 cast->base.type = type;
6865 cast->unary.value = value;
6867 if (! semantic_cast(cast)) {
6868 /* TODO: record the error in the AST. else it is impossible to detect it */
6873 return create_invalid_expression();
6877 * Parse a statement expression.
6879 static expression_t *parse_statement_expression(void)
6881 add_anchor_token(')');
6883 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6885 statement_t *statement = parse_compound_statement(true);
6886 expression->statement.statement = statement;
6888 /* find last statement and use its type */
6889 type_t *type = type_void;
6890 const statement_t *stmt = statement->compound.statements;
6892 while (stmt->base.next != NULL)
6893 stmt = stmt->base.next;
6895 if (stmt->kind == STATEMENT_EXPRESSION) {
6896 type = stmt->expression.expression->base.type;
6898 } else if (warning.other) {
6899 warningf(&expression->base.source_position, "empty statement expression ({})");
6901 expression->base.type = type;
6903 rem_anchor_token(')');
6911 * Parse a parenthesized expression.
6913 static expression_t *parse_parenthesized_expression(void)
6917 switch (token.type) {
6919 /* gcc extension: a statement expression */
6920 return parse_statement_expression();
6924 return parse_cast();
6926 if (is_typedef_symbol(token.v.symbol)) {
6927 return parse_cast();
6931 add_anchor_token(')');
6932 expression_t *result = parse_expression();
6933 rem_anchor_token(')');
6940 static expression_t *parse_function_keyword(void)
6944 if (current_function == NULL) {
6945 errorf(HERE, "'__func__' used outside of a function");
6948 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6949 expression->base.type = type_char_ptr;
6950 expression->funcname.kind = FUNCNAME_FUNCTION;
6957 static expression_t *parse_pretty_function_keyword(void)
6959 if (current_function == NULL) {
6960 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6963 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6964 expression->base.type = type_char_ptr;
6965 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6967 eat(T___PRETTY_FUNCTION__);
6972 static expression_t *parse_funcsig_keyword(void)
6974 if (current_function == NULL) {
6975 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6978 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6979 expression->base.type = type_char_ptr;
6980 expression->funcname.kind = FUNCNAME_FUNCSIG;
6987 static expression_t *parse_funcdname_keyword(void)
6989 if (current_function == NULL) {
6990 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6993 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6994 expression->base.type = type_char_ptr;
6995 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6997 eat(T___FUNCDNAME__);
7002 static designator_t *parse_designator(void)
7004 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7005 result->source_position = *HERE;
7007 if (token.type != T_IDENTIFIER) {
7008 parse_error_expected("while parsing member designator",
7009 T_IDENTIFIER, NULL);
7012 result->symbol = token.v.symbol;
7015 designator_t *last_designator = result;
7017 if (token.type == '.') {
7019 if (token.type != T_IDENTIFIER) {
7020 parse_error_expected("while parsing member designator",
7021 T_IDENTIFIER, NULL);
7024 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7025 designator->source_position = *HERE;
7026 designator->symbol = token.v.symbol;
7029 last_designator->next = designator;
7030 last_designator = designator;
7033 if (token.type == '[') {
7035 add_anchor_token(']');
7036 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7037 designator->source_position = *HERE;
7038 designator->array_index = parse_expression();
7039 rem_anchor_token(']');
7041 if (designator->array_index == NULL) {
7045 last_designator->next = designator;
7046 last_designator = designator;
7058 * Parse the __builtin_offsetof() expression.
7060 static expression_t *parse_offsetof(void)
7062 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7063 expression->base.type = type_size_t;
7065 eat(T___builtin_offsetof);
7068 add_anchor_token(',');
7069 type_t *type = parse_typename();
7070 rem_anchor_token(',');
7072 add_anchor_token(')');
7073 designator_t *designator = parse_designator();
7074 rem_anchor_token(')');
7077 expression->offsetofe.type = type;
7078 expression->offsetofe.designator = designator;
7081 memset(&path, 0, sizeof(path));
7082 path.top_type = type;
7083 path.path = NEW_ARR_F(type_path_entry_t, 0);
7085 descend_into_subtype(&path);
7087 if (!walk_designator(&path, designator, true)) {
7088 return create_invalid_expression();
7091 DEL_ARR_F(path.path);
7095 return create_invalid_expression();
7099 * Parses a _builtin_va_start() expression.
7101 static expression_t *parse_va_start(void)
7103 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7105 eat(T___builtin_va_start);
7108 add_anchor_token(',');
7109 expression->va_starte.ap = parse_assignment_expression();
7110 rem_anchor_token(',');
7112 expression_t *const expr = parse_assignment_expression();
7113 if (expr->kind == EXPR_REFERENCE) {
7114 entity_t *const entity = expr->reference.entity;
7115 if (entity->base.parent_scope != ¤t_function->parameters
7116 || entity->base.next != NULL
7117 || entity->kind != ENTITY_VARIABLE) {
7118 errorf(&expr->base.source_position,
7119 "second argument of 'va_start' must be last parameter of the current function");
7121 expression->va_starte.parameter = &entity->variable;
7128 return create_invalid_expression();
7132 * Parses a _builtin_va_arg() expression.
7134 static expression_t *parse_va_arg(void)
7136 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7138 eat(T___builtin_va_arg);
7141 expression->va_arge.ap = parse_assignment_expression();
7143 expression->base.type = parse_typename();
7148 return create_invalid_expression();
7151 static expression_t *parse_builtin_symbol(void)
7153 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7155 symbol_t *symbol = token.v.symbol;
7157 expression->builtin_symbol.symbol = symbol;
7160 type_t *type = get_builtin_symbol_type(symbol);
7161 type = automatic_type_conversion(type);
7163 expression->base.type = type;
7168 * Parses a __builtin_constant() expression.
7170 static expression_t *parse_builtin_constant(void)
7172 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7174 eat(T___builtin_constant_p);
7177 add_anchor_token(')');
7178 expression->builtin_constant.value = parse_assignment_expression();
7179 rem_anchor_token(')');
7181 expression->base.type = type_int;
7185 return create_invalid_expression();
7189 * Parses a __builtin_prefetch() expression.
7191 static expression_t *parse_builtin_prefetch(void)
7193 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7195 eat(T___builtin_prefetch);
7198 add_anchor_token(')');
7199 expression->builtin_prefetch.adr = parse_assignment_expression();
7200 if (token.type == ',') {
7202 expression->builtin_prefetch.rw = parse_assignment_expression();
7204 if (token.type == ',') {
7206 expression->builtin_prefetch.locality = parse_assignment_expression();
7208 rem_anchor_token(')');
7210 expression->base.type = type_void;
7214 return create_invalid_expression();
7218 * Parses a __builtin_is_*() compare expression.
7220 static expression_t *parse_compare_builtin(void)
7222 expression_t *expression;
7224 switch (token.type) {
7225 case T___builtin_isgreater:
7226 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7228 case T___builtin_isgreaterequal:
7229 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7231 case T___builtin_isless:
7232 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7234 case T___builtin_islessequal:
7235 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7237 case T___builtin_islessgreater:
7238 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7240 case T___builtin_isunordered:
7241 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7244 internal_errorf(HERE, "invalid compare builtin found");
7246 expression->base.source_position = *HERE;
7250 expression->binary.left = parse_assignment_expression();
7252 expression->binary.right = parse_assignment_expression();
7255 type_t *const orig_type_left = expression->binary.left->base.type;
7256 type_t *const orig_type_right = expression->binary.right->base.type;
7258 type_t *const type_left = skip_typeref(orig_type_left);
7259 type_t *const type_right = skip_typeref(orig_type_right);
7260 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7261 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7262 type_error_incompatible("invalid operands in comparison",
7263 &expression->base.source_position, orig_type_left, orig_type_right);
7266 semantic_comparison(&expression->binary);
7271 return create_invalid_expression();
7276 * Parses a __builtin_expect() expression.
7278 static expression_t *parse_builtin_expect(void)
7280 expression_t *expression
7281 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7283 eat(T___builtin_expect);
7286 expression->binary.left = parse_assignment_expression();
7288 expression->binary.right = parse_constant_expression();
7291 expression->base.type = expression->binary.left->base.type;
7295 return create_invalid_expression();
7300 * Parses a MS assume() expression.
7302 static expression_t *parse_assume(void)
7304 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7309 add_anchor_token(')');
7310 expression->unary.value = parse_assignment_expression();
7311 rem_anchor_token(')');
7314 expression->base.type = type_void;
7317 return create_invalid_expression();
7321 * Return the declaration for a given label symbol or create a new one.
7323 * @param symbol the symbol of the label
7325 static label_t *get_label(symbol_t *symbol)
7328 assert(current_function != NULL);
7330 label = get_entity(symbol, NAMESPACE_LABEL);
7331 /* if we found a local label, we already created the declaration */
7332 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7333 if (label->base.parent_scope != current_scope) {
7334 assert(label->base.parent_scope->depth < current_scope->depth);
7335 current_function->goto_to_outer = true;
7337 return &label->label;
7340 label = get_entity(symbol, NAMESPACE_LABEL);
7341 /* if we found a label in the same function, then we already created the
7344 && label->base.parent_scope == ¤t_function->parameters) {
7345 return &label->label;
7348 /* otherwise we need to create a new one */
7349 label = allocate_entity_zero(ENTITY_LABEL);
7350 label->base.namespc = NAMESPACE_LABEL;
7351 label->base.symbol = symbol;
7355 return &label->label;
7359 * Parses a GNU && label address expression.
7361 static expression_t *parse_label_address(void)
7363 source_position_t source_position = token.source_position;
7365 if (token.type != T_IDENTIFIER) {
7366 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7369 symbol_t *symbol = token.v.symbol;
7372 label_t *label = get_label(symbol);
7374 label->address_taken = true;
7376 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7377 expression->base.source_position = source_position;
7379 /* label address is threaten as a void pointer */
7380 expression->base.type = type_void_ptr;
7381 expression->label_address.label = label;
7384 return create_invalid_expression();
7388 * Parse a microsoft __noop expression.
7390 static expression_t *parse_noop_expression(void)
7392 /* the result is a (int)0 */
7393 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7394 cnst->base.type = type_int;
7395 cnst->conste.v.int_value = 0;
7396 cnst->conste.is_ms_noop = true;
7400 if (token.type == '(') {
7401 /* parse arguments */
7403 add_anchor_token(')');
7404 add_anchor_token(',');
7406 if (token.type != ')') {
7408 (void)parse_assignment_expression();
7409 if (token.type != ',')
7415 rem_anchor_token(',');
7416 rem_anchor_token(')');
7424 * Parses a primary expression.
7426 static expression_t *parse_primary_expression(void)
7428 switch (token.type) {
7429 case T_false: return parse_bool_const(false);
7430 case T_true: return parse_bool_const(true);
7431 case T_INTEGER: return parse_int_const();
7432 case T_CHARACTER_CONSTANT: return parse_character_constant();
7433 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7434 case T_FLOATINGPOINT: return parse_float_const();
7435 case T_STRING_LITERAL:
7436 case T_WIDE_STRING_LITERAL: return parse_string_const();
7437 case T_IDENTIFIER: return parse_reference();
7438 case T___FUNCTION__:
7439 case T___func__: return parse_function_keyword();
7440 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7441 case T___FUNCSIG__: return parse_funcsig_keyword();
7442 case T___FUNCDNAME__: return parse_funcdname_keyword();
7443 case T___builtin_offsetof: return parse_offsetof();
7444 case T___builtin_va_start: return parse_va_start();
7445 case T___builtin_va_arg: return parse_va_arg();
7446 case T___builtin_expect:
7447 case T___builtin_alloca:
7448 case T___builtin_inf:
7449 case T___builtin_inff:
7450 case T___builtin_infl:
7451 case T___builtin_nan:
7452 case T___builtin_nanf:
7453 case T___builtin_nanl:
7454 case T___builtin_huge_val:
7455 case T___builtin_va_end: return parse_builtin_symbol();
7456 case T___builtin_isgreater:
7457 case T___builtin_isgreaterequal:
7458 case T___builtin_isless:
7459 case T___builtin_islessequal:
7460 case T___builtin_islessgreater:
7461 case T___builtin_isunordered: return parse_compare_builtin();
7462 case T___builtin_constant_p: return parse_builtin_constant();
7463 case T___builtin_prefetch: return parse_builtin_prefetch();
7464 case T__assume: return parse_assume();
7467 return parse_label_address();
7470 case '(': return parse_parenthesized_expression();
7471 case T___noop: return parse_noop_expression();
7474 errorf(HERE, "unexpected token %K, expected an expression", &token);
7475 return create_invalid_expression();
7479 * Check if the expression has the character type and issue a warning then.
7481 static void check_for_char_index_type(const expression_t *expression)
7483 type_t *const type = expression->base.type;
7484 const type_t *const base_type = skip_typeref(type);
7486 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7487 warning.char_subscripts) {
7488 warningf(&expression->base.source_position,
7489 "array subscript has type '%T'", type);
7493 static expression_t *parse_array_expression(expression_t *left)
7495 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7498 add_anchor_token(']');
7500 expression_t *inside = parse_expression();
7502 type_t *const orig_type_left = left->base.type;
7503 type_t *const orig_type_inside = inside->base.type;
7505 type_t *const type_left = skip_typeref(orig_type_left);
7506 type_t *const type_inside = skip_typeref(orig_type_inside);
7508 type_t *return_type;
7509 array_access_expression_t *array_access = &expression->array_access;
7510 if (is_type_pointer(type_left)) {
7511 return_type = type_left->pointer.points_to;
7512 array_access->array_ref = left;
7513 array_access->index = inside;
7514 check_for_char_index_type(inside);
7515 } else if (is_type_pointer(type_inside)) {
7516 return_type = type_inside->pointer.points_to;
7517 array_access->array_ref = inside;
7518 array_access->index = left;
7519 array_access->flipped = true;
7520 check_for_char_index_type(left);
7522 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7524 "array access on object with non-pointer types '%T', '%T'",
7525 orig_type_left, orig_type_inside);
7527 return_type = type_error_type;
7528 array_access->array_ref = left;
7529 array_access->index = inside;
7532 expression->base.type = automatic_type_conversion(return_type);
7534 rem_anchor_token(']');
7540 static expression_t *parse_typeprop(expression_kind_t const kind)
7542 expression_t *tp_expression = allocate_expression_zero(kind);
7543 tp_expression->base.type = type_size_t;
7545 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7547 /* we only refer to a type property, mark this case */
7548 bool old = in_type_prop;
7549 in_type_prop = true;
7552 expression_t *expression;
7553 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7555 add_anchor_token(')');
7556 orig_type = parse_typename();
7557 rem_anchor_token(')');
7560 if (token.type == '{') {
7561 /* It was not sizeof(type) after all. It is sizeof of an expression
7562 * starting with a compound literal */
7563 expression = parse_compound_literal(orig_type);
7564 goto typeprop_expression;
7567 expression = parse_sub_expression(PREC_UNARY);
7569 typeprop_expression:
7570 tp_expression->typeprop.tp_expression = expression;
7572 orig_type = revert_automatic_type_conversion(expression);
7573 expression->base.type = orig_type;
7576 tp_expression->typeprop.type = orig_type;
7577 type_t const* const type = skip_typeref(orig_type);
7578 char const* const wrong_type =
7579 is_type_incomplete(type) ? "incomplete" :
7580 type->kind == TYPE_FUNCTION ? "function designator" :
7581 type->kind == TYPE_BITFIELD ? "bitfield" :
7583 if (wrong_type != NULL) {
7584 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7585 errorf(&tp_expression->base.source_position,
7586 "operand of %s expression must not be of %s type '%T'",
7587 what, wrong_type, orig_type);
7592 return tp_expression;
7595 static expression_t *parse_sizeof(void)
7597 return parse_typeprop(EXPR_SIZEOF);
7600 static expression_t *parse_alignof(void)
7602 return parse_typeprop(EXPR_ALIGNOF);
7605 static expression_t *parse_select_expression(expression_t *compound)
7607 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7608 select->select.compound = compound;
7610 assert(token.type == '.' || token.type == T_MINUSGREATER);
7611 bool is_pointer = (token.type == T_MINUSGREATER);
7614 if (token.type != T_IDENTIFIER) {
7615 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7618 symbol_t *symbol = token.v.symbol;
7621 type_t *const orig_type = compound->base.type;
7622 type_t *const type = skip_typeref(orig_type);
7625 bool saw_error = false;
7626 if (is_type_pointer(type)) {
7629 "request for member '%Y' in something not a struct or union, but '%T'",
7633 type_left = skip_typeref(type->pointer.points_to);
7635 if (is_pointer && is_type_valid(type)) {
7636 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7643 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7644 type_left->kind == TYPE_COMPOUND_UNION) {
7645 compound_t *compound = type_left->compound.compound;
7647 if (!compound->complete) {
7648 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7650 goto create_error_entry;
7653 entry = find_compound_entry(compound, symbol);
7654 if (entry == NULL) {
7655 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7656 goto create_error_entry;
7659 if (is_type_valid(type_left) && !saw_error) {
7661 "request for member '%Y' in something not a struct or union, but '%T'",
7665 return create_invalid_expression();
7668 assert(is_declaration(entry));
7669 select->select.compound_entry = entry;
7671 type_t *entry_type = entry->declaration.type;
7673 = get_qualified_type(entry_type, type_left->base.qualifiers);
7675 /* we always do the auto-type conversions; the & and sizeof parser contains
7676 * code to revert this! */
7677 select->base.type = automatic_type_conversion(res_type);
7679 type_t *skipped = skip_typeref(res_type);
7680 if (skipped->kind == TYPE_BITFIELD) {
7681 select->base.type = skipped->bitfield.base_type;
7687 static void check_call_argument(const function_parameter_t *parameter,
7688 call_argument_t *argument, unsigned pos)
7690 type_t *expected_type = parameter->type;
7691 type_t *expected_type_skip = skip_typeref(expected_type);
7692 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7693 expression_t *arg_expr = argument->expression;
7694 type_t *arg_type = skip_typeref(arg_expr->base.type);
7696 /* handle transparent union gnu extension */
7697 if (is_type_union(expected_type_skip)
7698 && (expected_type_skip->base.modifiers
7699 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7700 compound_t *union_decl = expected_type_skip->compound.compound;
7701 type_t *best_type = NULL;
7702 entity_t *entry = union_decl->members.entities;
7703 for ( ; entry != NULL; entry = entry->base.next) {
7704 assert(is_declaration(entry));
7705 type_t *decl_type = entry->declaration.type;
7706 error = semantic_assign(decl_type, arg_expr);
7707 if (error == ASSIGN_ERROR_INCOMPATIBLE
7708 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7711 if (error == ASSIGN_SUCCESS) {
7712 best_type = decl_type;
7713 } else if (best_type == NULL) {
7714 best_type = decl_type;
7718 if (best_type != NULL) {
7719 expected_type = best_type;
7723 error = semantic_assign(expected_type, arg_expr);
7724 argument->expression = create_implicit_cast(argument->expression,
7727 if (error != ASSIGN_SUCCESS) {
7728 /* report exact scope in error messages (like "in argument 3") */
7730 snprintf(buf, sizeof(buf), "call argument %u", pos);
7731 report_assign_error(error, expected_type, arg_expr, buf,
7732 &arg_expr->base.source_position);
7733 } else if (warning.traditional || warning.conversion) {
7734 type_t *const promoted_type = get_default_promoted_type(arg_type);
7735 if (!types_compatible(expected_type_skip, promoted_type) &&
7736 !types_compatible(expected_type_skip, type_void_ptr) &&
7737 !types_compatible(type_void_ptr, promoted_type)) {
7738 /* Deliberately show the skipped types in this warning */
7739 warningf(&arg_expr->base.source_position,
7740 "passing call argument %u as '%T' rather than '%T' due to prototype",
7741 pos, expected_type_skip, promoted_type);
7747 * Parse a call expression, ie. expression '( ... )'.
7749 * @param expression the function address
7751 static expression_t *parse_call_expression(expression_t *expression)
7753 expression_t *result = allocate_expression_zero(EXPR_CALL);
7754 call_expression_t *call = &result->call;
7755 call->function = expression;
7757 type_t *const orig_type = expression->base.type;
7758 type_t *const type = skip_typeref(orig_type);
7760 function_type_t *function_type = NULL;
7761 if (is_type_pointer(type)) {
7762 type_t *const to_type = skip_typeref(type->pointer.points_to);
7764 if (is_type_function(to_type)) {
7765 function_type = &to_type->function;
7766 call->base.type = function_type->return_type;
7770 if (function_type == NULL && is_type_valid(type)) {
7771 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7774 /* parse arguments */
7776 add_anchor_token(')');
7777 add_anchor_token(',');
7779 if (token.type != ')') {
7780 call_argument_t *last_argument = NULL;
7783 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7785 argument->expression = parse_assignment_expression();
7786 if (last_argument == NULL) {
7787 call->arguments = argument;
7789 last_argument->next = argument;
7791 last_argument = argument;
7793 if (token.type != ',')
7798 rem_anchor_token(',');
7799 rem_anchor_token(')');
7802 if (function_type == NULL)
7805 function_parameter_t *parameter = function_type->parameters;
7806 call_argument_t *argument = call->arguments;
7807 if (!function_type->unspecified_parameters) {
7808 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7809 parameter = parameter->next, argument = argument->next) {
7810 check_call_argument(parameter, argument, ++pos);
7813 if (parameter != NULL) {
7814 errorf(HERE, "too few arguments to function '%E'", expression);
7815 } else if (argument != NULL && !function_type->variadic) {
7816 errorf(HERE, "too many arguments to function '%E'", expression);
7820 /* do default promotion */
7821 for (; argument != NULL; argument = argument->next) {
7822 type_t *type = argument->expression->base.type;
7824 type = get_default_promoted_type(type);
7826 argument->expression
7827 = create_implicit_cast(argument->expression, type);
7830 check_format(&result->call);
7832 if (warning.aggregate_return &&
7833 is_type_compound(skip_typeref(function_type->return_type))) {
7834 warningf(&result->base.source_position,
7835 "function call has aggregate value");
7842 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7844 static bool same_compound_type(const type_t *type1, const type_t *type2)
7847 is_type_compound(type1) &&
7848 type1->kind == type2->kind &&
7849 type1->compound.compound == type2->compound.compound;
7852 static expression_t const *get_reference_address(expression_t const *expr)
7854 bool regular_take_address = true;
7856 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7857 expr = expr->unary.value;
7859 regular_take_address = false;
7862 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7865 expr = expr->unary.value;
7868 if (expr->kind != EXPR_REFERENCE)
7871 /* special case for functions which are automatically converted to a
7872 * pointer to function without an extra TAKE_ADDRESS operation */
7873 if (!regular_take_address &&
7874 expr->reference.entity->kind != ENTITY_FUNCTION) {
7881 static void warn_reference_address_as_bool(expression_t const* expr)
7883 if (!warning.address)
7886 expr = get_reference_address(expr);
7888 warningf(&expr->base.source_position,
7889 "the address of '%Y' will always evaluate as 'true'",
7890 expr->reference.entity->base.symbol);
7895 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7897 * @param expression the conditional expression
7899 static expression_t *parse_conditional_expression(expression_t *expression)
7901 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7903 conditional_expression_t *conditional = &result->conditional;
7904 conditional->condition = expression;
7906 warn_reference_address_as_bool(expression);
7909 add_anchor_token(':');
7912 type_t *const condition_type_orig = expression->base.type;
7913 type_t *const condition_type = skip_typeref(condition_type_orig);
7914 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7915 type_error("expected a scalar type in conditional condition",
7916 &expression->base.source_position, condition_type_orig);
7919 expression_t *true_expression = expression;
7920 bool gnu_cond = false;
7921 if (GNU_MODE && token.type == ':') {
7924 true_expression = parse_expression();
7926 rem_anchor_token(':');
7928 expression_t *false_expression =
7929 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7931 type_t *const orig_true_type = true_expression->base.type;
7932 type_t *const orig_false_type = false_expression->base.type;
7933 type_t *const true_type = skip_typeref(orig_true_type);
7934 type_t *const false_type = skip_typeref(orig_false_type);
7937 type_t *result_type;
7938 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7939 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7940 /* ISO/IEC 14882:1998(E) §5.16:2 */
7941 if (true_expression->kind == EXPR_UNARY_THROW) {
7942 result_type = false_type;
7943 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7944 result_type = true_type;
7946 if (warning.other && (
7947 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7948 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7950 warningf(&conditional->base.source_position,
7951 "ISO C forbids conditional expression with only one void side");
7953 result_type = type_void;
7955 } else if (is_type_arithmetic(true_type)
7956 && is_type_arithmetic(false_type)) {
7957 result_type = semantic_arithmetic(true_type, false_type);
7959 true_expression = create_implicit_cast(true_expression, result_type);
7960 false_expression = create_implicit_cast(false_expression, result_type);
7962 conditional->true_expression = true_expression;
7963 conditional->false_expression = false_expression;
7964 conditional->base.type = result_type;
7965 } else if (same_compound_type(true_type, false_type)) {
7966 /* just take 1 of the 2 types */
7967 result_type = true_type;
7968 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7969 type_t *pointer_type;
7971 expression_t *other_expression;
7972 if (is_type_pointer(true_type) &&
7973 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7974 pointer_type = true_type;
7975 other_type = false_type;
7976 other_expression = false_expression;
7978 pointer_type = false_type;
7979 other_type = true_type;
7980 other_expression = true_expression;
7983 if (is_null_pointer_constant(other_expression)) {
7984 result_type = pointer_type;
7985 } else if (is_type_pointer(other_type)) {
7986 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7987 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7990 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7991 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7993 } else if (types_compatible(get_unqualified_type(to1),
7994 get_unqualified_type(to2))) {
7997 if (warning.other) {
7998 warningf(&conditional->base.source_position,
7999 "pointer types '%T' and '%T' in conditional expression are incompatible",
8000 true_type, false_type);
8005 type_t *const type =
8006 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8007 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8008 } else if (is_type_integer(other_type)) {
8009 if (warning.other) {
8010 warningf(&conditional->base.source_position,
8011 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8013 result_type = pointer_type;
8015 if (is_type_valid(other_type)) {
8016 type_error_incompatible("while parsing conditional",
8017 &expression->base.source_position, true_type, false_type);
8019 result_type = type_error_type;
8022 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8023 type_error_incompatible("while parsing conditional",
8024 &conditional->base.source_position, true_type,
8027 result_type = type_error_type;
8030 conditional->true_expression
8031 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8032 conditional->false_expression
8033 = create_implicit_cast(false_expression, result_type);
8034 conditional->base.type = result_type;
8037 return create_invalid_expression();
8041 * Parse an extension expression.
8043 static expression_t *parse_extension(void)
8045 eat(T___extension__);
8047 bool old_gcc_extension = in_gcc_extension;
8048 in_gcc_extension = true;
8049 expression_t *expression = parse_sub_expression(PREC_UNARY);
8050 in_gcc_extension = old_gcc_extension;
8055 * Parse a __builtin_classify_type() expression.
8057 static expression_t *parse_builtin_classify_type(void)
8059 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8060 result->base.type = type_int;
8062 eat(T___builtin_classify_type);
8065 add_anchor_token(')');
8066 expression_t *expression = parse_expression();
8067 rem_anchor_token(')');
8069 result->classify_type.type_expression = expression;
8073 return create_invalid_expression();
8077 * Parse a delete expression
8078 * ISO/IEC 14882:1998(E) §5.3.5
8080 static expression_t *parse_delete(void)
8082 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8083 result->base.type = type_void;
8087 if (token.type == '[') {
8089 result->kind = EXPR_UNARY_DELETE_ARRAY;
8094 expression_t *const value = parse_sub_expression(PREC_CAST);
8095 result->unary.value = value;
8097 type_t *const type = skip_typeref(value->base.type);
8098 if (!is_type_pointer(type)) {
8099 errorf(&value->base.source_position,
8100 "operand of delete must have pointer type");
8101 } else if (warning.other &&
8102 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8103 warningf(&value->base.source_position,
8104 "deleting 'void*' is undefined");
8111 * Parse a throw expression
8112 * ISO/IEC 14882:1998(E) §15:1
8114 static expression_t *parse_throw(void)
8116 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8117 result->base.type = type_void;
8121 expression_t *value = NULL;
8122 switch (token.type) {
8124 value = parse_assignment_expression();
8125 /* ISO/IEC 14882:1998(E) §15.1:3 */
8126 type_t *const orig_type = value->base.type;
8127 type_t *const type = skip_typeref(orig_type);
8128 if (is_type_incomplete(type)) {
8129 errorf(&value->base.source_position,
8130 "cannot throw object of incomplete type '%T'", orig_type);
8131 } else if (is_type_pointer(type)) {
8132 type_t *const points_to = skip_typeref(type->pointer.points_to);
8133 if (is_type_incomplete(points_to) &&
8134 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8135 errorf(&value->base.source_position,
8136 "cannot throw pointer to incomplete type '%T'", orig_type);
8144 result->unary.value = value;
8149 static bool check_pointer_arithmetic(const source_position_t *source_position,
8150 type_t *pointer_type,
8151 type_t *orig_pointer_type)
8153 type_t *points_to = pointer_type->pointer.points_to;
8154 points_to = skip_typeref(points_to);
8156 if (is_type_incomplete(points_to)) {
8157 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8158 errorf(source_position,
8159 "arithmetic with pointer to incomplete type '%T' not allowed",
8162 } else if (warning.pointer_arith) {
8163 warningf(source_position,
8164 "pointer of type '%T' used in arithmetic",
8167 } else if (is_type_function(points_to)) {
8169 errorf(source_position,
8170 "arithmetic with pointer to function type '%T' not allowed",
8173 } else if (warning.pointer_arith) {
8174 warningf(source_position,
8175 "pointer to a function '%T' used in arithmetic",
8182 static bool is_lvalue(const expression_t *expression)
8184 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8185 switch (expression->kind) {
8186 case EXPR_REFERENCE:
8187 case EXPR_ARRAY_ACCESS:
8189 case EXPR_UNARY_DEREFERENCE:
8193 /* Claim it is an lvalue, if the type is invalid. There was a parse
8194 * error before, which maybe prevented properly recognizing it as
8196 return !is_type_valid(skip_typeref(expression->base.type));
8200 static void semantic_incdec(unary_expression_t *expression)
8202 type_t *const orig_type = expression->value->base.type;
8203 type_t *const type = skip_typeref(orig_type);
8204 if (is_type_pointer(type)) {
8205 if (!check_pointer_arithmetic(&expression->base.source_position,
8209 } else if (!is_type_real(type) && is_type_valid(type)) {
8210 /* TODO: improve error message */
8211 errorf(&expression->base.source_position,
8212 "operation needs an arithmetic or pointer type");
8215 if (!is_lvalue(expression->value)) {
8216 /* TODO: improve error message */
8217 errorf(&expression->base.source_position, "lvalue required as operand");
8219 expression->base.type = orig_type;
8222 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8224 type_t *const orig_type = expression->value->base.type;
8225 type_t *const type = skip_typeref(orig_type);
8226 if (!is_type_arithmetic(type)) {
8227 if (is_type_valid(type)) {
8228 /* TODO: improve error message */
8229 errorf(&expression->base.source_position,
8230 "operation needs an arithmetic type");
8235 expression->base.type = orig_type;
8238 static void semantic_unexpr_plus(unary_expression_t *expression)
8240 semantic_unexpr_arithmetic(expression);
8241 if (warning.traditional)
8242 warningf(&expression->base.source_position,
8243 "traditional C rejects the unary plus operator");
8246 static void semantic_not(unary_expression_t *expression)
8248 type_t *const orig_type = expression->value->base.type;
8249 type_t *const type = skip_typeref(orig_type);
8250 if (!is_type_scalar(type) && is_type_valid(type)) {
8251 errorf(&expression->base.source_position,
8252 "operand of ! must be of scalar type");
8255 warn_reference_address_as_bool(expression->value);
8257 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8260 static void semantic_unexpr_integer(unary_expression_t *expression)
8262 type_t *const orig_type = expression->value->base.type;
8263 type_t *const type = skip_typeref(orig_type);
8264 if (!is_type_integer(type)) {
8265 if (is_type_valid(type)) {
8266 errorf(&expression->base.source_position,
8267 "operand of ~ must be of integer type");
8272 expression->base.type = orig_type;
8275 static void semantic_dereference(unary_expression_t *expression)
8277 type_t *const orig_type = expression->value->base.type;
8278 type_t *const type = skip_typeref(orig_type);
8279 if (!is_type_pointer(type)) {
8280 if (is_type_valid(type)) {
8281 errorf(&expression->base.source_position,
8282 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8287 type_t *result_type = type->pointer.points_to;
8288 result_type = automatic_type_conversion(result_type);
8289 expression->base.type = result_type;
8293 * Record that an address is taken (expression represents an lvalue).
8295 * @param expression the expression
8296 * @param may_be_register if true, the expression might be an register
8298 static void set_address_taken(expression_t *expression, bool may_be_register)
8300 if (expression->kind != EXPR_REFERENCE)
8303 entity_t *const entity = expression->reference.entity;
8305 if (entity->kind != ENTITY_VARIABLE)
8308 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8309 && !may_be_register) {
8310 errorf(&expression->base.source_position,
8311 "address of register variable '%Y' requested",
8312 entity->base.symbol);
8315 entity->variable.address_taken = true;
8319 * Check the semantic of the address taken expression.
8321 static void semantic_take_addr(unary_expression_t *expression)
8323 expression_t *value = expression->value;
8324 value->base.type = revert_automatic_type_conversion(value);
8326 type_t *orig_type = value->base.type;
8327 type_t *type = skip_typeref(orig_type);
8328 if (!is_type_valid(type))
8332 if (!is_lvalue(value)) {
8333 errorf(&expression->base.source_position, "'&' requires an lvalue");
8335 if (type->kind == TYPE_BITFIELD) {
8336 errorf(&expression->base.source_position,
8337 "'&' not allowed on object with bitfield type '%T'",
8341 set_address_taken(value, false);
8343 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8346 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8347 static expression_t *parse_##unexpression_type(void) \
8349 expression_t *unary_expression \
8350 = allocate_expression_zero(unexpression_type); \
8352 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8354 sfunc(&unary_expression->unary); \
8356 return unary_expression; \
8359 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8360 semantic_unexpr_arithmetic)
8361 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8362 semantic_unexpr_plus)
8363 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8365 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8366 semantic_dereference)
8367 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8369 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8370 semantic_unexpr_integer)
8371 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8373 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8376 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8378 static expression_t *parse_##unexpression_type(expression_t *left) \
8380 expression_t *unary_expression \
8381 = allocate_expression_zero(unexpression_type); \
8383 unary_expression->unary.value = left; \
8385 sfunc(&unary_expression->unary); \
8387 return unary_expression; \
8390 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8391 EXPR_UNARY_POSTFIX_INCREMENT,
8393 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8394 EXPR_UNARY_POSTFIX_DECREMENT,
8397 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8399 /* TODO: handle complex + imaginary types */
8401 type_left = get_unqualified_type(type_left);
8402 type_right = get_unqualified_type(type_right);
8404 /* § 6.3.1.8 Usual arithmetic conversions */
8405 if (type_left == type_long_double || type_right == type_long_double) {
8406 return type_long_double;
8407 } else if (type_left == type_double || type_right == type_double) {
8409 } else if (type_left == type_float || type_right == type_float) {
8413 type_left = promote_integer(type_left);
8414 type_right = promote_integer(type_right);
8416 if (type_left == type_right)
8419 bool const signed_left = is_type_signed(type_left);
8420 bool const signed_right = is_type_signed(type_right);
8421 int const rank_left = get_rank(type_left);
8422 int const rank_right = get_rank(type_right);
8424 if (signed_left == signed_right)
8425 return rank_left >= rank_right ? type_left : type_right;
8434 u_rank = rank_right;
8435 u_type = type_right;
8437 s_rank = rank_right;
8438 s_type = type_right;
8443 if (u_rank >= s_rank)
8446 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8448 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8449 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8453 case ATOMIC_TYPE_INT: return type_unsigned_int;
8454 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8455 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8457 default: panic("invalid atomic type");
8462 * Check the semantic restrictions for a binary expression.
8464 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8466 expression_t *const left = expression->left;
8467 expression_t *const right = expression->right;
8468 type_t *const orig_type_left = left->base.type;
8469 type_t *const orig_type_right = right->base.type;
8470 type_t *const type_left = skip_typeref(orig_type_left);
8471 type_t *const type_right = skip_typeref(orig_type_right);
8473 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8474 /* TODO: improve error message */
8475 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8476 errorf(&expression->base.source_position,
8477 "operation needs arithmetic types");
8482 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8483 expression->left = create_implicit_cast(left, arithmetic_type);
8484 expression->right = create_implicit_cast(right, arithmetic_type);
8485 expression->base.type = arithmetic_type;
8488 static void warn_div_by_zero(binary_expression_t const *const expression)
8490 if (!warning.div_by_zero ||
8491 !is_type_integer(expression->base.type))
8494 expression_t const *const right = expression->right;
8495 /* The type of the right operand can be different for /= */
8496 if (is_type_integer(right->base.type) &&
8497 is_constant_expression(right) &&
8498 fold_constant(right) == 0) {
8499 warningf(&expression->base.source_position, "division by zero");
8504 * Check the semantic restrictions for a div/mod expression.
8506 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8507 semantic_binexpr_arithmetic(expression);
8508 warn_div_by_zero(expression);
8511 static void semantic_shift_op(binary_expression_t *expression)
8513 expression_t *const left = expression->left;
8514 expression_t *const right = expression->right;
8515 type_t *const orig_type_left = left->base.type;
8516 type_t *const orig_type_right = right->base.type;
8517 type_t * type_left = skip_typeref(orig_type_left);
8518 type_t * type_right = skip_typeref(orig_type_right);
8520 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8521 /* TODO: improve error message */
8522 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8523 errorf(&expression->base.source_position,
8524 "operands of shift operation must have integer types");
8529 type_left = promote_integer(type_left);
8530 type_right = promote_integer(type_right);
8532 expression->left = create_implicit_cast(left, type_left);
8533 expression->right = create_implicit_cast(right, type_right);
8534 expression->base.type = type_left;
8537 static void semantic_add(binary_expression_t *expression)
8539 expression_t *const left = expression->left;
8540 expression_t *const right = expression->right;
8541 type_t *const orig_type_left = left->base.type;
8542 type_t *const orig_type_right = right->base.type;
8543 type_t *const type_left = skip_typeref(orig_type_left);
8544 type_t *const type_right = skip_typeref(orig_type_right);
8547 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8548 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8549 expression->left = create_implicit_cast(left, arithmetic_type);
8550 expression->right = create_implicit_cast(right, arithmetic_type);
8551 expression->base.type = arithmetic_type;
8553 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8554 check_pointer_arithmetic(&expression->base.source_position,
8555 type_left, orig_type_left);
8556 expression->base.type = type_left;
8557 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8558 check_pointer_arithmetic(&expression->base.source_position,
8559 type_right, orig_type_right);
8560 expression->base.type = type_right;
8561 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8562 errorf(&expression->base.source_position,
8563 "invalid operands to binary + ('%T', '%T')",
8564 orig_type_left, orig_type_right);
8568 static void semantic_sub(binary_expression_t *expression)
8570 expression_t *const left = expression->left;
8571 expression_t *const right = expression->right;
8572 type_t *const orig_type_left = left->base.type;
8573 type_t *const orig_type_right = right->base.type;
8574 type_t *const type_left = skip_typeref(orig_type_left);
8575 type_t *const type_right = skip_typeref(orig_type_right);
8576 source_position_t const *const pos = &expression->base.source_position;
8579 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8580 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8581 expression->left = create_implicit_cast(left, arithmetic_type);
8582 expression->right = create_implicit_cast(right, arithmetic_type);
8583 expression->base.type = arithmetic_type;
8585 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8586 check_pointer_arithmetic(&expression->base.source_position,
8587 type_left, orig_type_left);
8588 expression->base.type = type_left;
8589 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8590 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8591 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8592 if (!types_compatible(unqual_left, unqual_right)) {
8594 "subtracting pointers to incompatible types '%T' and '%T'",
8595 orig_type_left, orig_type_right);
8596 } else if (!is_type_object(unqual_left)) {
8597 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8598 errorf(pos, "subtracting pointers to non-object types '%T'",
8600 } else if (warning.other) {
8601 warningf(pos, "subtracting pointers to void");
8604 expression->base.type = type_ptrdiff_t;
8605 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8606 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8607 orig_type_left, orig_type_right);
8611 static void warn_string_literal_address(expression_t const* expr)
8613 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8614 expr = expr->unary.value;
8615 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8617 expr = expr->unary.value;
8620 if (expr->kind == EXPR_STRING_LITERAL ||
8621 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8622 warningf(&expr->base.source_position,
8623 "comparison with string literal results in unspecified behaviour");
8628 * Check the semantics of comparison expressions.
8630 * @param expression The expression to check.
8632 static void semantic_comparison(binary_expression_t *expression)
8634 expression_t *left = expression->left;
8635 expression_t *right = expression->right;
8637 if (warning.address) {
8638 warn_string_literal_address(left);
8639 warn_string_literal_address(right);
8641 expression_t const* const func_left = get_reference_address(left);
8642 if (func_left != NULL && is_null_pointer_constant(right)) {
8643 warningf(&expression->base.source_position,
8644 "the address of '%Y' will never be NULL",
8645 func_left->reference.entity->base.symbol);
8648 expression_t const* const func_right = get_reference_address(right);
8649 if (func_right != NULL && is_null_pointer_constant(right)) {
8650 warningf(&expression->base.source_position,
8651 "the address of '%Y' will never be NULL",
8652 func_right->reference.entity->base.symbol);
8656 type_t *orig_type_left = left->base.type;
8657 type_t *orig_type_right = right->base.type;
8658 type_t *type_left = skip_typeref(orig_type_left);
8659 type_t *type_right = skip_typeref(orig_type_right);
8661 /* TODO non-arithmetic types */
8662 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8663 /* test for signed vs unsigned compares */
8664 if (warning.sign_compare &&
8665 (expression->base.kind != EXPR_BINARY_EQUAL &&
8666 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8667 (is_type_signed(type_left) != is_type_signed(type_right))) {
8669 /* check if 1 of the operands is a constant, in this case we just
8670 * check wether we can safely represent the resulting constant in
8671 * the type of the other operand. */
8672 expression_t *const_expr = NULL;
8673 expression_t *other_expr = NULL;
8675 if (is_constant_expression(left)) {
8678 } else if (is_constant_expression(right)) {
8683 if (const_expr != NULL) {
8684 type_t *other_type = skip_typeref(other_expr->base.type);
8685 long val = fold_constant(const_expr);
8686 /* TODO: check if val can be represented by other_type */
8690 warningf(&expression->base.source_position,
8691 "comparison between signed and unsigned");
8693 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8694 expression->left = create_implicit_cast(left, arithmetic_type);
8695 expression->right = create_implicit_cast(right, arithmetic_type);
8696 expression->base.type = arithmetic_type;
8697 if (warning.float_equal &&
8698 (expression->base.kind == EXPR_BINARY_EQUAL ||
8699 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8700 is_type_float(arithmetic_type)) {
8701 warningf(&expression->base.source_position,
8702 "comparing floating point with == or != is unsafe");
8704 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8705 /* TODO check compatibility */
8706 } else if (is_type_pointer(type_left)) {
8707 expression->right = create_implicit_cast(right, type_left);
8708 } else if (is_type_pointer(type_right)) {
8709 expression->left = create_implicit_cast(left, type_right);
8710 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8711 type_error_incompatible("invalid operands in comparison",
8712 &expression->base.source_position,
8713 type_left, type_right);
8715 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8719 * Checks if a compound type has constant fields.
8721 static bool has_const_fields(const compound_type_t *type)
8723 compound_t *compound = type->compound;
8724 entity_t *entry = compound->members.entities;
8726 for (; entry != NULL; entry = entry->base.next) {
8727 if (!is_declaration(entry))
8730 const type_t *decl_type = skip_typeref(entry->declaration.type);
8731 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8738 static bool is_valid_assignment_lhs(expression_t const* const left)
8740 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8741 type_t *const type_left = skip_typeref(orig_type_left);
8743 if (!is_lvalue(left)) {
8744 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8749 if (is_type_array(type_left)) {
8750 errorf(HERE, "cannot assign to arrays ('%E')", left);
8753 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8754 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8758 if (is_type_incomplete(type_left)) {
8759 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8760 left, orig_type_left);
8763 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8764 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8765 left, orig_type_left);
8772 static void semantic_arithmetic_assign(binary_expression_t *expression)
8774 expression_t *left = expression->left;
8775 expression_t *right = expression->right;
8776 type_t *orig_type_left = left->base.type;
8777 type_t *orig_type_right = right->base.type;
8779 if (!is_valid_assignment_lhs(left))
8782 type_t *type_left = skip_typeref(orig_type_left);
8783 type_t *type_right = skip_typeref(orig_type_right);
8785 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8786 /* TODO: improve error message */
8787 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8788 errorf(&expression->base.source_position,
8789 "operation needs arithmetic types");
8794 /* combined instructions are tricky. We can't create an implicit cast on
8795 * the left side, because we need the uncasted form for the store.
8796 * The ast2firm pass has to know that left_type must be right_type
8797 * for the arithmetic operation and create a cast by itself */
8798 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8799 expression->right = create_implicit_cast(right, arithmetic_type);
8800 expression->base.type = type_left;
8803 static void semantic_divmod_assign(binary_expression_t *expression)
8805 semantic_arithmetic_assign(expression);
8806 warn_div_by_zero(expression);
8809 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8811 expression_t *const left = expression->left;
8812 expression_t *const right = expression->right;
8813 type_t *const orig_type_left = left->base.type;
8814 type_t *const orig_type_right = right->base.type;
8815 type_t *const type_left = skip_typeref(orig_type_left);
8816 type_t *const type_right = skip_typeref(orig_type_right);
8818 if (!is_valid_assignment_lhs(left))
8821 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8822 /* combined instructions are tricky. We can't create an implicit cast on
8823 * the left side, because we need the uncasted form for the store.
8824 * The ast2firm pass has to know that left_type must be right_type
8825 * for the arithmetic operation and create a cast by itself */
8826 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8827 expression->right = create_implicit_cast(right, arithmetic_type);
8828 expression->base.type = type_left;
8829 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8830 check_pointer_arithmetic(&expression->base.source_position,
8831 type_left, orig_type_left);
8832 expression->base.type = type_left;
8833 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8834 errorf(&expression->base.source_position,
8835 "incompatible types '%T' and '%T' in assignment",
8836 orig_type_left, orig_type_right);
8841 * Check the semantic restrictions of a logical expression.
8843 static void semantic_logical_op(binary_expression_t *expression)
8845 expression_t *const left = expression->left;
8846 expression_t *const right = expression->right;
8847 type_t *const orig_type_left = left->base.type;
8848 type_t *const orig_type_right = right->base.type;
8849 type_t *const type_left = skip_typeref(orig_type_left);
8850 type_t *const type_right = skip_typeref(orig_type_right);
8852 warn_reference_address_as_bool(left);
8853 warn_reference_address_as_bool(right);
8855 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8856 /* TODO: improve error message */
8857 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8858 errorf(&expression->base.source_position,
8859 "operation needs scalar types");
8864 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8868 * Check the semantic restrictions of a binary assign expression.
8870 static void semantic_binexpr_assign(binary_expression_t *expression)
8872 expression_t *left = expression->left;
8873 type_t *orig_type_left = left->base.type;
8875 if (!is_valid_assignment_lhs(left))
8878 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8879 report_assign_error(error, orig_type_left, expression->right,
8880 "assignment", &left->base.source_position);
8881 expression->right = create_implicit_cast(expression->right, orig_type_left);
8882 expression->base.type = orig_type_left;
8886 * Determine if the outermost operation (or parts thereof) of the given
8887 * expression has no effect in order to generate a warning about this fact.
8888 * Therefore in some cases this only examines some of the operands of the
8889 * expression (see comments in the function and examples below).
8891 * f() + 23; // warning, because + has no effect
8892 * x || f(); // no warning, because x controls execution of f()
8893 * x ? y : f(); // warning, because y has no effect
8894 * (void)x; // no warning to be able to suppress the warning
8895 * This function can NOT be used for an "expression has definitely no effect"-
8897 static bool expression_has_effect(const expression_t *const expr)
8899 switch (expr->kind) {
8900 case EXPR_UNKNOWN: break;
8901 case EXPR_INVALID: return true; /* do NOT warn */
8902 case EXPR_REFERENCE: return false;
8903 case EXPR_REFERENCE_ENUM_VALUE: return false;
8904 /* suppress the warning for microsoft __noop operations */
8905 case EXPR_CONST: return expr->conste.is_ms_noop;
8906 case EXPR_CHARACTER_CONSTANT: return false;
8907 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8908 case EXPR_STRING_LITERAL: return false;
8909 case EXPR_WIDE_STRING_LITERAL: return false;
8910 case EXPR_LABEL_ADDRESS: return false;
8913 const call_expression_t *const call = &expr->call;
8914 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8917 switch (call->function->builtin_symbol.symbol->ID) {
8918 case T___builtin_va_end: return true;
8919 default: return false;
8923 /* Generate the warning if either the left or right hand side of a
8924 * conditional expression has no effect */
8925 case EXPR_CONDITIONAL: {
8926 const conditional_expression_t *const cond = &expr->conditional;
8928 expression_has_effect(cond->true_expression) &&
8929 expression_has_effect(cond->false_expression);
8932 case EXPR_SELECT: return false;
8933 case EXPR_ARRAY_ACCESS: return false;
8934 case EXPR_SIZEOF: return false;
8935 case EXPR_CLASSIFY_TYPE: return false;
8936 case EXPR_ALIGNOF: return false;
8938 case EXPR_FUNCNAME: return false;
8939 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8940 case EXPR_BUILTIN_CONSTANT_P: return false;
8941 case EXPR_BUILTIN_PREFETCH: return true;
8942 case EXPR_OFFSETOF: return false;
8943 case EXPR_VA_START: return true;
8944 case EXPR_VA_ARG: return true;
8945 case EXPR_STATEMENT: return true; // TODO
8946 case EXPR_COMPOUND_LITERAL: return false;
8948 case EXPR_UNARY_NEGATE: return false;
8949 case EXPR_UNARY_PLUS: return false;
8950 case EXPR_UNARY_BITWISE_NEGATE: return false;
8951 case EXPR_UNARY_NOT: return false;
8952 case EXPR_UNARY_DEREFERENCE: return false;
8953 case EXPR_UNARY_TAKE_ADDRESS: return false;
8954 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8955 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8956 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8957 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8959 /* Treat void casts as if they have an effect in order to being able to
8960 * suppress the warning */
8961 case EXPR_UNARY_CAST: {
8962 type_t *const type = skip_typeref(expr->base.type);
8963 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8966 case EXPR_UNARY_CAST_IMPLICIT: return true;
8967 case EXPR_UNARY_ASSUME: return true;
8968 case EXPR_UNARY_DELETE: return true;
8969 case EXPR_UNARY_DELETE_ARRAY: return true;
8970 case EXPR_UNARY_THROW: return true;
8972 case EXPR_BINARY_ADD: return false;
8973 case EXPR_BINARY_SUB: return false;
8974 case EXPR_BINARY_MUL: return false;
8975 case EXPR_BINARY_DIV: return false;
8976 case EXPR_BINARY_MOD: return false;
8977 case EXPR_BINARY_EQUAL: return false;
8978 case EXPR_BINARY_NOTEQUAL: return false;
8979 case EXPR_BINARY_LESS: return false;
8980 case EXPR_BINARY_LESSEQUAL: return false;
8981 case EXPR_BINARY_GREATER: return false;
8982 case EXPR_BINARY_GREATEREQUAL: return false;
8983 case EXPR_BINARY_BITWISE_AND: return false;
8984 case EXPR_BINARY_BITWISE_OR: return false;
8985 case EXPR_BINARY_BITWISE_XOR: return false;
8986 case EXPR_BINARY_SHIFTLEFT: return false;
8987 case EXPR_BINARY_SHIFTRIGHT: return false;
8988 case EXPR_BINARY_ASSIGN: return true;
8989 case EXPR_BINARY_MUL_ASSIGN: return true;
8990 case EXPR_BINARY_DIV_ASSIGN: return true;
8991 case EXPR_BINARY_MOD_ASSIGN: return true;
8992 case EXPR_BINARY_ADD_ASSIGN: return true;
8993 case EXPR_BINARY_SUB_ASSIGN: return true;
8994 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8995 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8996 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8997 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8998 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9000 /* Only examine the right hand side of && and ||, because the left hand
9001 * side already has the effect of controlling the execution of the right
9003 case EXPR_BINARY_LOGICAL_AND:
9004 case EXPR_BINARY_LOGICAL_OR:
9005 /* Only examine the right hand side of a comma expression, because the left
9006 * hand side has a separate warning */
9007 case EXPR_BINARY_COMMA:
9008 return expression_has_effect(expr->binary.right);
9010 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9011 case EXPR_BINARY_ISGREATER: return false;
9012 case EXPR_BINARY_ISGREATEREQUAL: return false;
9013 case EXPR_BINARY_ISLESS: return false;
9014 case EXPR_BINARY_ISLESSEQUAL: return false;
9015 case EXPR_BINARY_ISLESSGREATER: return false;
9016 case EXPR_BINARY_ISUNORDERED: return false;
9019 internal_errorf(HERE, "unexpected expression");
9022 static void semantic_comma(binary_expression_t *expression)
9024 if (warning.unused_value) {
9025 const expression_t *const left = expression->left;
9026 if (!expression_has_effect(left)) {
9027 warningf(&left->base.source_position,
9028 "left-hand operand of comma expression has no effect");
9031 expression->base.type = expression->right->base.type;
9035 * @param prec_r precedence of the right operand
9037 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9038 static expression_t *parse_##binexpression_type(expression_t *left) \
9040 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9041 binexpr->binary.left = left; \
9044 expression_t *right = parse_sub_expression(prec_r); \
9046 binexpr->binary.right = right; \
9047 sfunc(&binexpr->binary); \
9052 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9053 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9054 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9055 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9056 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9057 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9058 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9059 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9060 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9061 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9062 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9063 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9064 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9065 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9066 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9067 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9068 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9069 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9070 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9071 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9072 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9073 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9074 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9075 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9076 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9077 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9078 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9079 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9080 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9081 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9084 static expression_t *parse_sub_expression(precedence_t precedence)
9086 if (token.type < 0) {
9087 return expected_expression_error();
9090 expression_parser_function_t *parser
9091 = &expression_parsers[token.type];
9092 source_position_t source_position = token.source_position;
9095 if (parser->parser != NULL) {
9096 left = parser->parser();
9098 left = parse_primary_expression();
9100 assert(left != NULL);
9101 left->base.source_position = source_position;
9104 if (token.type < 0) {
9105 return expected_expression_error();
9108 parser = &expression_parsers[token.type];
9109 if (parser->infix_parser == NULL)
9111 if (parser->infix_precedence < precedence)
9114 left = parser->infix_parser(left);
9116 assert(left != NULL);
9117 assert(left->kind != EXPR_UNKNOWN);
9118 left->base.source_position = source_position;
9125 * Parse an expression.
9127 static expression_t *parse_expression(void)
9129 return parse_sub_expression(PREC_EXPRESSION);
9133 * Register a parser for a prefix-like operator.
9135 * @param parser the parser function
9136 * @param token_type the token type of the prefix token
9138 static void register_expression_parser(parse_expression_function parser,
9141 expression_parser_function_t *entry = &expression_parsers[token_type];
9143 if (entry->parser != NULL) {
9144 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9145 panic("trying to register multiple expression parsers for a token");
9147 entry->parser = parser;
9151 * Register a parser for an infix operator with given precedence.
9153 * @param parser the parser function
9154 * @param token_type the token type of the infix operator
9155 * @param precedence the precedence of the operator
9157 static void register_infix_parser(parse_expression_infix_function parser,
9158 int token_type, unsigned precedence)
9160 expression_parser_function_t *entry = &expression_parsers[token_type];
9162 if (entry->infix_parser != NULL) {
9163 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9164 panic("trying to register multiple infix expression parsers for a "
9167 entry->infix_parser = parser;
9168 entry->infix_precedence = precedence;
9172 * Initialize the expression parsers.
9174 static void init_expression_parsers(void)
9176 memset(&expression_parsers, 0, sizeof(expression_parsers));
9178 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9179 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9180 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9181 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9182 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9183 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9184 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9185 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9186 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9187 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9188 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9189 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9190 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9191 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9192 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9193 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9194 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9195 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9196 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9197 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9198 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9199 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9200 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9201 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9202 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9203 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9204 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9205 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9206 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9207 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9208 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9209 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9210 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9211 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9212 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9213 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9214 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9216 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9217 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9218 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9219 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9220 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9221 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9222 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9223 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9224 register_expression_parser(parse_sizeof, T_sizeof);
9225 register_expression_parser(parse_alignof, T___alignof__);
9226 register_expression_parser(parse_extension, T___extension__);
9227 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9228 register_expression_parser(parse_delete, T_delete);
9229 register_expression_parser(parse_throw, T_throw);
9233 * Parse a asm statement arguments specification.
9235 static asm_argument_t *parse_asm_arguments(bool is_out)
9237 asm_argument_t *result = NULL;
9238 asm_argument_t **anchor = &result;
9240 while (token.type == T_STRING_LITERAL || token.type == '[') {
9241 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9242 memset(argument, 0, sizeof(argument[0]));
9244 if (token.type == '[') {
9246 if (token.type != T_IDENTIFIER) {
9247 parse_error_expected("while parsing asm argument",
9248 T_IDENTIFIER, NULL);
9251 argument->symbol = token.v.symbol;
9256 argument->constraints = parse_string_literals();
9258 add_anchor_token(')');
9259 expression_t *expression = parse_expression();
9260 rem_anchor_token(')');
9262 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9263 * change size or type representation (e.g. int -> long is ok, but
9264 * int -> float is not) */
9265 if (expression->kind == EXPR_UNARY_CAST) {
9266 type_t *const type = expression->base.type;
9267 type_kind_t const kind = type->kind;
9268 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9271 if (kind == TYPE_ATOMIC) {
9272 atomic_type_kind_t const akind = type->atomic.akind;
9273 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9274 size = get_atomic_type_size(akind);
9276 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9277 size = get_atomic_type_size(get_intptr_kind());
9281 expression_t *const value = expression->unary.value;
9282 type_t *const value_type = value->base.type;
9283 type_kind_t const value_kind = value_type->kind;
9285 unsigned value_flags;
9286 unsigned value_size;
9287 if (value_kind == TYPE_ATOMIC) {
9288 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9289 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9290 value_size = get_atomic_type_size(value_akind);
9291 } else if (value_kind == TYPE_POINTER) {
9292 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9293 value_size = get_atomic_type_size(get_intptr_kind());
9298 if (value_flags != flags || value_size != size)
9302 } while (expression->kind == EXPR_UNARY_CAST);
9306 if (!is_lvalue(expression)) {
9307 errorf(&expression->base.source_position,
9308 "asm output argument is not an lvalue");
9311 if (argument->constraints.begin[0] == '+')
9312 mark_vars_read(expression, NULL);
9314 mark_vars_read(expression, NULL);
9316 argument->expression = expression;
9319 set_address_taken(expression, true);
9322 anchor = &argument->next;
9324 if (token.type != ',')
9335 * Parse a asm statement clobber specification.
9337 static asm_clobber_t *parse_asm_clobbers(void)
9339 asm_clobber_t *result = NULL;
9340 asm_clobber_t *last = NULL;
9342 while (token.type == T_STRING_LITERAL) {
9343 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9344 clobber->clobber = parse_string_literals();
9347 last->next = clobber;
9353 if (token.type != ',')
9362 * Parse an asm statement.
9364 static statement_t *parse_asm_statement(void)
9366 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9367 asm_statement_t *asm_statement = &statement->asms;
9371 if (token.type == T_volatile) {
9373 asm_statement->is_volatile = true;
9377 add_anchor_token(')');
9378 add_anchor_token(':');
9379 asm_statement->asm_text = parse_string_literals();
9381 if (token.type != ':') {
9382 rem_anchor_token(':');
9387 asm_statement->outputs = parse_asm_arguments(true);
9388 if (token.type != ':') {
9389 rem_anchor_token(':');
9394 asm_statement->inputs = parse_asm_arguments(false);
9395 if (token.type != ':') {
9396 rem_anchor_token(':');
9399 rem_anchor_token(':');
9402 asm_statement->clobbers = parse_asm_clobbers();
9405 rem_anchor_token(')');
9409 if (asm_statement->outputs == NULL) {
9410 /* GCC: An 'asm' instruction without any output operands will be treated
9411 * identically to a volatile 'asm' instruction. */
9412 asm_statement->is_volatile = true;
9417 return create_invalid_statement();
9421 * Parse a case statement.
9423 static statement_t *parse_case_statement(void)
9425 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9426 source_position_t *const pos = &statement->base.source_position;
9430 expression_t *const expression = parse_expression();
9431 statement->case_label.expression = expression;
9432 if (!is_constant_expression(expression)) {
9433 /* This check does not prevent the error message in all cases of an
9434 * prior error while parsing the expression. At least it catches the
9435 * common case of a mistyped enum entry. */
9436 if (is_type_valid(skip_typeref(expression->base.type))) {
9437 errorf(pos, "case label does not reduce to an integer constant");
9439 statement->case_label.is_bad = true;
9441 long const val = fold_constant(expression);
9442 statement->case_label.first_case = val;
9443 statement->case_label.last_case = val;
9447 if (token.type == T_DOTDOTDOT) {
9449 expression_t *const end_range = parse_expression();
9450 statement->case_label.end_range = end_range;
9451 if (!is_constant_expression(end_range)) {
9452 /* This check does not prevent the error message in all cases of an
9453 * prior error while parsing the expression. At least it catches the
9454 * common case of a mistyped enum entry. */
9455 if (is_type_valid(skip_typeref(end_range->base.type))) {
9456 errorf(pos, "case range does not reduce to an integer constant");
9458 statement->case_label.is_bad = true;
9460 long const val = fold_constant(end_range);
9461 statement->case_label.last_case = val;
9463 if (warning.other && val < statement->case_label.first_case) {
9464 statement->case_label.is_empty_range = true;
9465 warningf(pos, "empty range specified");
9471 PUSH_PARENT(statement);
9475 if (current_switch != NULL) {
9476 if (! statement->case_label.is_bad) {
9477 /* Check for duplicate case values */
9478 case_label_statement_t *c = &statement->case_label;
9479 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9480 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9483 if (c->last_case < l->first_case || c->first_case > l->last_case)
9486 errorf(pos, "duplicate case value (previously used %P)",
9487 &l->base.source_position);
9491 /* link all cases into the switch statement */
9492 if (current_switch->last_case == NULL) {
9493 current_switch->first_case = &statement->case_label;
9495 current_switch->last_case->next = &statement->case_label;
9497 current_switch->last_case = &statement->case_label;
9499 errorf(pos, "case label not within a switch statement");
9502 statement_t *const inner_stmt = parse_statement();
9503 statement->case_label.statement = inner_stmt;
9504 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9505 errorf(&inner_stmt->base.source_position, "declaration after case label");
9512 return create_invalid_statement();
9516 * Parse a default statement.
9518 static statement_t *parse_default_statement(void)
9520 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9524 PUSH_PARENT(statement);
9527 if (current_switch != NULL) {
9528 const case_label_statement_t *def_label = current_switch->default_label;
9529 if (def_label != NULL) {
9530 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9531 &def_label->base.source_position);
9533 current_switch->default_label = &statement->case_label;
9535 /* link all cases into the switch statement */
9536 if (current_switch->last_case == NULL) {
9537 current_switch->first_case = &statement->case_label;
9539 current_switch->last_case->next = &statement->case_label;
9541 current_switch->last_case = &statement->case_label;
9544 errorf(&statement->base.source_position,
9545 "'default' label not within a switch statement");
9548 statement_t *const inner_stmt = parse_statement();
9549 statement->case_label.statement = inner_stmt;
9550 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9551 errorf(&inner_stmt->base.source_position, "declaration after default label");
9558 return create_invalid_statement();
9562 * Parse a label statement.
9564 static statement_t *parse_label_statement(void)
9566 assert(token.type == T_IDENTIFIER);
9567 symbol_t *symbol = token.v.symbol;
9568 label_t *label = get_label(symbol);
9570 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9571 statement->label.label = label;
9575 PUSH_PARENT(statement);
9577 /* if statement is already set then the label is defined twice,
9578 * otherwise it was just mentioned in a goto/local label declaration so far
9580 if (label->statement != NULL) {
9581 errorf(HERE, "duplicate label '%Y' (declared %P)",
9582 symbol, &label->base.source_position);
9584 label->base.source_position = token.source_position;
9585 label->statement = statement;
9590 if (token.type == '}') {
9591 /* TODO only warn? */
9592 if (warning.other && false) {
9593 warningf(HERE, "label at end of compound statement");
9594 statement->label.statement = create_empty_statement();
9596 errorf(HERE, "label at end of compound statement");
9597 statement->label.statement = create_invalid_statement();
9599 } else if (token.type == ';') {
9600 /* Eat an empty statement here, to avoid the warning about an empty
9601 * statement after a label. label:; is commonly used to have a label
9602 * before a closing brace. */
9603 statement->label.statement = create_empty_statement();
9606 statement_t *const inner_stmt = parse_statement();
9607 statement->label.statement = inner_stmt;
9608 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9609 errorf(&inner_stmt->base.source_position, "declaration after label");
9613 /* remember the labels in a list for later checking */
9614 *label_anchor = &statement->label;
9615 label_anchor = &statement->label.next;
9622 * Parse an if statement.
9624 static statement_t *parse_if(void)
9626 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9630 PUSH_PARENT(statement);
9632 add_anchor_token('{');
9635 add_anchor_token(')');
9636 expression_t *const expr = parse_expression();
9637 statement->ifs.condition = expr;
9638 warn_reference_address_as_bool(expr);
9639 mark_vars_read(expr, NULL);
9640 rem_anchor_token(')');
9644 rem_anchor_token('{');
9646 add_anchor_token(T_else);
9647 statement->ifs.true_statement = parse_statement();
9648 rem_anchor_token(T_else);
9650 if (token.type == T_else) {
9652 statement->ifs.false_statement = parse_statement();
9660 * Check that all enums are handled in a switch.
9662 * @param statement the switch statement to check
9664 static void check_enum_cases(const switch_statement_t *statement) {
9665 const type_t *type = skip_typeref(statement->expression->base.type);
9666 if (! is_type_enum(type))
9668 const enum_type_t *enumt = &type->enumt;
9670 /* if we have a default, no warnings */
9671 if (statement->default_label != NULL)
9674 /* FIXME: calculation of value should be done while parsing */
9675 /* TODO: quadratic algorithm here. Change to an n log n one */
9676 long last_value = -1;
9677 const entity_t *entry = enumt->enume->base.next;
9678 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9679 entry = entry->base.next) {
9680 const expression_t *expression = entry->enum_value.value;
9681 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9683 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9684 if (l->expression == NULL)
9686 if (l->first_case <= value && value <= l->last_case) {
9692 warningf(&statement->base.source_position,
9693 "enumeration value '%Y' not handled in switch",
9694 entry->base.symbol);
9701 * Parse a switch statement.
9703 static statement_t *parse_switch(void)
9705 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9709 PUSH_PARENT(statement);
9712 add_anchor_token(')');
9713 expression_t *const expr = parse_expression();
9714 mark_vars_read(expr, NULL);
9715 type_t * type = skip_typeref(expr->base.type);
9716 if (is_type_integer(type)) {
9717 type = promote_integer(type);
9718 if (warning.traditional) {
9719 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9720 warningf(&expr->base.source_position,
9721 "'%T' switch expression not converted to '%T' in ISO C",
9725 } else if (is_type_valid(type)) {
9726 errorf(&expr->base.source_position,
9727 "switch quantity is not an integer, but '%T'", type);
9728 type = type_error_type;
9730 statement->switchs.expression = create_implicit_cast(expr, type);
9732 rem_anchor_token(')');
9734 switch_statement_t *rem = current_switch;
9735 current_switch = &statement->switchs;
9736 statement->switchs.body = parse_statement();
9737 current_switch = rem;
9739 if (warning.switch_default &&
9740 statement->switchs.default_label == NULL) {
9741 warningf(&statement->base.source_position, "switch has no default case");
9743 if (warning.switch_enum)
9744 check_enum_cases(&statement->switchs);
9750 return create_invalid_statement();
9753 static statement_t *parse_loop_body(statement_t *const loop)
9755 statement_t *const rem = current_loop;
9756 current_loop = loop;
9758 statement_t *const body = parse_statement();
9765 * Parse a while statement.
9767 static statement_t *parse_while(void)
9769 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9773 PUSH_PARENT(statement);
9776 add_anchor_token(')');
9777 expression_t *const cond = parse_expression();
9778 statement->whiles.condition = cond;
9779 warn_reference_address_as_bool(cond);
9780 mark_vars_read(cond, NULL);
9781 rem_anchor_token(')');
9784 statement->whiles.body = parse_loop_body(statement);
9790 return create_invalid_statement();
9794 * Parse a do statement.
9796 static statement_t *parse_do(void)
9798 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9802 PUSH_PARENT(statement);
9804 add_anchor_token(T_while);
9805 statement->do_while.body = parse_loop_body(statement);
9806 rem_anchor_token(T_while);
9810 add_anchor_token(')');
9811 expression_t *const cond = parse_expression();
9812 statement->do_while.condition = cond;
9813 warn_reference_address_as_bool(cond);
9814 mark_vars_read(cond, NULL);
9815 rem_anchor_token(')');
9823 return create_invalid_statement();
9827 * Parse a for statement.
9829 static statement_t *parse_for(void)
9831 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9835 PUSH_PARENT(statement);
9837 size_t const top = environment_top();
9838 scope_push(&statement->fors.scope);
9841 add_anchor_token(')');
9843 if (token.type != ';') {
9844 if (is_declaration_specifier(&token, false)) {
9845 parse_declaration(record_entity);
9847 add_anchor_token(';');
9848 expression_t *const init = parse_expression();
9849 statement->fors.initialisation = init;
9850 mark_vars_read(init, VAR_ANY);
9851 if (warning.unused_value && !expression_has_effect(init)) {
9852 warningf(&init->base.source_position,
9853 "initialisation of 'for'-statement has no effect");
9855 rem_anchor_token(';');
9862 if (token.type != ';') {
9863 add_anchor_token(';');
9864 expression_t *const cond = parse_expression();
9865 statement->fors.condition = cond;
9866 warn_reference_address_as_bool(cond);
9867 mark_vars_read(cond, NULL);
9868 rem_anchor_token(';');
9871 if (token.type != ')') {
9872 expression_t *const step = parse_expression();
9873 statement->fors.step = step;
9874 mark_vars_read(step, VAR_ANY);
9875 if (warning.unused_value && !expression_has_effect(step)) {
9876 warningf(&step->base.source_position,
9877 "step of 'for'-statement has no effect");
9881 rem_anchor_token(')');
9882 statement->fors.body = parse_loop_body(statement);
9884 assert(current_scope == &statement->fors.scope);
9886 environment_pop_to(top);
9893 rem_anchor_token(')');
9894 assert(current_scope == &statement->fors.scope);
9896 environment_pop_to(top);
9898 return create_invalid_statement();
9902 * Parse a goto statement.
9904 static statement_t *parse_goto(void)
9906 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9909 if (GNU_MODE && token.type == '*') {
9911 expression_t *expression = parse_expression();
9912 mark_vars_read(expression, NULL);
9914 /* Argh: although documentation says the expression must be of type void*,
9915 * gcc accepts anything that can be casted into void* without error */
9916 type_t *type = expression->base.type;
9918 if (type != type_error_type) {
9919 if (!is_type_pointer(type) && !is_type_integer(type)) {
9920 errorf(&expression->base.source_position,
9921 "cannot convert to a pointer type");
9922 } else if (warning.other && type != type_void_ptr) {
9923 warningf(&expression->base.source_position,
9924 "type of computed goto expression should be 'void*' not '%T'", type);
9926 expression = create_implicit_cast(expression, type_void_ptr);
9929 statement->gotos.expression = expression;
9931 if (token.type != T_IDENTIFIER) {
9933 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9935 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9939 symbol_t *symbol = token.v.symbol;
9942 statement->gotos.label = get_label(symbol);
9945 /* remember the goto's in a list for later checking */
9946 *goto_anchor = &statement->gotos;
9947 goto_anchor = &statement->gotos.next;
9953 return create_invalid_statement();
9957 * Parse a continue statement.
9959 static statement_t *parse_continue(void)
9961 if (current_loop == NULL) {
9962 errorf(HERE, "continue statement not within loop");
9965 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9975 * Parse a break statement.
9977 static statement_t *parse_break(void)
9979 if (current_switch == NULL && current_loop == NULL) {
9980 errorf(HERE, "break statement not within loop or switch");
9983 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9993 * Parse a __leave statement.
9995 static statement_t *parse_leave_statement(void)
9997 if (current_try == NULL) {
9998 errorf(HERE, "__leave statement not within __try");
10001 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10011 * Check if a given entity represents a local variable.
10013 static bool is_local_variable(const entity_t *entity)
10015 if (entity->kind != ENTITY_VARIABLE)
10018 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10019 case STORAGE_CLASS_AUTO:
10020 case STORAGE_CLASS_REGISTER: {
10021 const type_t *type = skip_typeref(entity->declaration.type);
10022 if (is_type_function(type)) {
10034 * Check if a given expression represents a local variable.
10036 static bool expression_is_local_variable(const expression_t *expression)
10038 if (expression->base.kind != EXPR_REFERENCE) {
10041 const entity_t *entity = expression->reference.entity;
10042 return is_local_variable(entity);
10046 * Check if a given expression represents a local variable and
10047 * return its declaration then, else return NULL.
10049 entity_t *expression_is_variable(const expression_t *expression)
10051 if (expression->base.kind != EXPR_REFERENCE) {
10054 entity_t *entity = expression->reference.entity;
10055 if (entity->kind != ENTITY_VARIABLE)
10062 * Parse a return statement.
10064 static statement_t *parse_return(void)
10068 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10070 expression_t *return_value = NULL;
10071 if (token.type != ';') {
10072 return_value = parse_expression();
10073 mark_vars_read(return_value, NULL);
10076 const type_t *const func_type = skip_typeref(current_function->base.type);
10077 assert(is_type_function(func_type));
10078 type_t *const return_type = skip_typeref(func_type->function.return_type);
10080 if (return_value != NULL) {
10081 type_t *return_value_type = skip_typeref(return_value->base.type);
10083 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10084 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10085 if (warning.other) {
10086 warningf(&statement->base.source_position,
10087 "'return' with a value, in function returning void");
10089 return_value = NULL;
10091 assign_error_t error = semantic_assign(return_type, return_value);
10092 report_assign_error(error, return_type, return_value, "'return'",
10093 &statement->base.source_position);
10094 return_value = create_implicit_cast(return_value, return_type);
10096 /* check for returning address of a local var */
10097 if (warning.other && return_value != NULL
10098 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10099 const expression_t *expression = return_value->unary.value;
10100 if (expression_is_local_variable(expression)) {
10101 warningf(&statement->base.source_position,
10102 "function returns address of local variable");
10105 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10106 warningf(&statement->base.source_position,
10107 "'return' without value, in function returning non-void");
10109 statement->returns.value = return_value;
10118 * Parse a declaration statement.
10120 static statement_t *parse_declaration_statement(void)
10122 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10124 entity_t *before = current_scope->last_entity;
10126 parse_external_declaration();
10128 parse_declaration(record_entity);
10130 if (before == NULL) {
10131 statement->declaration.declarations_begin = current_scope->entities;
10133 statement->declaration.declarations_begin = before->base.next;
10135 statement->declaration.declarations_end = current_scope->last_entity;
10141 * Parse an expression statement, ie. expr ';'.
10143 static statement_t *parse_expression_statement(void)
10145 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10147 expression_t *const expr = parse_expression();
10148 statement->expression.expression = expr;
10149 mark_vars_read(expr, VAR_ANY);
10158 * Parse a microsoft __try { } __finally { } or
10159 * __try{ } __except() { }
10161 static statement_t *parse_ms_try_statment(void)
10163 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10166 PUSH_PARENT(statement);
10168 ms_try_statement_t *rem = current_try;
10169 current_try = &statement->ms_try;
10170 statement->ms_try.try_statement = parse_compound_statement(false);
10175 if (token.type == T___except) {
10178 add_anchor_token(')');
10179 expression_t *const expr = parse_expression();
10180 mark_vars_read(expr, NULL);
10181 type_t * type = skip_typeref(expr->base.type);
10182 if (is_type_integer(type)) {
10183 type = promote_integer(type);
10184 } else if (is_type_valid(type)) {
10185 errorf(&expr->base.source_position,
10186 "__expect expression is not an integer, but '%T'", type);
10187 type = type_error_type;
10189 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10190 rem_anchor_token(')');
10192 statement->ms_try.final_statement = parse_compound_statement(false);
10193 } else if (token.type == T__finally) {
10195 statement->ms_try.final_statement = parse_compound_statement(false);
10197 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10198 return create_invalid_statement();
10202 return create_invalid_statement();
10205 static statement_t *parse_empty_statement(void)
10207 if (warning.empty_statement) {
10208 warningf(HERE, "statement is empty");
10210 statement_t *const statement = create_empty_statement();
10215 static statement_t *parse_local_label_declaration(void)
10217 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10221 entity_t *begin = NULL, *end = NULL;
10224 if (token.type != T_IDENTIFIER) {
10225 parse_error_expected("while parsing local label declaration",
10226 T_IDENTIFIER, NULL);
10229 symbol_t *symbol = token.v.symbol;
10230 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10231 if (entity != NULL && entity->base.parent_scope == current_scope) {
10232 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10233 symbol, &entity->base.source_position);
10235 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10237 entity->base.parent_scope = current_scope;
10238 entity->base.namespc = NAMESPACE_LABEL;
10239 entity->base.source_position = token.source_position;
10240 entity->base.symbol = symbol;
10243 end->base.next = entity;
10248 environment_push(entity);
10252 if (token.type != ',')
10258 statement->declaration.declarations_begin = begin;
10259 statement->declaration.declarations_end = end;
10263 static void parse_namespace_definition(void)
10267 entity_t *entity = NULL;
10268 symbol_t *symbol = NULL;
10270 if (token.type == T_IDENTIFIER) {
10271 symbol = token.v.symbol;
10274 entity = get_entity(symbol, NAMESPACE_NORMAL);
10275 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10276 && entity->base.parent_scope == current_scope) {
10277 error_redefined_as_different_kind(&token.source_position,
10278 entity, ENTITY_NAMESPACE);
10283 if (entity == NULL) {
10284 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10285 entity->base.symbol = symbol;
10286 entity->base.source_position = token.source_position;
10287 entity->base.namespc = NAMESPACE_NORMAL;
10288 entity->base.parent_scope = current_scope;
10291 if (token.type == '=') {
10292 /* TODO: parse namespace alias */
10293 panic("namespace alias definition not supported yet");
10296 environment_push(entity);
10297 append_entity(current_scope, entity);
10299 size_t const top = environment_top();
10300 scope_push(&entity->namespacee.members);
10307 assert(current_scope == &entity->namespacee.members);
10309 environment_pop_to(top);
10313 * Parse a statement.
10314 * There's also parse_statement() which additionally checks for
10315 * "statement has no effect" warnings
10317 static statement_t *intern_parse_statement(void)
10319 statement_t *statement = NULL;
10321 /* declaration or statement */
10322 add_anchor_token(';');
10323 switch (token.type) {
10324 case T_IDENTIFIER: {
10325 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10326 if (la1_type == ':') {
10327 statement = parse_label_statement();
10328 } else if (is_typedef_symbol(token.v.symbol)) {
10329 statement = parse_declaration_statement();
10331 /* it's an identifier, the grammar says this must be an
10332 * expression statement. However it is common that users mistype
10333 * declaration types, so we guess a bit here to improve robustness
10334 * for incorrect programs */
10335 switch (la1_type) {
10338 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10339 goto expression_statment;
10344 statement = parse_declaration_statement();
10348 expression_statment:
10349 statement = parse_expression_statement();
10356 case T___extension__:
10357 /* This can be a prefix to a declaration or an expression statement.
10358 * We simply eat it now and parse the rest with tail recursion. */
10361 } while (token.type == T___extension__);
10362 bool old_gcc_extension = in_gcc_extension;
10363 in_gcc_extension = true;
10364 statement = parse_statement();
10365 in_gcc_extension = old_gcc_extension;
10369 statement = parse_declaration_statement();
10373 statement = parse_local_label_declaration();
10376 case ';': statement = parse_empty_statement(); break;
10377 case '{': statement = parse_compound_statement(false); break;
10378 case T___leave: statement = parse_leave_statement(); break;
10379 case T___try: statement = parse_ms_try_statment(); break;
10380 case T_asm: statement = parse_asm_statement(); break;
10381 case T_break: statement = parse_break(); break;
10382 case T_case: statement = parse_case_statement(); break;
10383 case T_continue: statement = parse_continue(); break;
10384 case T_default: statement = parse_default_statement(); break;
10385 case T_do: statement = parse_do(); break;
10386 case T_for: statement = parse_for(); break;
10387 case T_goto: statement = parse_goto(); break;
10388 case T_if: statement = parse_if(); break;
10389 case T_return: statement = parse_return(); break;
10390 case T_switch: statement = parse_switch(); break;
10391 case T_while: statement = parse_while(); break;
10394 statement = parse_expression_statement();
10398 errorf(HERE, "unexpected token %K while parsing statement", &token);
10399 statement = create_invalid_statement();
10404 rem_anchor_token(';');
10406 assert(statement != NULL
10407 && statement->base.source_position.input_name != NULL);
10413 * parse a statement and emits "statement has no effect" warning if needed
10414 * (This is really a wrapper around intern_parse_statement with check for 1
10415 * single warning. It is needed, because for statement expressions we have
10416 * to avoid the warning on the last statement)
10418 static statement_t *parse_statement(void)
10420 statement_t *statement = intern_parse_statement();
10422 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10423 expression_t *expression = statement->expression.expression;
10424 if (!expression_has_effect(expression)) {
10425 warningf(&expression->base.source_position,
10426 "statement has no effect");
10434 * Parse a compound statement.
10436 static statement_t *parse_compound_statement(bool inside_expression_statement)
10438 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10440 PUSH_PARENT(statement);
10443 add_anchor_token('}');
10445 size_t const top = environment_top();
10446 scope_push(&statement->compound.scope);
10448 statement_t **anchor = &statement->compound.statements;
10449 bool only_decls_so_far = true;
10450 while (token.type != '}') {
10451 if (token.type == T_EOF) {
10452 errorf(&statement->base.source_position,
10453 "EOF while parsing compound statement");
10456 statement_t *sub_statement = intern_parse_statement();
10457 if (is_invalid_statement(sub_statement)) {
10458 /* an error occurred. if we are at an anchor, return */
10464 if (warning.declaration_after_statement) {
10465 if (sub_statement->kind != STATEMENT_DECLARATION) {
10466 only_decls_so_far = false;
10467 } else if (!only_decls_so_far) {
10468 warningf(&sub_statement->base.source_position,
10469 "ISO C90 forbids mixed declarations and code");
10473 *anchor = sub_statement;
10475 while (sub_statement->base.next != NULL)
10476 sub_statement = sub_statement->base.next;
10478 anchor = &sub_statement->base.next;
10482 /* look over all statements again to produce no effect warnings */
10483 if (warning.unused_value) {
10484 statement_t *sub_statement = statement->compound.statements;
10485 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10486 if (sub_statement->kind != STATEMENT_EXPRESSION)
10488 /* don't emit a warning for the last expression in an expression
10489 * statement as it has always an effect */
10490 if (inside_expression_statement && sub_statement->base.next == NULL)
10493 expression_t *expression = sub_statement->expression.expression;
10494 if (!expression_has_effect(expression)) {
10495 warningf(&expression->base.source_position,
10496 "statement has no effect");
10502 rem_anchor_token('}');
10503 assert(current_scope == &statement->compound.scope);
10505 environment_pop_to(top);
10512 * Check for unused global static functions and variables
10514 static void check_unused_globals(void)
10516 if (!warning.unused_function && !warning.unused_variable)
10519 for (const entity_t *entity = file_scope->entities; entity != NULL;
10520 entity = entity->base.next) {
10521 if (!is_declaration(entity))
10524 const declaration_t *declaration = &entity->declaration;
10525 if (declaration->used ||
10526 declaration->modifiers & DM_UNUSED ||
10527 declaration->modifiers & DM_USED ||
10528 declaration->storage_class != STORAGE_CLASS_STATIC)
10531 type_t *const type = declaration->type;
10533 if (entity->kind == ENTITY_FUNCTION) {
10534 /* inhibit warning for static inline functions */
10535 if (entity->function.is_inline)
10538 s = entity->function.statement != NULL ? "defined" : "declared";
10543 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10544 type, declaration->base.symbol, s);
10548 static void parse_global_asm(void)
10550 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10555 statement->asms.asm_text = parse_string_literals();
10556 statement->base.next = unit->global_asm;
10557 unit->global_asm = statement;
10565 static void parse_linkage_specification(void)
10568 assert(token.type == T_STRING_LITERAL);
10570 const char *linkage = parse_string_literals().begin;
10572 linkage_kind_t old_linkage = current_linkage;
10573 linkage_kind_t new_linkage;
10574 if (strcmp(linkage, "C") == 0) {
10575 new_linkage = LINKAGE_C;
10576 } else if (strcmp(linkage, "C++") == 0) {
10577 new_linkage = LINKAGE_CXX;
10579 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10580 new_linkage = LINKAGE_INVALID;
10582 current_linkage = new_linkage;
10584 if (token.type == '{') {
10593 assert(current_linkage == new_linkage);
10594 current_linkage = old_linkage;
10597 static void parse_external(void)
10599 switch (token.type) {
10600 DECLARATION_START_NO_EXTERN
10602 case T___extension__:
10603 case '(': /* for function declarations with implicit return type and
10604 * parenthesized declarator, i.e. (f)(void); */
10605 parse_external_declaration();
10609 if (look_ahead(1)->type == T_STRING_LITERAL) {
10610 parse_linkage_specification();
10612 parse_external_declaration();
10617 parse_global_asm();
10621 parse_namespace_definition();
10625 if (!strict_mode) {
10627 warningf(HERE, "stray ';' outside of function");
10634 errorf(HERE, "stray %K outside of function", &token);
10635 if (token.type == '(' || token.type == '{' || token.type == '[')
10636 eat_until_matching_token(token.type);
10642 static void parse_externals(void)
10644 add_anchor_token('}');
10645 add_anchor_token(T_EOF);
10648 unsigned char token_anchor_copy[T_LAST_TOKEN];
10649 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10652 while (token.type != T_EOF && token.type != '}') {
10654 bool anchor_leak = false;
10655 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10656 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10658 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10659 anchor_leak = true;
10662 if (in_gcc_extension) {
10663 errorf(HERE, "Leaked __extension__");
10664 anchor_leak = true;
10674 rem_anchor_token(T_EOF);
10675 rem_anchor_token('}');
10679 * Parse a translation unit.
10681 static void parse_translation_unit(void)
10683 add_anchor_token(T_EOF);
10688 if (token.type == T_EOF)
10691 errorf(HERE, "stray %K outside of function", &token);
10692 if (token.type == '(' || token.type == '{' || token.type == '[')
10693 eat_until_matching_token(token.type);
10701 * @return the translation unit or NULL if errors occurred.
10703 void start_parsing(void)
10705 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10706 label_stack = NEW_ARR_F(stack_entry_t, 0);
10707 diagnostic_count = 0;
10711 type_set_output(stderr);
10712 ast_set_output(stderr);
10714 assert(unit == NULL);
10715 unit = allocate_ast_zero(sizeof(unit[0]));
10717 assert(file_scope == NULL);
10718 file_scope = &unit->scope;
10720 assert(current_scope == NULL);
10721 scope_push(&unit->scope);
10724 translation_unit_t *finish_parsing(void)
10726 /* do NOT use scope_pop() here, this will crash, will it by hand */
10727 assert(current_scope == &unit->scope);
10728 current_scope = NULL;
10730 assert(file_scope == &unit->scope);
10731 check_unused_globals();
10734 DEL_ARR_F(environment_stack);
10735 DEL_ARR_F(label_stack);
10737 translation_unit_t *result = unit;
10744 lookahead_bufpos = 0;
10745 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10748 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10749 parse_translation_unit();
10753 * Initialize the parser.
10755 void init_parser(void)
10757 sym_anonymous = symbol_table_insert("<anonymous>");
10759 if (c_mode & _MS) {
10760 /* add predefined symbols for extended-decl-modifier */
10761 sym_align = symbol_table_insert("align");
10762 sym_allocate = symbol_table_insert("allocate");
10763 sym_dllimport = symbol_table_insert("dllimport");
10764 sym_dllexport = symbol_table_insert("dllexport");
10765 sym_naked = symbol_table_insert("naked");
10766 sym_noinline = symbol_table_insert("noinline");
10767 sym_noreturn = symbol_table_insert("noreturn");
10768 sym_nothrow = symbol_table_insert("nothrow");
10769 sym_novtable = symbol_table_insert("novtable");
10770 sym_property = symbol_table_insert("property");
10771 sym_get = symbol_table_insert("get");
10772 sym_put = symbol_table_insert("put");
10773 sym_selectany = symbol_table_insert("selectany");
10774 sym_thread = symbol_table_insert("thread");
10775 sym_uuid = symbol_table_insert("uuid");
10776 sym_deprecated = symbol_table_insert("deprecated");
10777 sym_restrict = symbol_table_insert("restrict");
10778 sym_noalias = symbol_table_insert("noalias");
10780 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10782 init_expression_parsers();
10783 obstack_init(&temp_obst);
10785 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10786 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10790 * Terminate the parser.
10792 void exit_parser(void)
10794 obstack_free(&temp_obst, NULL);