OSDN Git Service

81f8f7e83268a9d4a05adcc9ce12c4f94172dac4
[pf3gnuchains/gcc-fork.git] / gcc / java / parse.y
1 /* Source code parsing and tree node generation for the GNU compiler
2    for the Java(TM) language.
3    Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003
4    Free Software Foundation, Inc.
5    Contributed by Alexandre Petit-Bianco (apbianco@cygnus.com)
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.
23
24 Java and all Java-based marks are trademarks or registered trademarks
25 of Sun Microsystems, Inc. in the United States and other countries.
26 The Free Software Foundation is independent of Sun Microsystems, Inc.  */
27
28 /* This file parses java source code and issues a tree node image
29 suitable for code generation (byte code and targeted CPU assembly
30 language).
31
32 The grammar conforms to the Java grammar described in "The Java(TM)
33 Language Specification. J. Gosling, B. Joy, G. Steele. Addison Wesley
34 1996, ISBN 0-201-63451-1"
35
36 The following modifications were brought to the original grammar:
37
38 method_body: added the rule '| block SC_TK'
39 static_initializer: added the rule 'static block SC_TK'.
40
41 Note: All the extra rules described above should go away when the
42       empty_statement rule will work.
43
44 statement_nsi: 'nsi' should be read no_short_if.
45
46 Some rules have been modified to support JDK1.1 inner classes
47 definitions and other extensions.  */
48
49 %{
50 #include "config.h"
51 #include "system.h"
52 #include "coretypes.h"
53 #include "tm.h"
54 #include <dirent.h>
55 #include "tree.h"
56 #include "rtl.h"
57 #include "real.h"
58 #include "obstack.h"
59 #include "toplev.h"
60 #include "flags.h"
61 #include "java-tree.h"
62 #include "jcf.h"
63 #include "lex.h"
64 #include "parse.h"
65 #include "zipfile.h"
66 #include "convert.h"
67 #include "buffer.h"
68 #include "xref.h"
69 #include "function.h"
70 #include "except.h"
71 #include "ggc.h"
72 #include "debug.h"
73 #include "tree-inline.h"
74 #include "cgraph.h"
75
76 /* Local function prototypes */
77 static char *java_accstring_lookup (int);
78 static void  classitf_redefinition_error (const char *,tree, tree, tree);
79 static void  variable_redefinition_error (tree, tree, tree, int);
80 static tree  create_class (int, tree, tree, tree);
81 static tree  create_interface (int, tree, tree);
82 static void  end_class_declaration (int);
83 static tree  find_field (tree, tree);
84 static tree lookup_field_wrapper (tree, tree);
85 static int   duplicate_declaration_error_p (tree, tree, tree);
86 static void  register_fields (int, tree, tree);
87 static tree parser_qualified_classname (tree);
88 static int  parser_check_super (tree, tree, tree);
89 static int  parser_check_super_interface (tree, tree, tree);
90 static void check_modifiers_consistency (int);
91 static tree lookup_cl (tree);
92 static tree lookup_java_method2 (tree, tree, int);
93 static tree method_header (int, tree, tree, tree);
94 static void fix_method_argument_names (tree ,tree);
95 static tree method_declarator (tree, tree);
96 static void parse_warning_context (tree cl, const char *msg, ...)
97   ATTRIBUTE_PRINTF_2;
98 static void issue_warning_error_from_context (tree, const char *msg, va_list)
99   ATTRIBUTE_PRINTF (2, 0);
100 static void parse_ctor_invocation_error (void);
101 static tree parse_jdk1_1_error (const char *);
102 static void complete_class_report_errors (jdep *);
103 static int process_imports (void);
104 static void read_import_dir (tree);
105 static int find_in_imports_on_demand (tree, tree);
106 static void find_in_imports (tree, tree);
107 static void check_inner_class_access (tree, tree, tree);
108 static int check_pkg_class_access (tree, tree, bool);
109 static void register_package (tree);
110 static tree resolve_package (tree, tree *, tree *);
111 static tree resolve_class (tree, tree, tree, tree);
112 static void declare_local_variables (int, tree, tree);
113 static void dump_java_tree (enum tree_dump_index, tree);
114 static void source_start_java_method (tree);
115 static void source_end_java_method (void);
116 static tree find_name_in_single_imports (tree);
117 static void check_abstract_method_header (tree);
118 static tree lookup_java_interface_method2 (tree, tree);
119 static tree resolve_expression_name (tree, tree *);
120 static tree maybe_create_class_interface_decl (tree, tree, tree, tree);
121 static int check_class_interface_creation (int, int, tree, tree, tree, tree);
122 static tree patch_method_invocation (tree, tree, tree, int, int *, tree *);
123 static int breakdown_qualified (tree *, tree *, tree);
124 static int in_same_package (tree, tree);
125 static tree resolve_and_layout (tree, tree);
126 static tree qualify_and_find (tree, tree, tree);
127 static tree resolve_no_layout (tree, tree);
128 static int invocation_mode (tree, int);
129 static tree find_applicable_accessible_methods_list (int, tree, tree, tree);
130 static void search_applicable_methods_list (int, tree, tree, tree, tree *, tree *);
131 static tree find_most_specific_methods_list (tree);
132 static int argument_types_convertible (tree, tree);
133 static tree patch_invoke (tree, tree, tree);
134 static int maybe_use_access_method (int, tree *, tree *);
135 static tree lookup_method_invoke (int, tree, tree, tree, tree);
136 static tree register_incomplete_type (int, tree, tree, tree);
137 static tree check_inner_circular_reference (tree, tree);
138 static tree check_circular_reference (tree);
139 static tree obtain_incomplete_type (tree);
140 static tree java_complete_lhs (tree);
141 static tree java_complete_tree (tree);
142 static tree maybe_generate_pre_expand_clinit (tree);
143 static int analyze_clinit_body (tree, tree);
144 static int maybe_yank_clinit (tree);
145 static void java_complete_expand_method (tree);
146 static void java_expand_method_bodies (tree);
147 static int  unresolved_type_p (tree, tree *);
148 static void create_jdep_list (struct parser_ctxt *);
149 static tree build_expr_block (tree, tree);
150 static tree enter_block (void);
151 static tree exit_block (void);
152 static tree lookup_name_in_blocks (tree);
153 static void maybe_absorb_scoping_blocks (void);
154 static tree build_method_invocation (tree, tree);
155 static tree build_new_invocation (tree, tree);
156 static tree build_assignment (int, int, tree, tree);
157 static tree build_binop (enum tree_code, int, tree, tree);
158 static tree patch_assignment (tree, tree);
159 static tree patch_binop (tree, tree, tree);
160 static tree build_unaryop (int, int, tree);
161 static tree build_incdec (int, int, tree, int);
162 static tree patch_unaryop (tree, tree);
163 static tree build_cast (int, tree, tree);
164 static tree build_null_of_type (tree);
165 static tree patch_cast (tree, tree);
166 static int valid_ref_assignconv_cast_p (tree, tree, int);
167 static int valid_builtin_assignconv_identity_widening_p (tree, tree);
168 static int valid_cast_to_p (tree, tree);
169 static int valid_method_invocation_conversion_p (tree, tree);
170 static tree try_builtin_assignconv (tree, tree, tree);
171 static tree try_reference_assignconv (tree, tree);
172 static tree build_unresolved_array_type (tree);
173 static int build_type_name_from_array_name (tree, tree *);
174 static tree build_array_from_name (tree, tree, tree, tree *);
175 static tree build_array_ref (int, tree, tree);
176 static tree patch_array_ref (tree);
177 static tree make_qualified_name (tree, tree, int);
178 static tree merge_qualified_name (tree, tree);
179 static tree make_qualified_primary (tree, tree, int);
180 static int resolve_qualified_expression_name (tree, tree *, tree *, tree *);
181 static void qualify_ambiguous_name (tree);
182 static tree resolve_field_access (tree, tree *, tree *);
183 static tree build_newarray_node (tree, tree, int);
184 static tree patch_newarray (tree);
185 static tree resolve_type_during_patch (tree);
186 static tree build_this (int);
187 static tree build_wfl_wrap (tree, int);
188 static tree build_return (int, tree);
189 static tree patch_return (tree);
190 static tree maybe_access_field (tree, tree, tree);
191 static int complete_function_arguments (tree);
192 static int check_for_static_method_reference (tree, tree, tree, tree, tree);
193 static int not_accessible_p (tree, tree, tree, int);
194 static void check_deprecation (tree, tree);
195 static int class_in_current_package (tree);
196 static tree build_if_else_statement (int, tree, tree, tree);
197 static tree patch_if_else_statement (tree);
198 static tree add_stmt_to_compound (tree, tree, tree);
199 static tree add_stmt_to_block (tree, tree, tree);
200 static tree patch_exit_expr (tree);
201 static tree build_labeled_block (int, tree);
202 static tree finish_labeled_statement (tree, tree);
203 static tree build_bc_statement (int, int, tree);
204 static tree patch_bc_statement (tree);
205 static tree patch_loop_statement (tree);
206 static tree build_new_loop (tree);
207 static tree build_loop_body (int, tree, int);
208 static tree finish_loop_body (int, tree, tree, int);
209 static tree build_debugable_stmt (int, tree);
210 static tree finish_for_loop (int, tree, tree, tree);
211 static tree patch_switch_statement (tree);
212 static tree string_constant_concatenation (tree, tree);
213 static tree build_string_concatenation (tree, tree);
214 static tree patch_string_cst (tree);
215 static tree patch_string (tree);
216 static tree encapsulate_with_try_catch (int, tree, tree, tree);
217 static tree build_assertion (int, tree, tree);
218 static tree build_try_statement (int, tree, tree);
219 static tree build_try_finally_statement (int, tree, tree);
220 static tree patch_try_statement (tree);
221 static tree patch_synchronized_statement (tree, tree);
222 static tree patch_throw_statement (tree, tree);
223 static void check_thrown_exceptions (int, tree, tree);
224 static int check_thrown_exceptions_do (tree);
225 static void purge_unchecked_exceptions (tree);
226 static bool ctors_unchecked_throws_clause_p (tree);
227 static void check_concrete_throws_clauses (tree, tree, tree, tree);
228 static void check_throws_clauses (tree, tree, tree);
229 static void finish_method_declaration (tree);
230 static tree build_super_invocation (tree);
231 static int verify_constructor_circularity (tree, tree);
232 static char *constructor_circularity_msg (tree, tree);
233 static tree build_this_super_qualified_invocation (int, tree, tree, int, int);
234 static const char *get_printable_method_name (tree);
235 static tree patch_conditional_expr (tree, tree, tree);
236 static tree generate_finit (tree);
237 static tree generate_instinit (tree);
238 static tree build_instinit_invocation (tree);
239 static void fix_constructors (tree);
240 static tree build_alias_initializer_parameter_list (int, tree, tree, int *);
241 static tree craft_constructor (tree, tree);
242 static int verify_constructor_super (tree);
243 static tree create_artificial_method (tree, int, tree, tree, tree);
244 static void start_artificial_method_body (tree);
245 static void end_artificial_method_body (tree);
246 static int check_method_redefinition (tree, tree);
247 static int check_method_types_complete (tree);
248 static bool hack_is_accessible_p (tree, tree);
249 static void java_check_regular_methods (tree);
250 static void check_interface_throws_clauses (tree, tree);
251 static void java_check_abstract_methods (tree);
252 static void unreachable_stmt_error (tree);
253 static int not_accessible_field_error (tree, tree);
254 static tree find_expr_with_wfl (tree);
255 static void missing_return_error (tree);
256 static tree build_new_array_init (int, tree);
257 static tree patch_new_array_init (tree, tree);
258 static tree maybe_build_array_element_wfl (tree);
259 static int array_constructor_check_entry (tree, tree);
260 static const char *purify_type_name (const char *);
261 static tree fold_constant_for_init (tree, tree);
262 static tree strip_out_static_field_access_decl (tree);
263 static jdeplist *reverse_jdep_list (struct parser_ctxt *);
264 static void static_ref_err (tree, tree, tree);
265 static void parser_add_interface (tree, tree, tree);
266 static void add_superinterfaces (tree, tree);
267 static tree jdep_resolve_class (jdep *);
268 static int note_possible_classname (const char *, int);
269 static void java_complete_expand_classes (void);
270 static void java_complete_expand_class (tree);
271 static void java_complete_expand_methods (tree);
272 static tree cut_identifier_in_qualified (tree);
273 static tree java_stabilize_reference (tree);
274 static tree do_unary_numeric_promotion (tree);
275 static char * operator_string (tree);
276 static tree do_merge_string_cste (tree, const char *, int, int);
277 static tree merge_string_cste (tree, tree, int);
278 static tree java_refold (tree);
279 static int java_decl_equiv (tree, tree);
280 static int binop_compound_p (enum tree_code);
281 static tree search_loop (tree);
282 static int labeled_block_contains_loop_p (tree, tree);
283 static int check_abstract_method_definitions (int, tree, tree);
284 static void java_check_abstract_method_definitions (tree);
285 static void java_debug_context_do (int);
286 static void java_parser_context_push_initialized_field (void);
287 static void java_parser_context_pop_initialized_field (void);
288 static tree reorder_static_initialized (tree);
289 static void java_parser_context_suspend (void);
290 static void java_parser_context_resume (void);
291 static int pop_current_osb (struct parser_ctxt *);
292
293 /* JDK 1.1 work. FIXME */
294
295 static tree maybe_make_nested_class_name (tree);
296 static int make_nested_class_name (tree);
297 static void set_nested_class_simple_name_value (tree, int);
298 static void link_nested_class_to_enclosing (void);
299 static tree resolve_inner_class (htab_t, tree, tree *, tree *, tree);
300 static tree find_as_inner_class (tree, tree, tree);
301 static tree find_as_inner_class_do (tree, tree);
302 static int check_inner_class_redefinition (tree, tree);
303
304 static tree build_thisn_assign (void);
305 static tree build_current_thisn (tree);
306 static tree build_access_to_thisn (tree, tree, int);
307 static tree maybe_build_thisn_access_method (tree);
308
309 static tree build_outer_field_access (tree, tree);
310 static tree build_outer_field_access_methods (tree);
311 static tree build_outer_field_access_expr (int, tree, tree,
312                                                   tree, tree);
313 static tree build_outer_method_access_method (tree);
314 static tree build_new_access_id (void);
315 static tree build_outer_field_access_method (tree, tree, tree,
316                                                     tree, tree);
317
318 static int outer_field_access_p (tree, tree);
319 static int outer_field_expanded_access_p (tree, tree *,
320                                                  tree *, tree *);
321 static tree outer_field_access_fix (tree, tree, tree);
322 static tree build_incomplete_class_ref (int, tree);
323 static tree patch_incomplete_class_ref (tree);
324 static tree create_anonymous_class (int, tree);
325 static void patch_anonymous_class (tree, tree, tree);
326 static void add_inner_class_fields (tree, tree);
327
328 static tree build_dot_class_method (tree);
329 static tree build_dot_class_method_invocation (tree, tree);
330 static void create_new_parser_context (int);
331 static tree maybe_build_class_init_for_field (tree, tree);
332
333 static int attach_init_test_initialization_flags (void **, void *);
334 static int emit_test_initialization (void **, void *);
335
336 static char *string_convert_int_cst (tree);
337
338 /* Number of error found so far. */
339 int java_error_count;
340 /* Number of warning found so far. */
341 int java_warning_count;
342 /* Tell when not to fold, when doing xrefs */
343 int do_not_fold;
344 /* Cyclic inheritance report, as it can be set by layout_class */
345 const char *cyclic_inheritance_report;
346
347 /* The current parser context */
348 struct parser_ctxt *ctxp;
349
350 /* List of things that were analyzed for which code will be generated */
351 struct parser_ctxt *ctxp_for_generation = NULL;
352
353 /* binop_lookup maps token to tree_code. It is used where binary
354    operations are involved and required by the parser. RDIV_EXPR
355    covers both integral/floating point division. The code is changed
356    once the type of both operator is worked out.  */
357
358 static const enum tree_code binop_lookup[19] =
359   {
360     PLUS_EXPR, MINUS_EXPR, MULT_EXPR, RDIV_EXPR, TRUNC_MOD_EXPR,
361     LSHIFT_EXPR, RSHIFT_EXPR, URSHIFT_EXPR,
362     BIT_AND_EXPR, BIT_XOR_EXPR, BIT_IOR_EXPR,
363     TRUTH_ANDIF_EXPR, TRUTH_ORIF_EXPR,
364     EQ_EXPR, NE_EXPR, GT_EXPR, GE_EXPR, LT_EXPR, LE_EXPR,
365    };
366 #define BINOP_LOOKUP(VALUE)                                             \
367   binop_lookup [((VALUE) - PLUS_TK) % ARRAY_SIZE (binop_lookup)]
368
369 /* This is the end index for binary operators that can also be used
370    in compound assignments. */
371 #define BINOP_COMPOUND_CANDIDATES 11
372
373 /* The "$L" identifier we use to create labels.  */
374 static GTY(()) tree label_id;
375
376 /* The "StringBuffer" identifier used for the String `+' operator. */
377 static GTY(()) tree wfl_string_buffer;
378
379 /* The "append" identifier used for String `+' operator.  */
380 static GTY(()) tree wfl_append;
381
382 /* The "toString" identifier used for String `+' operator. */
383 static GTY(()) tree wfl_to_string;
384
385 /* The "java.lang" import qualified name.  */
386 static GTY(()) tree java_lang_id;
387
388 /* The generated `inst$' identifier used for generated enclosing
389    instance/field access functions.  */
390 static GTY(()) tree inst_id;
391
392 /* Context and flag for static blocks */
393 static GTY(()) tree current_static_block;
394
395 /* The generated `write_parm_value$' identifier.  */
396 static GTY(()) tree wpv_id;
397
398 /* The list of all packages we've seen so far */
399 static GTY(()) tree package_list;
400
401 /* Hold THIS for the scope of the current method decl.  */
402 static GTY(()) tree current_this;
403
404 /* Hold a list of catch clauses list. The first element of this list is
405    the list of the catch clauses of the currently analyzed try block. */
406 static GTY(()) tree currently_caught_type_list;
407
408 /* This holds a linked list of all the case labels for the current
409    switch statement.  It is only used when checking to see if there
410    are duplicate labels.  FIXME: probably this should just be attached
411    to the switch itself; then it could be referenced via
412    `ctxp->current_loop'.  */
413 static GTY(()) tree case_label_list;
414
415 /* Anonymous class counter. Will be reset to 1 every time a non
416    anonymous class gets created. */
417 static int anonymous_class_counter = 1;
418
419 static GTY(()) tree src_parse_roots[1];
420
421 /* All classes seen from source code */
422 #define gclass_list src_parse_roots[0]
423
424 /* Check modifiers. If one doesn't fit, retrieve it in its declaration
425    line and point it out.  */
426 /* Should point out the one that don't fit. ASCII/unicode, going
427    backward. FIXME */
428
429 #define check_modifiers(__message, __value, __mask) do {        \
430   if ((__value) & ~(__mask))                                    \
431     {                                                           \
432       size_t i, remainder = (__value) & ~(__mask);              \
433       for (i = 0; i < ARRAY_SIZE (ctxp->modifier_ctx); i++)     \
434         if ((1 << i) & remainder)                               \
435           parse_error_context (ctxp->modifier_ctx [i], (__message), \
436                                java_accstring_lookup (1 << i)); \
437     }                                                           \
438 } while (0)
439
440 %}
441
442 %union {
443   tree node;
444   int sub_token;
445   struct {
446     int token;
447     int location;
448   } operator;
449   int value;
450 }
451
452 %{
453 #include "lex.c"
454 %}
455
456 %pure_parser
457
458 /* Things defined here have to match the order of what's in the
459    binop_lookup table.  */
460
461 %token   PLUS_TK         MINUS_TK        MULT_TK         DIV_TK    REM_TK
462 %token   LS_TK           SRS_TK          ZRS_TK
463 %token   AND_TK          XOR_TK          OR_TK
464 %token   BOOL_AND_TK BOOL_OR_TK
465 %token   EQ_TK NEQ_TK GT_TK GTE_TK LT_TK LTE_TK
466
467 /* This maps to the same binop_lookup entry than the token above */
468
469 %token   PLUS_ASSIGN_TK  MINUS_ASSIGN_TK MULT_ASSIGN_TK DIV_ASSIGN_TK
470 %token   REM_ASSIGN_TK
471 %token   LS_ASSIGN_TK    SRS_ASSIGN_TK   ZRS_ASSIGN_TK
472 %token   AND_ASSIGN_TK   XOR_ASSIGN_TK   OR_ASSIGN_TK
473
474
475 /* Modifier TOKEN have to be kept in this order. Don't scramble it */
476
477 %token   PUBLIC_TK       PRIVATE_TK         PROTECTED_TK
478 %token   STATIC_TK       FINAL_TK           SYNCHRONIZED_TK
479 %token   VOLATILE_TK     TRANSIENT_TK       NATIVE_TK
480 %token   PAD_TK          ABSTRACT_TK        STRICT_TK
481 %token   MODIFIER_TK
482
483 /* Keep those two in order, too */
484 %token   DECR_TK INCR_TK
485
486 /* From now one, things can be in any order */
487
488 %token   DEFAULT_TK      IF_TK              THROW_TK
489 %token   BOOLEAN_TK      DO_TK              IMPLEMENTS_TK
490 %token   THROWS_TK       BREAK_TK           IMPORT_TK
491 %token   ELSE_TK         INSTANCEOF_TK      RETURN_TK
492 %token   VOID_TK         CATCH_TK           INTERFACE_TK
493 %token   CASE_TK         EXTENDS_TK         FINALLY_TK
494 %token   SUPER_TK        WHILE_TK           CLASS_TK
495 %token   SWITCH_TK       CONST_TK           TRY_TK
496 %token   FOR_TK          NEW_TK             CONTINUE_TK
497 %token   GOTO_TK         PACKAGE_TK         THIS_TK
498 %token   ASSERT_TK
499
500 %token   BYTE_TK         SHORT_TK           INT_TK            LONG_TK
501 %token   CHAR_TK         INTEGRAL_TK
502
503 %token   FLOAT_TK        DOUBLE_TK          FP_TK
504
505 %token   ID_TK
506
507 %token   REL_QM_TK         REL_CL_TK NOT_TK  NEG_TK
508
509 %token   ASSIGN_ANY_TK   ASSIGN_TK
510 %token   OP_TK  CP_TK  OCB_TK  CCB_TK  OSB_TK  CSB_TK  SC_TK  C_TK DOT_TK
511
512 %token   STRING_LIT_TK   CHAR_LIT_TK        INT_LIT_TK        FP_LIT_TK
513 %token   TRUE_TK         FALSE_TK           BOOL_LIT_TK       NULL_TK
514
515 %type    <value>        modifiers MODIFIER_TK final synchronized
516
517 %type    <node>         super ID_TK identifier
518 %type    <node>         name simple_name qualified_name
519 %type    <node>         type_declaration compilation_unit
520                         field_declaration method_declaration extends_interfaces
521                         interfaces interface_type_list
522                         import_declarations package_declaration
523                         type_declarations interface_body
524                         interface_member_declaration constant_declaration
525                         interface_member_declarations interface_type
526                         abstract_method_declaration
527 %type    <node>         class_body_declaration class_member_declaration
528                         static_initializer constructor_declaration block
529 %type    <node>         class_body_declarations constructor_header
530 %type    <node>         class_or_interface_type class_type class_type_list
531                         constructor_declarator explicit_constructor_invocation
532 %type    <node>         dim_expr dim_exprs this_or_super throws
533
534 %type    <node>         variable_declarator_id variable_declarator
535                         variable_declarators variable_initializer
536                         variable_initializers constructor_body
537                         array_initializer
538
539 %type    <node>         class_body block_end constructor_block_end
540 %type    <node>         statement statement_without_trailing_substatement
541                         labeled_statement if_then_statement label_decl
542                         if_then_else_statement while_statement for_statement
543                         statement_nsi labeled_statement_nsi do_statement
544                         if_then_else_statement_nsi while_statement_nsi
545                         for_statement_nsi statement_expression_list for_init
546                         for_update statement_expression expression_statement
547                         primary_no_new_array expression primary
548                         array_creation_expression array_type
549                         class_instance_creation_expression field_access
550                         method_invocation array_access something_dot_new
551                         argument_list postfix_expression while_expression
552                         post_increment_expression post_decrement_expression
553                         unary_expression_not_plus_minus unary_expression
554                         pre_increment_expression pre_decrement_expression
555                         cast_expression
556                         multiplicative_expression additive_expression
557                         shift_expression relational_expression
558                         equality_expression and_expression
559                         exclusive_or_expression inclusive_or_expression
560                         conditional_and_expression conditional_or_expression
561                         conditional_expression assignment_expression
562                         left_hand_side assignment for_header for_begin
563                         constant_expression do_statement_begin empty_statement
564                         switch_statement synchronized_statement throw_statement
565                         try_statement assert_statement
566                         switch_expression switch_block
567                         catches catch_clause catch_clause_parameter finally
568                         anonymous_class_creation trap_overflow_corner_case
569 %type    <node>         return_statement break_statement continue_statement
570
571 %type    <operator>     ASSIGN_TK      MULT_ASSIGN_TK  DIV_ASSIGN_TK
572 %type    <operator>     REM_ASSIGN_TK  PLUS_ASSIGN_TK  MINUS_ASSIGN_TK
573 %type    <operator>     LS_ASSIGN_TK   SRS_ASSIGN_TK   ZRS_ASSIGN_TK
574 %type    <operator>     AND_ASSIGN_TK  XOR_ASSIGN_TK   OR_ASSIGN_TK
575 %type    <operator>     ASSIGN_ANY_TK  assignment_operator
576 %token   <operator>     EQ_TK GTE_TK ZRS_TK SRS_TK GT_TK LTE_TK LS_TK
577 %token   <operator>     BOOL_AND_TK AND_TK BOOL_OR_TK OR_TK INCR_TK PLUS_TK
578 %token   <operator>     DECR_TK MINUS_TK MULT_TK DIV_TK XOR_TK REM_TK NEQ_TK
579 %token   <operator>     NEG_TK REL_QM_TK REL_CL_TK NOT_TK LT_TK OCB_TK CCB_TK
580 %token   <operator>     OP_TK OSB_TK DOT_TK THROW_TK INSTANCEOF_TK
581 %type    <operator>     THIS_TK SUPER_TK RETURN_TK BREAK_TK CONTINUE_TK
582 %type    <operator>     CASE_TK DEFAULT_TK TRY_TK CATCH_TK SYNCHRONIZED_TK
583 %type    <operator>     NEW_TK ASSERT_TK
584
585 %type    <node>         method_body
586
587 %type    <node>         literal INT_LIT_TK FP_LIT_TK BOOL_LIT_TK CHAR_LIT_TK
588                         STRING_LIT_TK NULL_TK VOID_TK
589
590 %type    <node>         IF_TK WHILE_TK FOR_TK
591
592 %type    <node>         formal_parameter_list formal_parameter
593                         method_declarator method_header
594
595 %type    <node>         primitive_type reference_type type
596                         BOOLEAN_TK INTEGRAL_TK FP_TK
597
598 /* Added or modified JDK 1.1 rule types  */
599 %type    <node>         type_literals
600
601 %%
602 /* 19.2 Production from 2.3: The Syntactic Grammar  */
603 goal:  compilation_unit
604                 {}
605 ;
606
607 /* 19.3 Productions from 3: Lexical structure  */
608 literal:
609         INT_LIT_TK
610 |       FP_LIT_TK
611 |       BOOL_LIT_TK
612 |       CHAR_LIT_TK
613 |       STRING_LIT_TK
614 |       NULL_TK
615 ;
616
617 /* 19.4 Productions from 4: Types, Values and Variables  */
618 type:
619         primitive_type
620 |       reference_type
621 ;
622
623 primitive_type:
624         INTEGRAL_TK
625 |       FP_TK
626 |       BOOLEAN_TK
627 ;
628
629 reference_type:
630         class_or_interface_type
631 |       array_type
632 ;
633
634 class_or_interface_type:
635         name
636 ;
637
638 class_type:
639         class_or_interface_type /* Default rule */
640 ;
641
642 interface_type:
643          class_or_interface_type
644 ;
645
646 array_type:
647         primitive_type dims
648                 {
649                   int osb = pop_current_osb (ctxp);
650                   tree t = build_java_array_type (($1), -1);
651                   while (--osb)
652                     t = build_unresolved_array_type (t);
653                   $$ = t;
654                 }
655 |       name dims
656                 {
657                   int osb = pop_current_osb (ctxp);
658                   tree t = $1;
659                   while (osb--)
660                     t = build_unresolved_array_type (t);
661                   $$ = t;
662                 }
663 ;
664
665 /* 19.5 Productions from 6: Names  */
666 name:
667         simple_name             /* Default rule */
668 |       qualified_name          /* Default rule */
669 ;
670
671 simple_name:
672         identifier              /* Default rule */
673 ;
674
675 qualified_name:
676         name DOT_TK identifier
677                 { $$ = make_qualified_name ($1, $3, $2.location); }
678 ;
679
680 identifier:
681         ID_TK
682 ;
683
684 /* 19.6: Production from 7: Packages  */
685 compilation_unit:
686                 {$$ = NULL;}
687 |       package_declaration
688 |       import_declarations
689 |       type_declarations
690 |       package_declaration import_declarations
691 |       package_declaration type_declarations
692 |       import_declarations type_declarations
693 |       package_declaration import_declarations type_declarations
694 ;
695
696 import_declarations:
697         import_declaration
698                 {
699                   $$ = NULL;
700                 }
701 |       import_declarations import_declaration
702                 {
703                   $$ = NULL;
704                 }
705 ;
706
707 type_declarations:
708         type_declaration
709 |       type_declarations type_declaration
710 ;
711
712 package_declaration:
713         PACKAGE_TK name SC_TK
714                 {
715                   ctxp->package = EXPR_WFL_NODE ($2);
716                   register_package (ctxp->package);
717                 }
718 |       PACKAGE_TK error
719                 {yyerror ("Missing name"); RECOVER;}
720 |       PACKAGE_TK name error
721                 {yyerror ("';' expected"); RECOVER;}
722 ;
723
724 import_declaration:
725         single_type_import_declaration
726 |       type_import_on_demand_declaration
727 ;
728
729 single_type_import_declaration:
730         IMPORT_TK name SC_TK
731                 {
732                   tree name = EXPR_WFL_NODE ($2), last_name;
733                   int   i = IDENTIFIER_LENGTH (name)-1;
734                   const char *last = &IDENTIFIER_POINTER (name)[i];
735                   while (last != IDENTIFIER_POINTER (name))
736                     {
737                       if (last [0] == '.')
738                         break;
739                       last--;
740                     }
741                   last_name = get_identifier (++last);
742                   if (IS_A_SINGLE_IMPORT_CLASSFILE_NAME_P (last_name))
743                     {
744                       tree err = find_name_in_single_imports (last_name);
745                       if (err && err != name)
746                         parse_error_context
747                           ($2, "Ambiguous class: `%s' and `%s'",
748                            IDENTIFIER_POINTER (name),
749                            IDENTIFIER_POINTER (err));
750                       else
751                         REGISTER_IMPORT ($2, last_name);
752                     }
753                   else
754                     REGISTER_IMPORT ($2, last_name);
755                 }
756 |       IMPORT_TK error
757                 {yyerror ("Missing name"); RECOVER;}
758 |       IMPORT_TK name error
759                 {yyerror ("';' expected"); RECOVER;}
760 ;
761
762 type_import_on_demand_declaration:
763         IMPORT_TK name DOT_TK MULT_TK SC_TK
764                 {
765                   tree name = EXPR_WFL_NODE ($2);
766                   tree it;
767                   /* Search for duplicates. */
768                   for (it = ctxp->import_demand_list; it; it = TREE_CHAIN (it))
769                     if (EXPR_WFL_NODE (TREE_PURPOSE (it)) == name)
770                       break;
771                   /* Don't import the same thing more than once, just ignore
772                      duplicates (7.5.2) */
773                   if (! it)
774                     {
775                       read_import_dir ($2);
776                       ctxp->import_demand_list =
777                         chainon (ctxp->import_demand_list,
778                                  build_tree_list ($2, NULL_TREE));
779                     }
780                 }
781 |       IMPORT_TK name DOT_TK error
782                 {yyerror ("'*' expected"); RECOVER;}
783 |       IMPORT_TK name DOT_TK MULT_TK error
784                 {yyerror ("';' expected"); RECOVER;}
785 ;
786
787 type_declaration:
788         class_declaration
789                 { end_class_declaration (0); }
790 |       interface_declaration
791                 { end_class_declaration (0); }
792 |       empty_statement
793 |       error
794                 {
795                   YYERROR_NOW;
796                   yyerror ("Class or interface declaration expected");
797                 }
798 ;
799
800 /* 19.7 Shortened from the original:
801    modifiers: modifier | modifiers modifier
802    modifier: any of public...  */
803 modifiers:
804         MODIFIER_TK
805                 {
806                   $$ = (1 << $1);
807                 }
808 |       modifiers MODIFIER_TK
809                 {
810                   int acc = (1 << $2);
811                   if ($$ & acc)
812                     parse_error_context
813                       (ctxp->modifier_ctx [$2], "Modifier `%s' declared twice",
814                        java_accstring_lookup (acc));
815                   else
816                     {
817                       $$ |= acc;
818                     }
819                 }
820 ;
821
822 /* 19.8.1 Production from $8.1: Class Declaration */
823 class_declaration:
824         modifiers CLASS_TK identifier super interfaces
825                 { create_class ($1, $3, $4, $5); }
826         class_body
827                 {;}
828 |       CLASS_TK identifier super interfaces
829                 { create_class (0, $2, $3, $4); }
830         class_body
831                 {;}
832 |       modifiers CLASS_TK error
833                 { yyerror ("Missing class name"); RECOVER; }
834 |       CLASS_TK error
835                 { yyerror ("Missing class name"); RECOVER; }
836 |       CLASS_TK identifier error
837                 {
838                   if (!ctxp->class_err) yyerror ("'{' expected");
839                   DRECOVER(class1);
840                 }
841 |       modifiers CLASS_TK identifier error
842                 { if (!ctxp->class_err) yyerror ("'{' expected"); RECOVER; }
843 ;
844
845 super:
846                 { $$ = NULL; }
847 |       EXTENDS_TK class_type
848                 { $$ = $2; }
849 |       EXTENDS_TK class_type error
850                 {yyerror ("'{' expected"); ctxp->class_err=1;}
851 |       EXTENDS_TK error
852                 {yyerror ("Missing super class name"); ctxp->class_err=1;}
853 ;
854
855 interfaces:
856                 { $$ = NULL_TREE; }
857 |       IMPLEMENTS_TK interface_type_list
858                 { $$ = $2; }
859 |       IMPLEMENTS_TK error
860                 {
861                   ctxp->class_err=1;
862                   yyerror ("Missing interface name");
863                 }
864 ;
865
866 interface_type_list:
867         interface_type
868                 {
869                   ctxp->interface_number = 1;
870                   $$ = build_tree_list ($1, NULL_TREE);
871                 }
872 |       interface_type_list C_TK interface_type
873                 {
874                   ctxp->interface_number++;
875                   $$ = chainon ($1, build_tree_list ($3, NULL_TREE));
876                 }
877 |       interface_type_list C_TK error
878                 {yyerror ("Missing interface name"); RECOVER;}
879 ;
880
881 class_body:
882         OCB_TK CCB_TK
883                 {
884                   /* Store the location of the `}' when doing xrefs */
885                   if (flag_emit_xref)
886                     DECL_END_SOURCE_LINE (GET_CPC ()) =
887                       EXPR_WFL_ADD_COL ($2.location, 1);
888                   $$ = GET_CPC ();
889                 }
890 |       OCB_TK class_body_declarations CCB_TK
891                 {
892                   /* Store the location of the `}' when doing xrefs */
893                   if (flag_emit_xref)
894                     DECL_END_SOURCE_LINE (GET_CPC ()) =
895                       EXPR_WFL_ADD_COL ($3.location, 1);
896                   $$ = GET_CPC ();
897                 }
898 ;
899
900 class_body_declarations:
901         class_body_declaration
902 |       class_body_declarations class_body_declaration
903 ;
904
905 class_body_declaration:
906         class_member_declaration
907 |       static_initializer
908 |       constructor_declaration
909 |       block                   /* Added, JDK1.1, instance initializer */
910                 {
911                   if ($1 != empty_stmt_node)
912                     {
913                       TREE_CHAIN ($1) = CPC_INSTANCE_INITIALIZER_STMT (ctxp);
914                       SET_CPC_INSTANCE_INITIALIZER_STMT (ctxp, $1);
915                     }
916                 }
917 ;
918
919 class_member_declaration:
920         field_declaration
921 |       method_declaration
922 |       class_declaration       /* Added, JDK1.1 inner classes */
923                 { end_class_declaration (1); }
924 |       interface_declaration   /* Added, JDK1.1 inner interfaces */
925                 { end_class_declaration (1); }
926 |       empty_statement
927 ;
928
929 /* 19.8.2 Productions from 8.3: Field Declarations  */
930 field_declaration:
931         type variable_declarators SC_TK
932                 { register_fields (0, $1, $2); }
933 |       modifiers type variable_declarators SC_TK
934                 {
935                   check_modifiers
936                     ("Illegal modifier `%s' for field declaration",
937                      $1, FIELD_MODIFIERS);
938                   check_modifiers_consistency ($1);
939                   register_fields ($1, $2, $3);
940                 }
941 ;
942
943 variable_declarators:
944         /* Should we use build_decl_list () instead ? FIXME */
945         variable_declarator     /* Default rule */
946 |       variable_declarators C_TK variable_declarator
947                 { $$ = chainon ($1, $3); }
948 |       variable_declarators C_TK error
949                 {yyerror ("Missing term"); RECOVER;}
950 ;
951
952 variable_declarator:
953         variable_declarator_id
954                 { $$ = build_tree_list ($1, NULL_TREE); }
955 |       variable_declarator_id ASSIGN_TK variable_initializer
956                 {
957                   if (java_error_count)
958                     $3 = NULL_TREE;
959                   $$ = build_tree_list
960                     ($1, build_assignment ($2.token, $2.location, $1, $3));
961                 }
962 |       variable_declarator_id ASSIGN_TK error
963                 {
964                   yyerror ("Missing variable initializer");
965                   $$ = build_tree_list ($1, NULL_TREE);
966                   RECOVER;
967                 }
968 |       variable_declarator_id ASSIGN_TK variable_initializer error
969                 {
970                   yyerror ("';' expected");
971                   $$ = build_tree_list ($1, NULL_TREE);
972                   RECOVER;
973                 }
974 ;
975
976 variable_declarator_id:
977         identifier
978 |       variable_declarator_id OSB_TK CSB_TK
979                 { $$ = build_unresolved_array_type ($1); }
980 |       identifier error
981                 {yyerror ("Invalid declaration"); DRECOVER(vdi);}
982 |       variable_declarator_id OSB_TK error
983                 {
984                   yyerror ("']' expected");
985                   DRECOVER(vdi);
986                 }
987 |       variable_declarator_id CSB_TK error
988                 {yyerror ("Unbalanced ']'"); DRECOVER(vdi);}
989 ;
990
991 variable_initializer:
992         expression
993 |       array_initializer
994 ;
995
996 /* 19.8.3 Productions from 8.4: Method Declarations  */
997 method_declaration:
998         method_header
999                 {
1000                   current_function_decl = $1;
1001                   if (current_function_decl
1002                       && TREE_CODE (current_function_decl) == FUNCTION_DECL)
1003                     source_start_java_method (current_function_decl);
1004                   else
1005                     current_function_decl = NULL_TREE;
1006                 }
1007         method_body
1008                 { finish_method_declaration ($3); }
1009 |       method_header error
1010                 {YYNOT_TWICE yyerror ("'{' expected"); RECOVER;}
1011 ;
1012
1013 method_header:
1014         type method_declarator throws
1015                 { $$ = method_header (0, $1, $2, $3); }
1016 |       VOID_TK method_declarator throws
1017                 { $$ = method_header (0, void_type_node, $2, $3); }
1018 |       modifiers type method_declarator throws
1019                 { $$ = method_header ($1, $2, $3, $4); }
1020 |       modifiers VOID_TK method_declarator throws
1021                 { $$ = method_header ($1, void_type_node, $3, $4); }
1022 |       type error
1023                 {
1024                   yyerror ("Invalid method declaration, method name required");
1025                   RECOVER;
1026                 }
1027 |       modifiers type error
1028                 {
1029                   yyerror ("Identifier expected");
1030                   RECOVER;
1031                 }
1032 |       VOID_TK error
1033                 {
1034                   yyerror ("Identifier expected");
1035                   RECOVER;
1036                 }
1037 |       modifiers VOID_TK error
1038                 {
1039                   yyerror ("Identifier expected");
1040                   RECOVER;
1041                 }
1042 |       modifiers error
1043                 {
1044                   yyerror ("Invalid method declaration, return type required");
1045                   RECOVER;
1046                 }
1047 ;
1048
1049 method_declarator:
1050         identifier OP_TK CP_TK
1051                 {
1052                   ctxp->formal_parameter_number = 0;
1053                   $$ = method_declarator ($1, NULL_TREE);
1054                 }
1055 |       identifier OP_TK formal_parameter_list CP_TK
1056                 { $$ = method_declarator ($1, $3); }
1057 |       method_declarator OSB_TK CSB_TK
1058                 {
1059                   EXPR_WFL_LINECOL (wfl_operator) = $2.location;
1060                   TREE_PURPOSE ($1) =
1061                     build_unresolved_array_type (TREE_PURPOSE ($1));
1062                   parse_warning_context
1063                     (wfl_operator,
1064                      "Discouraged form of returned type specification");
1065                 }
1066 |       identifier OP_TK error
1067                 {yyerror ("')' expected"); DRECOVER(method_declarator);}
1068 |       method_declarator OSB_TK error
1069                 {yyerror ("']' expected"); RECOVER;}
1070 ;
1071
1072 formal_parameter_list:
1073         formal_parameter
1074                 {
1075                   ctxp->formal_parameter_number = 1;
1076                 }
1077 |       formal_parameter_list C_TK formal_parameter
1078                 {
1079                   ctxp->formal_parameter_number += 1;
1080                   $$ = chainon ($1, $3);
1081                 }
1082 |       formal_parameter_list C_TK error
1083                 { yyerror ("Missing formal parameter term"); RECOVER; }
1084 ;
1085
1086 formal_parameter:
1087         type variable_declarator_id
1088                 {
1089                   $$ = build_tree_list ($2, $1);
1090                 }
1091 |       final type variable_declarator_id /* Added, JDK1.1 final parms */
1092                 {
1093                   $$ = build_tree_list ($3, $2);
1094                   ARG_FINAL_P ($$) = 1;
1095                 }
1096 |       type error
1097                 {
1098                   yyerror ("Missing identifier"); RECOVER;
1099                   $$ = NULL_TREE;
1100                 }
1101 |       final type error
1102                 {
1103                   yyerror ("Missing identifier"); RECOVER;
1104                   $$ = NULL_TREE;
1105                 }
1106 ;
1107
1108 final:
1109         modifiers
1110                 {
1111                   check_modifiers ("Illegal modifier `%s'. Only `final' was expected here",
1112                                    $1, ACC_FINAL);
1113                   if ($1 != ACC_FINAL)
1114                     MODIFIER_WFL (FINAL_TK) = build_wfl_node (NULL_TREE);
1115                 }
1116 ;
1117
1118 throws:
1119                 { $$ = NULL_TREE; }
1120 |       THROWS_TK class_type_list
1121                 { $$ = $2; }
1122 |       THROWS_TK error
1123                 {yyerror ("Missing class type term"); RECOVER;}
1124 ;
1125
1126 class_type_list:
1127         class_type
1128                 { $$ = build_tree_list ($1, $1); }
1129 |       class_type_list C_TK class_type
1130                 { $$ = tree_cons ($3, $3, $1); }
1131 |       class_type_list C_TK error
1132                 {yyerror ("Missing class type term"); RECOVER;}
1133 ;
1134
1135 method_body:
1136         block
1137 |       SC_TK { $$ = NULL_TREE; }
1138 ;
1139
1140 /* 19.8.4 Productions from 8.5: Static Initializers  */
1141 static_initializer:
1142         static block
1143                 {
1144                   TREE_CHAIN ($2) = CPC_STATIC_INITIALIZER_STMT (ctxp);
1145                   SET_CPC_STATIC_INITIALIZER_STMT (ctxp, $2);
1146                   current_static_block = NULL_TREE;
1147                 }
1148 ;
1149
1150 static:                         /* Test lval.sub_token here */
1151         modifiers
1152                 {
1153                   check_modifiers ("Illegal modifier `%s' for static initializer", $1, ACC_STATIC);
1154                   /* Can't have a static initializer in an innerclass */
1155                   if ($1 | ACC_STATIC &&
1156                       GET_CPC_LIST () && !TOPLEVEL_CLASS_DECL_P (GET_CPC ()))
1157                     parse_error_context
1158                       (MODIFIER_WFL (STATIC_TK),
1159                        "Can't define static initializer in class `%s'. Static initializer can only be defined in top-level classes",
1160                        IDENTIFIER_POINTER (DECL_NAME (GET_CPC ())));
1161                   SOURCE_FRONTEND_DEBUG (("Modifiers: %d", $1));
1162                 }
1163 ;
1164
1165 /* 19.8.5 Productions from 8.6: Constructor Declarations  */
1166 constructor_declaration:
1167         constructor_header
1168                 {
1169                   current_function_decl = $1;
1170                   source_start_java_method (current_function_decl);
1171                 }
1172         constructor_body
1173                 { finish_method_declaration ($3); }
1174 ;
1175
1176 constructor_header:
1177         constructor_declarator throws
1178                 { $$ = method_header (0, NULL_TREE, $1, $2); }
1179 |       modifiers constructor_declarator throws
1180                 { $$ = method_header ($1, NULL_TREE, $2, $3); }
1181 ;
1182
1183 constructor_declarator:
1184         simple_name OP_TK CP_TK
1185                 {
1186                   ctxp->formal_parameter_number = 0;
1187                   $$ = method_declarator ($1, NULL_TREE);
1188                 }
1189 |       simple_name OP_TK formal_parameter_list CP_TK
1190                 { $$ = method_declarator ($1, $3); }
1191 ;
1192
1193 constructor_body:
1194         /* Unlike regular method, we always need a complete (empty)
1195            body so we can safely perform all the required code
1196            addition (super invocation and field initialization) */
1197         block_begin constructor_block_end
1198                 {
1199                   BLOCK_EXPR_BODY ($2) = empty_stmt_node;
1200                   $$ = $2;
1201                 }
1202 |       block_begin explicit_constructor_invocation constructor_block_end
1203                 { $$ = $3; }
1204 |       block_begin block_statements constructor_block_end
1205                 { $$ = $3; }
1206 |       block_begin explicit_constructor_invocation block_statements constructor_block_end
1207                 { $$ = $4; }
1208 ;
1209
1210 constructor_block_end:
1211         block_end
1212 ;
1213
1214 /* Error recovery for that rule moved down expression_statement: rule.  */
1215 explicit_constructor_invocation:
1216         this_or_super OP_TK CP_TK SC_TK
1217                 {
1218                   $$ = build_method_invocation ($1, NULL_TREE);
1219                   $$ = build_debugable_stmt (EXPR_WFL_LINECOL ($1), $$);
1220                   $$ = java_method_add_stmt (current_function_decl, $$);
1221                 }
1222 |       this_or_super OP_TK argument_list CP_TK SC_TK
1223                 {
1224                   $$ = build_method_invocation ($1, $3);
1225                   $$ = build_debugable_stmt (EXPR_WFL_LINECOL ($1), $$);
1226                   $$ = java_method_add_stmt (current_function_decl, $$);
1227                 }
1228         /* Added, JDK1.1 inner classes. Modified because the rule
1229            'primary' couldn't work.  */
1230 |       name DOT_TK SUPER_TK OP_TK argument_list CP_TK SC_TK
1231                 {$$ = parse_jdk1_1_error ("explicit constructor invocation"); }
1232 |       name DOT_TK SUPER_TK OP_TK CP_TK SC_TK
1233                 {$$ = parse_jdk1_1_error ("explicit constructor invocation"); }
1234 ;
1235
1236 this_or_super:                  /* Added, simplifies error diagnostics */
1237         THIS_TK
1238                 {
1239                   tree wfl = build_wfl_node (this_identifier_node);
1240                   EXPR_WFL_LINECOL (wfl) = $1.location;
1241                   $$ = wfl;
1242                 }
1243 |       SUPER_TK
1244                 {
1245                   tree wfl = build_wfl_node (super_identifier_node);
1246                   EXPR_WFL_LINECOL (wfl) = $1.location;
1247                   $$ = wfl;
1248                 }
1249 ;
1250
1251 /* 19.9 Productions from 9: Interfaces  */
1252 /* 19.9.1 Productions from 9.1: Interfaces Declarations  */
1253 interface_declaration:
1254         INTERFACE_TK identifier
1255                 { create_interface (0, $2, NULL_TREE); }
1256         interface_body
1257                 { ; }
1258 |       modifiers INTERFACE_TK identifier
1259                 { create_interface ($1, $3, NULL_TREE); }
1260         interface_body
1261                 { ; }
1262 |       INTERFACE_TK identifier extends_interfaces
1263                 { create_interface (0, $2, $3); }
1264         interface_body
1265                 { ; }
1266 |       modifiers INTERFACE_TK identifier extends_interfaces
1267                 { create_interface ($1, $3, $4); }
1268         interface_body
1269                 { ; }
1270 |       INTERFACE_TK identifier error
1271                 { yyerror ("'{' expected"); RECOVER; }
1272 |       modifiers INTERFACE_TK identifier error
1273                 { yyerror ("'{' expected"); RECOVER; }
1274 ;
1275
1276 extends_interfaces:
1277         EXTENDS_TK interface_type
1278                 {
1279                   ctxp->interface_number = 1;
1280                   $$ = build_tree_list ($2, NULL_TREE);
1281                 }
1282 |       extends_interfaces C_TK interface_type
1283                 {
1284                   ctxp->interface_number++;
1285                   $$ = chainon ($1, build_tree_list ($3, NULL_TREE));
1286                 }
1287 |       EXTENDS_TK error
1288                 {yyerror ("Invalid interface type"); RECOVER;}
1289 |       extends_interfaces C_TK error
1290                 {yyerror ("Missing term"); RECOVER;}
1291 ;
1292
1293 interface_body:
1294         OCB_TK CCB_TK
1295                 { $$ = NULL_TREE; }
1296 |       OCB_TK interface_member_declarations CCB_TK
1297                 { $$ = NULL_TREE; }
1298 ;
1299
1300 interface_member_declarations:
1301         interface_member_declaration
1302 |       interface_member_declarations interface_member_declaration
1303 ;
1304
1305 interface_member_declaration:
1306         constant_declaration
1307 |       abstract_method_declaration
1308 |       class_declaration       /* Added, JDK1.1 inner classes */
1309                 { end_class_declaration (1); }
1310 |       interface_declaration   /* Added, JDK1.1 inner interfaces */
1311                 { end_class_declaration (1); }
1312 ;
1313
1314 constant_declaration:
1315         field_declaration
1316 ;
1317
1318 abstract_method_declaration:
1319         method_header SC_TK
1320                 {
1321                   check_abstract_method_header ($1);
1322                   current_function_decl = NULL_TREE; /* FIXME ? */
1323                 }
1324 |       method_header error
1325                 {yyerror ("';' expected"); RECOVER;}
1326 ;
1327
1328 /* 19.10 Productions from 10: Arrays  */
1329 array_initializer:
1330         OCB_TK CCB_TK
1331                 { $$ = build_new_array_init ($1.location, NULL_TREE); }
1332 |       OCB_TK C_TK CCB_TK
1333                 { $$ = build_new_array_init ($1.location, NULL_TREE); }
1334 |       OCB_TK variable_initializers CCB_TK
1335                 { $$ = build_new_array_init ($1.location, $2); }
1336 |       OCB_TK variable_initializers C_TK CCB_TK
1337                 { $$ = build_new_array_init ($1.location, $2); }
1338 ;
1339
1340 variable_initializers:
1341         variable_initializer
1342                 {
1343                   $$ = tree_cons (maybe_build_array_element_wfl ($1),
1344                                   $1, NULL_TREE);
1345                 }
1346 |       variable_initializers C_TK variable_initializer
1347                 {
1348                   $$ = tree_cons (maybe_build_array_element_wfl ($3), $3, $1);
1349                 }
1350 |       variable_initializers C_TK error
1351                 {yyerror ("Missing term"); RECOVER;}
1352 ;
1353
1354 /* 19.11 Production from 14: Blocks and Statements  */
1355 block:
1356         block_begin block_end
1357                 { $$ = $2; }
1358 |       block_begin block_statements block_end
1359                 { $$ = $3; }
1360 ;
1361
1362 block_begin:
1363         OCB_TK
1364                 { enter_block (); }
1365 ;
1366
1367 block_end:
1368         CCB_TK
1369                 {
1370                   maybe_absorb_scoping_blocks ();
1371                   /* Store the location of the `}' when doing xrefs */
1372                   if (current_function_decl && flag_emit_xref)
1373                     DECL_END_SOURCE_LINE (current_function_decl) =
1374                       EXPR_WFL_ADD_COL ($1.location, 1);
1375                   $$ = exit_block ();
1376                   if (!BLOCK_SUBBLOCKS ($$))
1377                     BLOCK_SUBBLOCKS ($$) = empty_stmt_node;
1378                 }
1379 ;
1380
1381 block_statements:
1382         block_statement
1383 |       block_statements block_statement
1384 ;
1385
1386 block_statement:
1387         local_variable_declaration_statement
1388 |       statement
1389                 { java_method_add_stmt (current_function_decl, $1); }
1390 |       class_declaration       /* Added, JDK1.1 local classes */
1391                 {
1392                   LOCAL_CLASS_P (TREE_TYPE (GET_CPC ())) = 1;
1393                   end_class_declaration (1);
1394                 }
1395 ;
1396
1397 local_variable_declaration_statement:
1398         local_variable_declaration SC_TK /* Can't catch missing ';' here */
1399 ;
1400
1401 local_variable_declaration:
1402         type variable_declarators
1403                 { declare_local_variables (0, $1, $2); }
1404 |       final type variable_declarators /* Added, JDK1.1 final locals */
1405                 { declare_local_variables ($1, $2, $3); }
1406 ;
1407
1408 statement:
1409         statement_without_trailing_substatement
1410 |       labeled_statement
1411 |       if_then_statement
1412 |       if_then_else_statement
1413 |       while_statement
1414 |       for_statement
1415                 { $$ = exit_block (); }
1416 ;
1417
1418 statement_nsi:
1419         statement_without_trailing_substatement
1420 |       labeled_statement_nsi
1421 |       if_then_else_statement_nsi
1422 |       while_statement_nsi
1423 |       for_statement_nsi
1424                 { $$ = exit_block (); }
1425 ;
1426
1427 statement_without_trailing_substatement:
1428         block
1429 |       empty_statement
1430 |       expression_statement
1431 |       switch_statement
1432 |       do_statement
1433 |       break_statement
1434 |       continue_statement
1435 |       return_statement
1436 |       synchronized_statement
1437 |       throw_statement
1438 |       try_statement
1439 |       assert_statement
1440 ;
1441
1442 empty_statement:
1443         SC_TK
1444                 {
1445                   if (flag_extraneous_semicolon
1446                       && ! current_static_block
1447                       && (! current_function_decl ||
1448                           /* Verify we're not in a inner class declaration */
1449                           (GET_CPC () != TYPE_NAME
1450                            (DECL_CONTEXT (current_function_decl)))))
1451
1452                     {
1453                       EXPR_WFL_SET_LINECOL (wfl_operator, input_line, -1);
1454                       parse_warning_context (wfl_operator, "An empty declaration is a deprecated feature that should not be used");
1455                     }
1456                   $$ = empty_stmt_node;
1457                 }
1458 ;
1459
1460 label_decl:
1461         identifier REL_CL_TK
1462                 {
1463                   $$ = build_labeled_block (EXPR_WFL_LINECOL ($1),
1464                                             EXPR_WFL_NODE ($1));
1465                   pushlevel (2);
1466                   push_labeled_block ($$);
1467                   PUSH_LABELED_BLOCK ($$);
1468                 }
1469 ;
1470
1471 labeled_statement:
1472         label_decl statement
1473                 { $$ = finish_labeled_statement ($1, $2); }
1474 |       identifier error
1475                 {yyerror ("':' expected"); RECOVER;}
1476 ;
1477
1478 labeled_statement_nsi:
1479         label_decl statement_nsi
1480                 { $$ = finish_labeled_statement ($1, $2); }
1481 ;
1482
1483 /* We concentrate here a bunch of error handling rules that we couldn't write
1484    earlier, because expression_statement catches a missing ';'.  */
1485 expression_statement:
1486         statement_expression SC_TK
1487                 {
1488                   /* We have a statement. Generate a WFL around it so
1489                      we can debug it */
1490                   $$ = build_expr_wfl ($1, input_filename, input_line, 0);
1491                   /* We know we have a statement, so set the debug
1492                      info to be eventually generate here. */
1493                   $$ = JAVA_MAYBE_GENERATE_DEBUG_INFO ($$);
1494                 }
1495 |       error SC_TK
1496                 {
1497                   YYNOT_TWICE yyerror ("Invalid expression statement");
1498                   DRECOVER (expr_stmt);
1499                 }
1500 |       error OCB_TK
1501                 {
1502                   YYNOT_TWICE yyerror ("Invalid expression statement");
1503                   DRECOVER (expr_stmt);
1504                 }
1505 |       error CCB_TK
1506                 {
1507                   YYNOT_TWICE yyerror ("Invalid expression statement");
1508                   DRECOVER (expr_stmt);
1509                 }
1510 |       this_or_super OP_TK error
1511                 {yyerror ("')' expected"); RECOVER;}
1512 |       this_or_super OP_TK CP_TK error
1513                 {
1514                   parse_ctor_invocation_error ();
1515                   RECOVER;
1516                 }
1517 |       this_or_super OP_TK argument_list error
1518                 {yyerror ("')' expected"); RECOVER;}
1519 |       this_or_super OP_TK argument_list CP_TK error
1520                 {
1521                   parse_ctor_invocation_error ();
1522                   RECOVER;
1523                 }
1524 |       name DOT_TK SUPER_TK error
1525                 {yyerror ("'(' expected"); RECOVER;}
1526 |       name DOT_TK SUPER_TK OP_TK error
1527                 {yyerror ("')' expected"); RECOVER;}
1528 |       name DOT_TK SUPER_TK OP_TK argument_list error
1529                 {yyerror ("')' expected"); RECOVER;}
1530 |       name DOT_TK SUPER_TK OP_TK argument_list CP_TK error
1531                 {yyerror ("';' expected"); RECOVER;}
1532 |       name DOT_TK SUPER_TK OP_TK CP_TK error
1533                 {yyerror ("';' expected"); RECOVER;}
1534 ;
1535
1536 statement_expression:
1537         assignment
1538 |       pre_increment_expression
1539 |       pre_decrement_expression
1540 |       post_increment_expression
1541 |       post_decrement_expression
1542 |       method_invocation
1543 |       class_instance_creation_expression
1544 ;
1545
1546 if_then_statement:
1547         IF_TK OP_TK expression CP_TK statement
1548                 {
1549                   $$ = build_if_else_statement ($2.location, $3,
1550                                                 $5, NULL_TREE);
1551                 }
1552 |       IF_TK error
1553                 {yyerror ("'(' expected"); RECOVER;}
1554 |       IF_TK OP_TK error
1555                 {yyerror ("Missing term"); RECOVER;}
1556 |       IF_TK OP_TK expression error
1557                 {yyerror ("')' expected"); RECOVER;}
1558 ;
1559
1560 if_then_else_statement:
1561         IF_TK OP_TK expression CP_TK statement_nsi ELSE_TK statement
1562                 { $$ = build_if_else_statement ($2.location, $3, $5, $7); }
1563 ;
1564
1565 if_then_else_statement_nsi:
1566         IF_TK OP_TK expression CP_TK statement_nsi ELSE_TK statement_nsi
1567                 { $$ = build_if_else_statement ($2.location, $3, $5, $7); }
1568 ;
1569
1570 switch_statement:
1571         switch_expression
1572                 {
1573                   enter_block ();
1574                 }
1575         switch_block
1576                 {
1577                   /* Make into "proper list" of COMPOUND_EXPRs.
1578                      I.e. make the last statement also have its own
1579                      COMPOUND_EXPR. */
1580                   maybe_absorb_scoping_blocks ();
1581                   TREE_OPERAND ($1, 1) = exit_block ();
1582                   $$ = build_debugable_stmt (EXPR_WFL_LINECOL ($1), $1);
1583                 }
1584 ;
1585
1586 switch_expression:
1587         SWITCH_TK OP_TK expression CP_TK
1588                 {
1589                   $$ = build (SWITCH_EXPR, NULL_TREE, $3, NULL_TREE);
1590                   EXPR_WFL_LINECOL ($$) = $2.location;
1591                 }
1592 |       SWITCH_TK error
1593                 {yyerror ("'(' expected"); RECOVER;}
1594 |       SWITCH_TK OP_TK error
1595                 {yyerror ("Missing term or ')'"); DRECOVER(switch_statement);}
1596 |       SWITCH_TK OP_TK expression CP_TK error
1597                 {yyerror ("'{' expected"); RECOVER;}
1598 ;
1599
1600 /* Default assignment is there to avoid type node on switch_block
1601    node. */
1602
1603 switch_block:
1604         OCB_TK CCB_TK
1605                 { $$ = NULL_TREE; }
1606 |       OCB_TK switch_labels CCB_TK
1607                 { $$ = NULL_TREE; }
1608 |       OCB_TK switch_block_statement_groups CCB_TK
1609                 { $$ = NULL_TREE; }
1610 |       OCB_TK switch_block_statement_groups switch_labels CCB_TK
1611                 { $$ = NULL_TREE; }
1612 ;
1613
1614 switch_block_statement_groups:
1615         switch_block_statement_group
1616 |       switch_block_statement_groups switch_block_statement_group
1617 ;
1618
1619 switch_block_statement_group:
1620         switch_labels block_statements
1621 ;
1622
1623 switch_labels:
1624         switch_label
1625 |       switch_labels switch_label
1626 ;
1627
1628 switch_label:
1629         CASE_TK constant_expression REL_CL_TK
1630                 {
1631                   tree lab = build1 (CASE_EXPR, NULL_TREE, $2);
1632                   EXPR_WFL_LINECOL (lab) = $1.location;
1633                   java_method_add_stmt (current_function_decl, lab);
1634                 }
1635 |       DEFAULT_TK REL_CL_TK
1636                 {
1637                   tree lab = build (DEFAULT_EXPR, NULL_TREE, NULL_TREE);
1638                   EXPR_WFL_LINECOL (lab) = $1.location;
1639                   java_method_add_stmt (current_function_decl, lab);
1640                 }
1641 |       CASE_TK error
1642                 {yyerror ("Missing or invalid constant expression"); RECOVER;}
1643 |       CASE_TK constant_expression error
1644                 {yyerror ("':' expected"); RECOVER;}
1645 |       DEFAULT_TK error
1646                 {yyerror ("':' expected"); RECOVER;}
1647 ;
1648
1649 while_expression:
1650         WHILE_TK OP_TK expression CP_TK
1651                 {
1652                   tree body = build_loop_body ($2.location, $3, 0);
1653                   $$ = build_new_loop (body);
1654                 }
1655 ;
1656
1657 while_statement:
1658         while_expression statement
1659                 { $$ = finish_loop_body (0, NULL_TREE, $2, 0); }
1660 |       WHILE_TK error
1661                 {YYERROR_NOW; yyerror ("'(' expected"); RECOVER;}
1662 |       WHILE_TK OP_TK error
1663                 {yyerror ("Missing term and ')' expected"); RECOVER;}
1664 |       WHILE_TK OP_TK expression error
1665                 {yyerror ("')' expected"); RECOVER;}
1666 ;
1667
1668 while_statement_nsi:
1669         while_expression statement_nsi
1670                 { $$ = finish_loop_body (0, NULL_TREE, $2, 0); }
1671 ;
1672
1673 do_statement_begin:
1674         DO_TK
1675                 {
1676                   tree body = build_loop_body (0, NULL_TREE, 1);
1677                   $$ = build_new_loop (body);
1678                 }
1679         /* Need error handing here. FIXME */
1680 ;
1681
1682 do_statement:
1683         do_statement_begin statement WHILE_TK OP_TK expression CP_TK SC_TK
1684                 { $$ = finish_loop_body ($4.location, $5, $2, 1); }
1685 ;
1686
1687 for_statement:
1688         for_begin SC_TK expression SC_TK for_update CP_TK statement
1689                 {
1690                   if (TREE_CODE_CLASS (TREE_CODE ($3)) == 'c')
1691                     $3 = build_wfl_node ($3);
1692                   $$ = finish_for_loop (EXPR_WFL_LINECOL ($3), $3, $5, $7);
1693                 }
1694 |       for_begin SC_TK SC_TK for_update CP_TK statement
1695                 {
1696                   $$ = finish_for_loop (0, NULL_TREE, $4, $6);
1697                   /* We have not condition, so we get rid of the EXIT_EXPR */
1698                   LOOP_EXPR_BODY_CONDITION_EXPR (LOOP_EXPR_BODY ($$), 0) =
1699                     empty_stmt_node;
1700                 }
1701 |       for_begin SC_TK error
1702                 {yyerror ("Invalid control expression"); RECOVER;}
1703 |       for_begin SC_TK expression SC_TK error
1704                 {yyerror ("Invalid update expression"); RECOVER;}
1705 |       for_begin SC_TK SC_TK error
1706                 {yyerror ("Invalid update expression"); RECOVER;}
1707 ;
1708
1709 for_statement_nsi:
1710         for_begin SC_TK expression SC_TK for_update CP_TK statement_nsi
1711                 { $$ = finish_for_loop (EXPR_WFL_LINECOL ($3), $3, $5, $7);}
1712 |       for_begin SC_TK SC_TK for_update CP_TK statement_nsi
1713                 {
1714                   $$ = finish_for_loop (0, NULL_TREE, $4, $6);
1715                   /* We have not condition, so we get rid of the EXIT_EXPR */
1716                   LOOP_EXPR_BODY_CONDITION_EXPR (LOOP_EXPR_BODY ($$), 0) =
1717                     empty_stmt_node;
1718                 }
1719 ;
1720
1721 for_header:
1722         FOR_TK OP_TK
1723                 {
1724                   /* This scope defined for local variable that may be
1725                      defined within the scope of the for loop */
1726                   enter_block ();
1727                 }
1728 |       FOR_TK error
1729                 {yyerror ("'(' expected"); DRECOVER(for_1);}
1730 |       FOR_TK OP_TK error
1731                 {yyerror ("Invalid init statement"); RECOVER;}
1732 ;
1733
1734 for_begin:
1735         for_header for_init
1736                 {
1737                   /* We now declare the loop body. The loop is
1738                      declared as a for loop. */
1739                   tree body = build_loop_body (0, NULL_TREE, 0);
1740                   $$ =  build_new_loop (body);
1741                   FOR_LOOP_P ($$) = 1;
1742                   /* The loop is added to the current block the for
1743                      statement is defined within */
1744                   java_method_add_stmt (current_function_decl, $$);
1745                 }
1746 ;
1747 for_init:                       /* Can be empty */
1748                 { $$ = empty_stmt_node; }
1749 |       statement_expression_list
1750                 {
1751                   /* Init statement recorded within the previously
1752                      defined block scope */
1753                   $$ = java_method_add_stmt (current_function_decl, $1);
1754                 }
1755 |       local_variable_declaration
1756                 {
1757                   /* Local variable are recorded within the previously
1758                      defined block scope */
1759                   $$ = NULL_TREE;
1760                 }
1761 |       statement_expression_list error
1762                 {yyerror ("';' expected"); DRECOVER(for_init_1);}
1763 ;
1764
1765 for_update:                     /* Can be empty */
1766                 {$$ = empty_stmt_node;}
1767 |       statement_expression_list
1768                 { $$ = build_debugable_stmt (BUILD_LOCATION (), $1); }
1769 ;
1770
1771 statement_expression_list:
1772         statement_expression
1773                 { $$ = add_stmt_to_compound (NULL_TREE, NULL_TREE, $1); }
1774 |       statement_expression_list C_TK statement_expression
1775                 { $$ = add_stmt_to_compound ($1, NULL_TREE, $3); }
1776 |       statement_expression_list C_TK error
1777                 {yyerror ("Missing term"); RECOVER;}
1778 ;
1779
1780 break_statement:
1781         BREAK_TK SC_TK
1782                 { $$ = build_bc_statement ($1.location, 1, NULL_TREE); }
1783 |       BREAK_TK identifier SC_TK
1784                 { $$ = build_bc_statement ($1.location, 1, $2); }
1785 |       BREAK_TK error
1786                 {yyerror ("Missing term"); RECOVER;}
1787 |       BREAK_TK identifier error
1788                 {yyerror ("';' expected"); RECOVER;}
1789 ;
1790
1791 continue_statement:
1792         CONTINUE_TK SC_TK
1793                 { $$ = build_bc_statement ($1.location, 0, NULL_TREE); }
1794 |       CONTINUE_TK identifier SC_TK
1795                 { $$ = build_bc_statement ($1.location, 0, $2); }
1796 |       CONTINUE_TK error
1797                 {yyerror ("Missing term"); RECOVER;}
1798 |       CONTINUE_TK identifier error
1799                 {yyerror ("';' expected"); RECOVER;}
1800 ;
1801
1802 return_statement:
1803         RETURN_TK SC_TK
1804                 { $$ = build_return ($1.location, NULL_TREE); }
1805 |       RETURN_TK expression SC_TK
1806                 { $$ = build_return ($1.location, $2); }
1807 |       RETURN_TK error
1808                 {yyerror ("Missing term"); RECOVER;}
1809 |       RETURN_TK expression error
1810                 {yyerror ("';' expected"); RECOVER;}
1811 ;
1812
1813 throw_statement:
1814         THROW_TK expression SC_TK
1815                 {
1816                   $$ = build1 (THROW_EXPR, NULL_TREE, $2);
1817                   EXPR_WFL_LINECOL ($$) = $1.location;
1818                 }
1819 |       THROW_TK error
1820                 {yyerror ("Missing term"); RECOVER;}
1821 |       THROW_TK expression error
1822                 {yyerror ("';' expected"); RECOVER;}
1823 ;
1824
1825 assert_statement:
1826         ASSERT_TK expression REL_CL_TK expression SC_TK
1827                 {
1828                   $$ = build_assertion ($1.location, $2, $4);
1829                 }
1830 |       ASSERT_TK expression SC_TK
1831                 {
1832                   $$ = build_assertion ($1.location, $2, NULL_TREE);
1833                 }
1834 |       ASSERT_TK error
1835                 {yyerror ("Missing term"); RECOVER;}
1836 |       ASSERT_TK expression error
1837                 {yyerror ("';' expected"); RECOVER;}
1838 ;
1839
1840 synchronized_statement:
1841         synchronized OP_TK expression CP_TK block
1842                 {
1843                   $$ = build (SYNCHRONIZED_EXPR, NULL_TREE, $3, $5);
1844                   EXPR_WFL_LINECOL ($$) =
1845                     EXPR_WFL_LINECOL (MODIFIER_WFL (SYNCHRONIZED_TK));
1846                 }
1847 |       synchronized OP_TK expression CP_TK error
1848                 {yyerror ("'{' expected"); RECOVER;}
1849 |       synchronized error
1850                 {yyerror ("'(' expected"); RECOVER;}
1851 |       synchronized OP_TK error CP_TK
1852                 {yyerror ("Missing term"); RECOVER;}
1853 |       synchronized OP_TK error
1854                 {yyerror ("Missing term"); RECOVER;}
1855 ;
1856
1857 synchronized:
1858         modifiers
1859                 {
1860                   check_modifiers (
1861              "Illegal modifier `%s'. Only `synchronized' was expected here",
1862                                    $1, ACC_SYNCHRONIZED);
1863                   if ($1 != ACC_SYNCHRONIZED)
1864                     MODIFIER_WFL (SYNCHRONIZED_TK) =
1865                       build_wfl_node (NULL_TREE);
1866                 }
1867 ;
1868
1869 try_statement:
1870         TRY_TK block catches
1871                 { $$ = build_try_statement ($1.location, $2, $3); }
1872 |       TRY_TK block finally
1873                 { $$ = build_try_finally_statement ($1.location, $2, $3); }
1874 |       TRY_TK block catches finally
1875                 { $$ = build_try_finally_statement
1876                     ($1.location, build_try_statement ($1.location,
1877                                                        $2, $3), $4);
1878                 }
1879 |       TRY_TK error
1880                 {yyerror ("'{' expected"); DRECOVER (try_statement);}
1881 ;
1882
1883 catches:
1884         catch_clause
1885 |       catches catch_clause
1886                 {
1887                   TREE_CHAIN ($2) = $1;
1888                   $$ = $2;
1889                 }
1890 ;
1891
1892 catch_clause:
1893         catch_clause_parameter block
1894                 {
1895                   java_method_add_stmt (current_function_decl, $2);
1896                   exit_block ();
1897                   $$ = $1;
1898                 }
1899 ;
1900
1901 catch_clause_parameter:
1902         CATCH_TK OP_TK formal_parameter CP_TK
1903                 {
1904                   /* We add a block to define a scope for
1905                      formal_parameter (CCBP). The formal parameter is
1906                      declared initialized by the appropriate function
1907                      call */
1908                   tree ccpb = enter_block ();
1909                   tree init = build_assignment
1910                     (ASSIGN_TK, $2.location, TREE_PURPOSE ($3),
1911                      build (JAVA_EXC_OBJ_EXPR, ptr_type_node));
1912                   declare_local_variables (0, TREE_VALUE ($3),
1913                                            build_tree_list (TREE_PURPOSE ($3),
1914                                                             init));
1915                   $$ = build1 (CATCH_EXPR, NULL_TREE, ccpb);
1916                   EXPR_WFL_LINECOL ($$) = $1.location;
1917                 }
1918 |       CATCH_TK error
1919                 {yyerror ("'(' expected"); RECOVER; $$ = NULL_TREE;}
1920 |       CATCH_TK OP_TK error
1921                 {
1922                   yyerror ("Missing term or ')' expected");
1923                   RECOVER; $$ = NULL_TREE;
1924                 }
1925 |       CATCH_TK OP_TK error CP_TK /* That's for () */
1926                 {yyerror ("Missing term"); RECOVER; $$ = NULL_TREE;}
1927 ;
1928
1929 finally:
1930         FINALLY_TK block
1931                 { $$ = $2; }
1932 |       FINALLY_TK error
1933                 {yyerror ("'{' expected"); RECOVER; }
1934 ;
1935
1936 /* 19.12 Production from 15: Expressions  */
1937 primary:
1938         primary_no_new_array
1939 |       array_creation_expression
1940 ;
1941
1942 primary_no_new_array:
1943         literal
1944 |       THIS_TK
1945                 { $$ = build_this ($1.location); }
1946 |       OP_TK expression CP_TK
1947                 {$$ = $2;}
1948 |       class_instance_creation_expression
1949 |       field_access
1950 |       method_invocation
1951 |       array_access
1952 |       type_literals
1953         /* Added, JDK1.1 inner classes. Documentation is wrong
1954            refering to a 'ClassName' (class_name) rule that doesn't
1955            exist. Used name: instead.  */
1956 |       name DOT_TK THIS_TK
1957                 {
1958                   tree wfl = build_wfl_node (this_identifier_node);
1959                   $$ = make_qualified_primary ($1, wfl, EXPR_WFL_LINECOL ($1));
1960                 }
1961 |       OP_TK expression error
1962                 {yyerror ("')' expected"); RECOVER;}
1963 |       name DOT_TK error
1964                 {yyerror ("'class' or 'this' expected" ); RECOVER;}
1965 |       primitive_type DOT_TK error
1966                 {yyerror ("'class' expected" ); RECOVER;}
1967 |       VOID_TK DOT_TK error
1968                 {yyerror ("'class' expected" ); RECOVER;}
1969 ;
1970
1971 type_literals:
1972         name DOT_TK CLASS_TK
1973                 { $$ = build_incomplete_class_ref ($2.location, $1); }
1974 |       array_type DOT_TK CLASS_TK
1975                 { $$ = build_incomplete_class_ref ($2.location, $1); }
1976 |       primitive_type DOT_TK CLASS_TK
1977                 { $$ = build_incomplete_class_ref ($2.location, $1); }
1978 |       VOID_TK DOT_TK CLASS_TK
1979                 {
1980                    $$ = build_incomplete_class_ref ($2.location,
1981                                                    void_type_node);
1982                 }
1983 ;
1984
1985 class_instance_creation_expression:
1986         NEW_TK class_type OP_TK argument_list CP_TK
1987                 { $$ = build_new_invocation ($2, $4); }
1988 |       NEW_TK class_type OP_TK CP_TK
1989                 { $$ = build_new_invocation ($2, NULL_TREE); }
1990 |       anonymous_class_creation
1991         /* Added, JDK1.1 inner classes, modified to use name or
1992            primary instead of primary solely which couldn't work in
1993            all situations.  */
1994 |       something_dot_new identifier OP_TK CP_TK
1995                 {
1996                   tree ctor = build_new_invocation ($2, NULL_TREE);
1997                   $$ = make_qualified_primary ($1, ctor,
1998                                                EXPR_WFL_LINECOL ($1));
1999                 }
2000 |       something_dot_new identifier OP_TK CP_TK class_body
2001 |       something_dot_new identifier OP_TK argument_list CP_TK
2002                 {
2003                   tree ctor = build_new_invocation ($2, $4);
2004                   $$ = make_qualified_primary ($1, ctor,
2005                                                EXPR_WFL_LINECOL ($1));
2006                 }
2007 |       something_dot_new identifier OP_TK argument_list CP_TK class_body
2008 |       NEW_TK error SC_TK
2009                 {yyerror ("'(' expected"); DRECOVER(new_1);}
2010 |       NEW_TK class_type error
2011                 {yyerror ("'(' expected"); RECOVER;}
2012 |       NEW_TK class_type OP_TK error
2013                 {yyerror ("')' or term expected"); RECOVER;}
2014 |       NEW_TK class_type OP_TK argument_list error
2015                 {yyerror ("')' expected"); RECOVER;}
2016 |       something_dot_new error
2017                 {YYERROR_NOW; yyerror ("Identifier expected"); RECOVER;}
2018 |       something_dot_new identifier error
2019                 {yyerror ("'(' expected"); RECOVER;}
2020 ;
2021
2022 /* Created after JDK1.1 rules originally added to
2023    class_instance_creation_expression, but modified to use
2024    'class_type' instead of 'TypeName' (type_name) which is mentioned
2025    in the documentation but doesn't exist. */
2026
2027 anonymous_class_creation:
2028         NEW_TK class_type OP_TK argument_list CP_TK
2029                 { create_anonymous_class ($1.location, $2); }
2030         class_body
2031                 {
2032                   tree id = build_wfl_node (DECL_NAME (GET_CPC ()));
2033                   EXPR_WFL_LINECOL (id) = EXPR_WFL_LINECOL ($2);
2034
2035                   end_class_declaration (1);
2036
2037                   /* Now we can craft the new expression */
2038                   $$ = build_new_invocation (id, $4);
2039
2040                   /* Note that we can't possibly be here if
2041                      `class_type' is an interface (in which case the
2042                      anonymous class extends Object and implements
2043                      `class_type', hence its constructor can't have
2044                      arguments.) */
2045
2046                   /* Otherwise, the innerclass must feature a
2047                      constructor matching `argument_list'. Anonymous
2048                      classes are a bit special: it's impossible to
2049                      define constructor for them, hence constructors
2050                      must be generated following the hints provided by
2051                      the `new' expression. Whether a super constructor
2052                      of that nature exists or not is to be verified
2053                      later on in verify_constructor_super.
2054
2055                      It's during the expansion of a `new' statement
2056                      refering to an anonymous class that a ctor will
2057                      be generated for the anonymous class, with the
2058                      right arguments. */
2059
2060                 }
2061 |       NEW_TK class_type OP_TK CP_TK
2062                 { create_anonymous_class ($1.location, $2); }
2063         class_body
2064                 {
2065                   tree id = build_wfl_node (DECL_NAME (GET_CPC ()));
2066                   EXPR_WFL_LINECOL (id) = EXPR_WFL_LINECOL ($2);
2067
2068                   end_class_declaration (1);
2069
2070                   /* Now we can craft the new expression. The
2071                      statement doesn't need to be remember so that a
2072                      constructor can be generated, since its signature
2073                      is already known. */
2074                   $$ = build_new_invocation (id, NULL_TREE);
2075                 }
2076 ;
2077
2078 something_dot_new:              /* Added, not part of the specs. */
2079         name DOT_TK NEW_TK
2080                 { $$ = $1; }
2081 |       primary DOT_TK NEW_TK
2082                 { $$ = $1; }
2083 ;
2084
2085 argument_list:
2086         expression
2087                 {
2088                   $$ = tree_cons (NULL_TREE, $1, NULL_TREE);
2089                   ctxp->formal_parameter_number = 1;
2090                 }
2091 |       argument_list C_TK expression
2092                 {
2093                   ctxp->formal_parameter_number += 1;
2094                   $$ = tree_cons (NULL_TREE, $3, $1);
2095                 }
2096 |       argument_list C_TK error
2097                 {yyerror ("Missing term"); RECOVER;}
2098 ;
2099
2100 array_creation_expression:
2101         NEW_TK primitive_type dim_exprs
2102                 { $$ = build_newarray_node ($2, $3, 0); }
2103 |       NEW_TK class_or_interface_type dim_exprs
2104                 { $$ = build_newarray_node ($2, $3, 0); }
2105 |       NEW_TK primitive_type dim_exprs dims
2106                 { $$ = build_newarray_node ($2, $3, pop_current_osb (ctxp));}
2107 |       NEW_TK class_or_interface_type dim_exprs dims
2108                 { $$ = build_newarray_node ($2, $3, pop_current_osb (ctxp));}
2109         /* Added, JDK1.1 anonymous array. Initial documentation rule
2110            modified */
2111 |       NEW_TK class_or_interface_type dims array_initializer
2112                 {
2113                   char *sig;
2114                   int osb = pop_current_osb (ctxp);
2115                   while (osb--)
2116                     obstack_grow (&temporary_obstack, "[]", 2);
2117                   obstack_1grow (&temporary_obstack, '\0');
2118                   sig = obstack_finish (&temporary_obstack);
2119                   $$ = build (NEW_ANONYMOUS_ARRAY_EXPR, NULL_TREE,
2120                               $2, get_identifier (sig), $4);
2121                 }
2122 |       NEW_TK primitive_type dims array_initializer
2123                 {
2124                   int osb = pop_current_osb (ctxp);
2125                   tree type = $2;
2126                   while (osb--)
2127                     type = build_java_array_type (type, -1);
2128                   $$ = build (NEW_ANONYMOUS_ARRAY_EXPR, NULL_TREE,
2129                               build_pointer_type (type), NULL_TREE, $4);
2130                 }
2131 |       NEW_TK error CSB_TK
2132                 {yyerror ("'[' expected"); DRECOVER ("]");}
2133 |       NEW_TK error OSB_TK
2134                 {yyerror ("']' expected"); RECOVER;}
2135 ;
2136
2137 dim_exprs:
2138         dim_expr
2139                 { $$ = build_tree_list (NULL_TREE, $1); }
2140 |       dim_exprs dim_expr
2141                 { $$ = tree_cons (NULL_TREE, $2, $$); }
2142 ;
2143
2144 dim_expr:
2145         OSB_TK expression CSB_TK
2146                 {
2147                   if (JNUMERIC_TYPE_P (TREE_TYPE ($2)))
2148                     {
2149                       $2 = build_wfl_node ($2);
2150                       TREE_TYPE ($2) = NULL_TREE;
2151                     }
2152                   EXPR_WFL_LINECOL ($2) = $1.location;
2153                   $$ = $2;
2154                 }
2155 |       OSB_TK expression error
2156                 {yyerror ("']' expected"); RECOVER;}
2157 |       OSB_TK error
2158                 {
2159                   yyerror ("Missing term");
2160                   yyerror ("']' expected");
2161                   RECOVER;
2162                 }
2163 ;
2164
2165 dims:
2166         OSB_TK CSB_TK
2167                 {
2168                   int allocate = 0;
2169                   /* If not initialized, allocate memory for the osb
2170                      numbers stack */
2171                   if (!ctxp->osb_limit)
2172                     {
2173                       allocate = ctxp->osb_limit = 32;
2174                       ctxp->osb_depth = -1;
2175                     }
2176                   /* If capacity overflown, reallocate a bigger chunk */
2177                   else if (ctxp->osb_depth+1 == ctxp->osb_limit)
2178                     allocate = ctxp->osb_limit << 1;
2179
2180                   if (allocate)
2181                     {
2182                       allocate *= sizeof (int);
2183                       if (ctxp->osb_number)
2184                         ctxp->osb_number = xrealloc (ctxp->osb_number,
2185                                                      allocate);
2186                       else
2187                         ctxp->osb_number = xmalloc (allocate);
2188                     }
2189                   ctxp->osb_depth++;
2190                   CURRENT_OSB (ctxp) = 1;
2191                 }
2192 |       dims OSB_TK CSB_TK
2193                 { CURRENT_OSB (ctxp)++; }
2194 |       dims OSB_TK error
2195                 { yyerror ("']' expected"); RECOVER;}
2196 ;
2197
2198 field_access:
2199         primary DOT_TK identifier
2200                 { $$ = make_qualified_primary ($1, $3, $2.location); }
2201                 /*  FIXME - REWRITE TO:
2202                 { $$ = build_binop (COMPONENT_REF, $2.location, $1, $3); } */
2203 |       SUPER_TK DOT_TK identifier
2204                 {
2205                   tree super_wfl = build_wfl_node (super_identifier_node);
2206                   EXPR_WFL_LINECOL (super_wfl) = $1.location;
2207                   $$ = make_qualified_name (super_wfl, $3, $2.location);
2208                 }
2209 |       SUPER_TK error
2210                 {yyerror ("Field expected"); DRECOVER (super_field_acces);}
2211 ;
2212
2213 method_invocation:
2214         name OP_TK CP_TK
2215                 { $$ = build_method_invocation ($1, NULL_TREE); }
2216 |       name OP_TK argument_list CP_TK
2217                 { $$ = build_method_invocation ($1, $3); }
2218 |       primary DOT_TK identifier OP_TK CP_TK
2219                 {
2220                   if (TREE_CODE ($1) == THIS_EXPR)
2221                     $$ = build_this_super_qualified_invocation
2222                       (1, $3, NULL_TREE, 0, $2.location);
2223                   else
2224                     {
2225                       tree invok = build_method_invocation ($3, NULL_TREE);
2226                       $$ = make_qualified_primary ($1, invok, $2.location);
2227                     }
2228                 }
2229 |       primary DOT_TK identifier OP_TK argument_list CP_TK
2230                 {
2231                   if (TREE_CODE ($1) == THIS_EXPR)
2232                     $$ = build_this_super_qualified_invocation
2233                       (1, $3, $5, 0, $2.location);
2234                   else
2235                     {
2236                       tree invok = build_method_invocation ($3, $5);
2237                       $$ = make_qualified_primary ($1, invok, $2.location);
2238                     }
2239                 }
2240 |       SUPER_TK DOT_TK identifier OP_TK CP_TK
2241                 {
2242                   $$ = build_this_super_qualified_invocation
2243                     (0, $3, NULL_TREE, $1.location, $2.location);
2244                 }
2245 |       SUPER_TK DOT_TK identifier OP_TK argument_list CP_TK
2246                 {
2247                   $$ = build_this_super_qualified_invocation
2248                     (0, $3, $5, $1.location, $2.location);
2249                 }
2250         /* Screws up thing. I let it here until I'm convinced it can
2251            be removed. FIXME
2252 |       primary DOT_TK error
2253                 {yyerror ("'(' expected"); DRECOVER(bad);} */
2254 |       SUPER_TK DOT_TK error CP_TK
2255                 { yyerror ("'(' expected"); DRECOVER (method_invocation); }
2256 |       SUPER_TK DOT_TK error DOT_TK
2257                 { yyerror ("'(' expected"); DRECOVER (method_invocation); }
2258 ;
2259
2260 array_access:
2261         name OSB_TK expression CSB_TK
2262                 { $$ = build_array_ref ($2.location, $1, $3); }
2263 |       primary_no_new_array OSB_TK expression CSB_TK
2264                 { $$ = build_array_ref ($2.location, $1, $3); }
2265 |       name OSB_TK error
2266                 {
2267                   yyerror ("Missing term and ']' expected");
2268                   DRECOVER(array_access);
2269                 }
2270 |       name OSB_TK expression error
2271                 {
2272                   yyerror ("']' expected");
2273                   DRECOVER(array_access);
2274                 }
2275 |       primary_no_new_array OSB_TK error
2276                 {
2277                   yyerror ("Missing term and ']' expected");
2278                   DRECOVER(array_access);
2279                 }
2280 |       primary_no_new_array OSB_TK expression error
2281                 {
2282                   yyerror ("']' expected");
2283                   DRECOVER(array_access);
2284                 }
2285 ;
2286
2287 postfix_expression:
2288         primary
2289 |       name
2290 |       post_increment_expression
2291 |       post_decrement_expression
2292 ;
2293
2294 post_increment_expression:
2295         postfix_expression INCR_TK
2296                 { $$ = build_incdec ($2.token, $2.location, $1, 1); }
2297 ;
2298
2299 post_decrement_expression:
2300         postfix_expression DECR_TK
2301                 { $$ = build_incdec ($2.token, $2.location, $1, 1); }
2302 ;
2303
2304 trap_overflow_corner_case:
2305         pre_increment_expression
2306 |       pre_decrement_expression
2307 |       PLUS_TK unary_expression
2308                 {$$ = build_unaryop ($1.token, $1.location, $2); }
2309 |       unary_expression_not_plus_minus
2310 |       PLUS_TK error
2311                 {yyerror ("Missing term"); RECOVER}
2312 ;
2313
2314 unary_expression:
2315         trap_overflow_corner_case
2316                 {
2317                   error_if_numeric_overflow ($1);
2318                   $$ = $1;
2319                 }
2320 |       MINUS_TK trap_overflow_corner_case
2321                 {$$ = build_unaryop ($1.token, $1.location, $2); }
2322 |       MINUS_TK error
2323                 {yyerror ("Missing term"); RECOVER}
2324 ;
2325
2326 pre_increment_expression:
2327         INCR_TK unary_expression
2328                 {$$ = build_incdec ($1.token, $1.location, $2, 0); }
2329 |       INCR_TK error
2330                 {yyerror ("Missing term"); RECOVER}
2331 ;
2332
2333 pre_decrement_expression:
2334         DECR_TK unary_expression
2335                 {$$ = build_incdec ($1.token, $1.location, $2, 0); }
2336 |       DECR_TK error
2337                 {yyerror ("Missing term"); RECOVER}
2338 ;
2339
2340 unary_expression_not_plus_minus:
2341         postfix_expression
2342 |       NOT_TK unary_expression
2343                 {$$ = build_unaryop ($1.token, $1.location, $2); }
2344 |       NEG_TK unary_expression
2345                 {$$ = build_unaryop ($1.token, $1.location, $2); }
2346 |       cast_expression
2347 |       NOT_TK error
2348                 {yyerror ("Missing term"); RECOVER}
2349 |       NEG_TK error
2350                 {yyerror ("Missing term"); RECOVER}
2351 ;
2352
2353 cast_expression:                /* Error handling here is potentially weak */
2354         OP_TK primitive_type dims CP_TK unary_expression
2355                 {
2356                   tree type = $2;
2357                   int osb = pop_current_osb (ctxp);
2358                   while (osb--)
2359                     type = build_java_array_type (type, -1);
2360                   $$ = build_cast ($1.location, type, $5);
2361                 }
2362 |       OP_TK primitive_type CP_TK unary_expression
2363                 { $$ = build_cast ($1.location, $2, $4); }
2364 |       OP_TK expression CP_TK unary_expression_not_plus_minus
2365                 { $$ = build_cast ($1.location, $2, $4); }
2366 |       OP_TK name dims CP_TK unary_expression_not_plus_minus
2367                 {
2368                   const char *ptr;
2369                   int osb = pop_current_osb (ctxp);
2370                   obstack_grow (&temporary_obstack,
2371                                 IDENTIFIER_POINTER (EXPR_WFL_NODE ($2)),
2372                                 IDENTIFIER_LENGTH (EXPR_WFL_NODE ($2)));
2373                   while (osb--)
2374                     obstack_grow (&temporary_obstack, "[]", 2);
2375                   obstack_1grow (&temporary_obstack, '\0');
2376                   ptr = obstack_finish (&temporary_obstack);
2377                   EXPR_WFL_NODE ($2) = get_identifier (ptr);
2378                   $$ = build_cast ($1.location, $2, $5);
2379                 }
2380 |       OP_TK primitive_type OSB_TK error
2381                 {yyerror ("']' expected, invalid type expression");}
2382 |       OP_TK error
2383                 {
2384                   YYNOT_TWICE yyerror ("Invalid type expression"); RECOVER;
2385                   RECOVER;
2386                 }
2387 |       OP_TK primitive_type dims CP_TK error
2388                 {yyerror ("Missing term"); RECOVER;}
2389 |       OP_TK primitive_type CP_TK error
2390                 {yyerror ("Missing term"); RECOVER;}
2391 |       OP_TK name dims CP_TK error
2392                 {yyerror ("Missing term"); RECOVER;}
2393 ;
2394
2395 multiplicative_expression:
2396         unary_expression
2397 |       multiplicative_expression MULT_TK unary_expression
2398                 {
2399                   $$ = build_binop (BINOP_LOOKUP ($2.token),
2400                                     $2.location, $1, $3);
2401                 }
2402 |       multiplicative_expression DIV_TK unary_expression
2403                 {
2404                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2405                                     $1, $3);
2406                 }
2407 |       multiplicative_expression REM_TK unary_expression
2408                 {
2409                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2410                                     $1, $3);
2411                 }
2412 |       multiplicative_expression MULT_TK error
2413                 {yyerror ("Missing term"); RECOVER;}
2414 |       multiplicative_expression DIV_TK error
2415                 {yyerror ("Missing term"); RECOVER;}
2416 |       multiplicative_expression REM_TK error
2417                 {yyerror ("Missing term"); RECOVER;}
2418 ;
2419
2420 additive_expression:
2421         multiplicative_expression
2422 |       additive_expression PLUS_TK multiplicative_expression
2423                 {
2424                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2425                                     $1, $3);
2426                 }
2427 |       additive_expression MINUS_TK multiplicative_expression
2428                 {
2429                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2430                                     $1, $3);
2431                 }
2432 |       additive_expression PLUS_TK error
2433                 {yyerror ("Missing term"); RECOVER;}
2434 |       additive_expression MINUS_TK error
2435                 {yyerror ("Missing term"); RECOVER;}
2436 ;
2437
2438 shift_expression:
2439         additive_expression
2440 |       shift_expression LS_TK additive_expression
2441                 {
2442                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2443                                     $1, $3);
2444                 }
2445 |       shift_expression SRS_TK additive_expression
2446                 {
2447                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2448                                     $1, $3);
2449                 }
2450 |       shift_expression ZRS_TK additive_expression
2451                 {
2452                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2453                                     $1, $3);
2454                 }
2455 |       shift_expression LS_TK error
2456                 {yyerror ("Missing term"); RECOVER;}
2457 |       shift_expression SRS_TK error
2458                 {yyerror ("Missing term"); RECOVER;}
2459 |       shift_expression ZRS_TK error
2460                 {yyerror ("Missing term"); RECOVER;}
2461 ;
2462
2463 relational_expression:
2464         shift_expression
2465 |       relational_expression LT_TK shift_expression
2466                 {
2467                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2468                                     $1, $3);
2469                 }
2470 |       relational_expression GT_TK shift_expression
2471                 {
2472                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2473                                     $1, $3);
2474                 }
2475 |       relational_expression LTE_TK shift_expression
2476                 {
2477                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2478                                     $1, $3);
2479                 }
2480 |       relational_expression GTE_TK shift_expression
2481                 {
2482                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2483                                     $1, $3);
2484                 }
2485 |       relational_expression INSTANCEOF_TK reference_type
2486                 { $$ = build_binop (INSTANCEOF_EXPR, $2.location, $1, $3); }
2487 |       relational_expression LT_TK error
2488                 {yyerror ("Missing term"); RECOVER;}
2489 |       relational_expression GT_TK error
2490                 {yyerror ("Missing term"); RECOVER;}
2491 |       relational_expression LTE_TK error
2492                 {yyerror ("Missing term"); RECOVER;}
2493 |       relational_expression GTE_TK error
2494                 {yyerror ("Missing term"); RECOVER;}
2495 |       relational_expression INSTANCEOF_TK error
2496                 {yyerror ("Invalid reference type"); RECOVER;}
2497 ;
2498
2499 equality_expression:
2500         relational_expression
2501 |       equality_expression EQ_TK relational_expression
2502                 {
2503                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2504                                     $1, $3);
2505                 }
2506 |       equality_expression NEQ_TK relational_expression
2507                 {
2508                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2509                                     $1, $3);
2510                 }
2511 |       equality_expression EQ_TK error
2512                 {yyerror ("Missing term"); RECOVER;}
2513 |       equality_expression NEQ_TK error
2514                 {yyerror ("Missing term"); RECOVER;}
2515 ;
2516
2517 and_expression:
2518         equality_expression
2519 |       and_expression AND_TK equality_expression
2520                 {
2521                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2522                                     $1, $3);
2523                 }
2524 |       and_expression AND_TK error
2525                 {yyerror ("Missing term"); RECOVER;}
2526 ;
2527
2528 exclusive_or_expression:
2529         and_expression
2530 |       exclusive_or_expression XOR_TK and_expression
2531                 {
2532                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2533                                     $1, $3);
2534                 }
2535 |       exclusive_or_expression XOR_TK error
2536                 {yyerror ("Missing term"); RECOVER;}
2537 ;
2538
2539 inclusive_or_expression:
2540         exclusive_or_expression
2541 |       inclusive_or_expression OR_TK exclusive_or_expression
2542                 {
2543                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2544                                     $1, $3);
2545                 }
2546 |       inclusive_or_expression OR_TK error
2547                 {yyerror ("Missing term"); RECOVER;}
2548 ;
2549
2550 conditional_and_expression:
2551         inclusive_or_expression
2552 |       conditional_and_expression BOOL_AND_TK inclusive_or_expression
2553                 {
2554                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2555                                     $1, $3);
2556                 }
2557 |       conditional_and_expression BOOL_AND_TK error
2558                 {yyerror ("Missing term"); RECOVER;}
2559 ;
2560
2561 conditional_or_expression:
2562         conditional_and_expression
2563 |       conditional_or_expression BOOL_OR_TK conditional_and_expression
2564                 {
2565                   $$ = build_binop (BINOP_LOOKUP ($2.token), $2.location,
2566                                     $1, $3);
2567                 }
2568 |       conditional_or_expression BOOL_OR_TK error
2569                 {yyerror ("Missing term"); RECOVER;}
2570 ;
2571
2572 conditional_expression:         /* Error handling here is weak */
2573         conditional_or_expression
2574 |       conditional_or_expression REL_QM_TK expression REL_CL_TK conditional_expression
2575                 {
2576                   $$ = build (CONDITIONAL_EXPR, NULL_TREE, $1, $3, $5);
2577                   EXPR_WFL_LINECOL ($$) = $2.location;
2578                 }
2579 |       conditional_or_expression REL_QM_TK REL_CL_TK error
2580                 {
2581                   YYERROR_NOW;
2582                   yyerror ("Missing term");
2583                   DRECOVER (1);
2584                 }
2585 |       conditional_or_expression REL_QM_TK error
2586                 {yyerror ("Missing term"); DRECOVER (2);}
2587 |       conditional_or_expression REL_QM_TK expression REL_CL_TK error
2588                 {yyerror ("Missing term"); DRECOVER (3);}
2589 ;
2590
2591 assignment_expression:
2592         conditional_expression
2593 |       assignment
2594 ;
2595
2596 assignment:
2597         left_hand_side assignment_operator assignment_expression
2598                 { $$ = build_assignment ($2.token, $2.location, $1, $3); }
2599 |       left_hand_side assignment_operator error
2600                 {
2601                   YYNOT_TWICE yyerror ("Missing term");
2602                   DRECOVER (assign);
2603                 }
2604 ;
2605
2606 left_hand_side:
2607         name
2608 |       field_access
2609 |       array_access
2610 ;
2611
2612 assignment_operator:
2613         ASSIGN_ANY_TK
2614 |       ASSIGN_TK
2615 ;
2616
2617 expression:
2618         assignment_expression
2619 ;
2620
2621 constant_expression:
2622         expression
2623 ;
2624
2625 %%
2626
2627 /* Helper function to retrieve an OSB count. Should be used when the
2628    `dims:' rule is being used.  */
2629
2630 static int
2631 pop_current_osb (struct parser_ctxt *ctxp)
2632 {
2633   int to_return;
2634
2635   if (ctxp->osb_depth < 0)
2636     abort ();
2637
2638   to_return = CURRENT_OSB (ctxp);
2639   ctxp->osb_depth--;
2640
2641   return to_return;
2642 }
2643
2644 \f
2645
2646 /* This section of the code deal with save/restoring parser contexts.
2647    Add mode documentation here. FIXME */
2648
2649 /* Helper function. Create a new parser context. With
2650    COPY_FROM_PREVIOUS set to a nonzero value, content of the previous
2651    context is copied, otherwise, the new context is zeroed. The newly
2652    created context becomes the current one.  */
2653
2654 static void
2655 create_new_parser_context (int copy_from_previous)
2656 {
2657   struct parser_ctxt *new;
2658
2659   new = ggc_alloc (sizeof (struct parser_ctxt));
2660   if (copy_from_previous)
2661     {
2662       memcpy (new, ctxp, sizeof (struct parser_ctxt));
2663       /* This flag, indicating the context saves global values,
2664          should only be set by java_parser_context_save_global.  */
2665       new->saved_data_ctx = 0;
2666     }
2667   else
2668     memset (new, 0, sizeof (struct parser_ctxt));
2669
2670   new->next = ctxp;
2671   ctxp = new;
2672 }
2673
2674 /* Create a new parser context and make it the current one. */
2675
2676 void
2677 java_push_parser_context (void)
2678 {
2679   create_new_parser_context (0);
2680 }
2681
2682 void
2683 java_pop_parser_context (int generate)
2684 {
2685   tree current;
2686   struct parser_ctxt *toFree, *next;
2687
2688   if (!ctxp)
2689     return;
2690
2691   toFree = ctxp;
2692   next = ctxp->next;
2693   if (next)
2694     {
2695       input_line = ctxp->lineno;
2696       current_class = ctxp->class_type;
2697     }
2698
2699   /* If the old and new lexers differ, then free the old one.  */
2700   if (ctxp->lexer && next && ctxp->lexer != next->lexer)
2701     java_destroy_lexer (ctxp->lexer);
2702
2703   /* Set the single import class file flag to 0 for the current list
2704      of imported things */
2705   for (current = ctxp->import_list; current; current = TREE_CHAIN (current))
2706     IS_A_SINGLE_IMPORT_CLASSFILE_NAME_P (TREE_VALUE (current)) = 0;
2707
2708   /* And restore those of the previous context */
2709   if ((ctxp = next))            /* Assignment is really meant here */
2710     for (current = ctxp->import_list; current; current = TREE_CHAIN (current))
2711       IS_A_SINGLE_IMPORT_CLASSFILE_NAME_P (TREE_VALUE (current)) = 1;
2712
2713   /* If we pushed a context to parse a class intended to be generated,
2714      we keep it so we can remember the class. What we could actually
2715      do is to just update a list of class names.  */
2716   if (generate)
2717     {
2718       toFree->next = ctxp_for_generation;
2719       ctxp_for_generation = toFree;
2720     }
2721 }
2722
2723 /* Create a parser context for the use of saving some global
2724    variables.  */
2725
2726 void
2727 java_parser_context_save_global (void)
2728 {
2729   if (!ctxp)
2730     {
2731       java_push_parser_context ();
2732       ctxp->saved_data_ctx = 1;
2733     }
2734
2735   /* If this context already stores data, create a new one suitable
2736      for data storage. */
2737   else if (ctxp->saved_data)
2738     {
2739       create_new_parser_context (1);
2740       ctxp->saved_data_ctx = 1;
2741     }
2742
2743   ctxp->lineno = input_line;
2744   ctxp->class_type = current_class;
2745   ctxp->filename = input_filename;
2746   ctxp->function_decl = current_function_decl;
2747   ctxp->saved_data = 1;
2748 }
2749
2750 /* Restore some global variables from the previous context. Make the
2751    previous context the current one.  */
2752
2753 void
2754 java_parser_context_restore_global (void)
2755 {
2756   input_line = ctxp->lineno;
2757   current_class = ctxp->class_type;
2758   input_filename = ctxp->filename;
2759   if (wfl_operator)
2760     {
2761       tree s;
2762       BUILD_FILENAME_IDENTIFIER_NODE (s, input_filename);
2763       EXPR_WFL_FILENAME_NODE (wfl_operator) = s;
2764     }
2765   current_function_decl = ctxp->function_decl;
2766   ctxp->saved_data = 0;
2767   if (ctxp->saved_data_ctx)
2768     java_pop_parser_context (0);
2769 }
2770
2771 /* Suspend vital data for the current class/function being parsed so
2772    that an other class can be parsed. Used to let local/anonymous
2773    classes be parsed.  */
2774
2775 static void
2776 java_parser_context_suspend (void)
2777 {
2778   /* This makes debugging through java_debug_context easier */
2779   static const char *const name = "<inner buffer context>";
2780
2781   /* Duplicate the previous context, use it to save the globals we're
2782      interested in */
2783   create_new_parser_context (1);
2784   ctxp->function_decl = current_function_decl;
2785   ctxp->class_type = current_class;
2786
2787   /* Then create a new context which inherits all data from the
2788      previous one. This will be the new current context  */
2789   create_new_parser_context (1);
2790
2791   /* Help debugging */
2792   ctxp->next->filename = name;
2793 }
2794
2795 /* Resume vital data for the current class/function being parsed so
2796    that an other class can be parsed. Used to let local/anonymous
2797    classes be parsed.  The trick is the data storing file position
2798    informations must be restored to their current value, so parsing
2799    can resume as if no context was ever saved. */
2800
2801 static void
2802 java_parser_context_resume (void)
2803 {
2804   struct parser_ctxt *old = ctxp;             /* This one is to be discarded */
2805   struct parser_ctxt *saver = old->next;      /* This one contain saved info */
2806   struct parser_ctxt *restored = saver->next; /* This one is the old current */
2807
2808   /* We need to inherit the list of classes to complete/generate */
2809   restored->classd_list = old->classd_list;
2810   restored->class_list = old->class_list;
2811
2812   /* Restore the current class and function from the saver */
2813   current_class = saver->class_type;
2814   current_function_decl = saver->function_decl;
2815
2816   /* Retrieve the restored context */
2817   ctxp = restored;
2818
2819   /* Re-installed the data for the parsing to carry on */
2820   memcpy (&ctxp->marker_begining, &old->marker_begining,
2821           (size_t)(&ctxp->marker_end - &ctxp->marker_begining));
2822 }
2823
2824 /* Add a new anchor node to which all statement(s) initializing static
2825    and non static initialized upon declaration field(s) will be
2826    linked.  */
2827
2828 static void
2829 java_parser_context_push_initialized_field (void)
2830 {
2831   tree node;
2832
2833   node = build_tree_list (NULL_TREE, NULL_TREE);
2834   TREE_CHAIN (node) = CPC_STATIC_INITIALIZER_LIST (ctxp);
2835   CPC_STATIC_INITIALIZER_LIST (ctxp) = node;
2836
2837   node = build_tree_list (NULL_TREE, NULL_TREE);
2838   TREE_CHAIN (node) = CPC_INITIALIZER_LIST (ctxp);
2839   CPC_INITIALIZER_LIST (ctxp) = node;
2840
2841   node = build_tree_list (NULL_TREE, NULL_TREE);
2842   TREE_CHAIN (node) = CPC_INSTANCE_INITIALIZER_LIST (ctxp);
2843   CPC_INSTANCE_INITIALIZER_LIST (ctxp) = node;
2844 }
2845
2846 /* Pop the lists of initialized field. If this lists aren't empty,
2847    remember them so we can use it to create and populate the finit$
2848    or <clinit> functions. */
2849
2850 static void
2851 java_parser_context_pop_initialized_field (void)
2852 {
2853   tree stmts;
2854   tree class_type = TREE_TYPE (GET_CPC ());
2855
2856   if (CPC_INITIALIZER_LIST (ctxp))
2857     {
2858       stmts = CPC_INITIALIZER_STMT (ctxp);
2859       CPC_INITIALIZER_LIST (ctxp) = TREE_CHAIN (CPC_INITIALIZER_LIST (ctxp));
2860       if (stmts && !java_error_count)
2861         TYPE_FINIT_STMT_LIST (class_type) = reorder_static_initialized (stmts);
2862     }
2863
2864   if (CPC_STATIC_INITIALIZER_LIST (ctxp))
2865     {
2866       stmts = CPC_STATIC_INITIALIZER_STMT (ctxp);
2867       CPC_STATIC_INITIALIZER_LIST (ctxp) =
2868         TREE_CHAIN (CPC_STATIC_INITIALIZER_LIST (ctxp));
2869       /* Keep initialization in order to enforce 8.5 */
2870       if (stmts && !java_error_count)
2871         TYPE_CLINIT_STMT_LIST (class_type) = nreverse (stmts);
2872     }
2873
2874   /* JDK 1.1 instance initializers */
2875   if (CPC_INSTANCE_INITIALIZER_LIST (ctxp))
2876     {
2877       stmts = CPC_INSTANCE_INITIALIZER_STMT (ctxp);
2878       CPC_INSTANCE_INITIALIZER_LIST (ctxp) =
2879         TREE_CHAIN (CPC_INSTANCE_INITIALIZER_LIST (ctxp));
2880       if (stmts && !java_error_count)
2881         TYPE_II_STMT_LIST (class_type) = nreverse (stmts);
2882     }
2883 }
2884
2885 static tree
2886 reorder_static_initialized (tree list)
2887 {
2888   /* We have to keep things in order. The alias initializer have to
2889      come first, then the initialized regular field, in reverse to
2890      keep them in lexical order. */
2891   tree marker, previous = NULL_TREE;
2892   for (marker = list; marker; previous = marker, marker = TREE_CHAIN (marker))
2893     if (TREE_CODE (marker) == TREE_LIST
2894         && !TREE_VALUE (marker) && !TREE_PURPOSE (marker))
2895       break;
2896
2897   /* No static initialized, the list is fine as is */
2898   if (!previous)
2899     list = TREE_CHAIN (marker);
2900
2901   /* No marker? reverse the whole list */
2902   else if (!marker)
2903     list = nreverse (list);
2904
2905   /* Otherwise, reverse what's after the marker and the new reordered
2906      sublist will replace the marker. */
2907   else
2908     {
2909       TREE_CHAIN (previous) = NULL_TREE;
2910       list = nreverse (list);
2911       list = chainon (TREE_CHAIN (marker), list);
2912     }
2913   return list;
2914 }
2915
2916 /* Helper functions to dump the parser context stack.  */
2917
2918 #define TAB_CONTEXT(C) \
2919   {int i; for (i = 0; i < (C); i++) fputc (' ', stderr);}
2920
2921 static void
2922 java_debug_context_do (int tab)
2923 {
2924   struct parser_ctxt *copy = ctxp;
2925   while (copy)
2926     {
2927       TAB_CONTEXT (tab);
2928       fprintf (stderr, "ctxt: 0x%0lX\n", (unsigned long)copy);
2929       TAB_CONTEXT (tab);
2930       fprintf (stderr, "filename: %s\n", copy->filename);
2931       TAB_CONTEXT (tab);
2932       fprintf (stderr, "lineno: %d\n", copy->lineno);
2933       TAB_CONTEXT (tab);
2934       fprintf (stderr, "package: %s\n",
2935                (copy->package ?
2936                 IDENTIFIER_POINTER (copy->package) : "<none>"));
2937       TAB_CONTEXT (tab);
2938       fprintf (stderr, "context for saving: %d\n", copy->saved_data_ctx);
2939       TAB_CONTEXT (tab);
2940       fprintf (stderr, "saved data: %d\n", copy->saved_data);
2941       copy = copy->next;
2942       tab += 2;
2943     }
2944 }
2945
2946 /* Dump the stacked up parser contexts. Intended to be called from a
2947    debugger.  */
2948
2949 void
2950 java_debug_context (void)
2951 {
2952   java_debug_context_do (0);
2953 }
2954
2955 \f
2956
2957 /* Flag for the error report routine to issue the error the first time
2958    it's called (overriding the default behavior which is to drop the
2959    first invocation and honor the second one, taking advantage of a
2960    richer context.  */
2961 static int force_error = 0;
2962
2963 /* Reporting an constructor invocation error.  */
2964 static void
2965 parse_ctor_invocation_error (void)
2966 {
2967   if (DECL_CONSTRUCTOR_P (current_function_decl))
2968     yyerror ("Constructor invocation must be first thing in a constructor");
2969   else
2970     yyerror ("Only constructors can invoke constructors");
2971 }
2972
2973 /* Reporting JDK1.1 features not implemented.  */
2974
2975 static tree
2976 parse_jdk1_1_error (const char *msg)
2977 {
2978   sorry (": `%s' JDK1.1(TM) feature", msg);
2979   java_error_count++;
2980   return empty_stmt_node;
2981 }
2982
2983 static int do_warning = 0;
2984
2985 void
2986 yyerror (const char *msg)
2987 {
2988   static java_lc elc;
2989   static int  prev_lineno;
2990   static const char *prev_msg;
2991
2992   int save_lineno;
2993   char *remainder, *code_from_source;
2994
2995   if (!force_error && prev_lineno == input_line)
2996     return;
2997
2998   /* Save current error location but report latter, when the context is
2999      richer.  */
3000   if (ctxp->java_error_flag == 0)
3001     {
3002       ctxp->java_error_flag = 1;
3003       elc = ctxp->elc;
3004       /* Do something to use the previous line if we're reaching the
3005          end of the file... */
3006 #ifdef VERBOSE_SKELETON
3007       printf ("* Error detected (%s)\n", (msg ? msg : "(null)"));
3008 #endif
3009       return;
3010     }
3011
3012   /* Ignore duplicate message on the same line. BTW, this is dubious. FIXME */
3013   if (!force_error && msg == prev_msg && prev_lineno == elc.line)
3014     return;
3015
3016   ctxp->java_error_flag = 0;
3017   if (do_warning)
3018     java_warning_count++;
3019   else
3020     java_error_count++;
3021
3022   if (elc.col == 0 && msg && msg[1] == ';')
3023     {
3024       elc.col  = ctxp->p_line->char_col-1;
3025       elc.line = ctxp->p_line->lineno;
3026     }
3027
3028   save_lineno = input_line;
3029   prev_lineno = input_line = elc.line;
3030   prev_msg = msg;
3031
3032   code_from_source = java_get_line_col (ctxp->filename, elc.line, elc.col);
3033   obstack_grow0 (&temporary_obstack,
3034                  code_from_source, strlen (code_from_source));
3035   remainder = obstack_finish (&temporary_obstack);
3036   if (do_warning)
3037     warning ("%s.\n%s", msg, remainder);
3038   else
3039     error ("%s.\n%s", msg, remainder);
3040
3041   /* This allow us to cheaply avoid an extra 'Invalid expression
3042      statement' error report when errors have been already reported on
3043      the same line. This occurs when we report an error but don't have
3044      a synchronization point other than ';', which
3045      expression_statement is the only one to take care of.  */
3046   ctxp->prevent_ese = input_line = save_lineno;
3047 }
3048
3049 static void
3050 issue_warning_error_from_context (tree cl, const char *msg, va_list ap)
3051 {
3052   const char *saved, *saved_input_filename;
3053   char buffer [4096];
3054   vsprintf (buffer, msg, ap);
3055   force_error = 1;
3056
3057   ctxp->elc.line = EXPR_WFL_LINENO (cl);
3058   ctxp->elc.col  = (EXPR_WFL_COLNO (cl) == 0xfff ? -1 :
3059                     (EXPR_WFL_COLNO (cl) == 0xffe ? -2 : EXPR_WFL_COLNO (cl)));
3060
3061   /* We have a CL, that's a good reason for using it if it contains data */
3062   saved = ctxp->filename;
3063   if (TREE_CODE (cl) == EXPR_WITH_FILE_LOCATION && EXPR_WFL_FILENAME_NODE (cl))
3064     ctxp->filename = EXPR_WFL_FILENAME (cl);
3065   saved_input_filename = input_filename;
3066   input_filename = ctxp->filename;
3067   java_error (NULL);
3068   java_error (buffer);
3069   ctxp->filename = saved;
3070   input_filename = saved_input_filename;
3071   force_error = 0;
3072 }
3073
3074 /* Issue an error message at a current source line CL */
3075
3076 void
3077 parse_error_context (tree cl, const char *msg, ...)
3078 {
3079   va_list ap;
3080   va_start (ap, msg);
3081   issue_warning_error_from_context (cl, msg, ap);
3082   va_end (ap);
3083 }
3084
3085 /* Issue a warning at a current source line CL */
3086
3087 static void
3088 parse_warning_context (tree cl, const char *msg, ...)
3089 {
3090   va_list ap;
3091   va_start (ap, msg);
3092
3093   force_error = do_warning = 1;
3094   issue_warning_error_from_context (cl, msg, ap);
3095   do_warning = force_error = 0;
3096   va_end (ap);
3097 }
3098
3099 static tree
3100 find_expr_with_wfl (tree node)
3101 {
3102   while (node)
3103     {
3104       char code;
3105       tree to_return;
3106
3107       switch (TREE_CODE (node))
3108         {
3109         case BLOCK:
3110           node = BLOCK_EXPR_BODY (node);
3111           continue;
3112
3113         case COMPOUND_EXPR:
3114           to_return = find_expr_with_wfl (TREE_OPERAND (node, 0));
3115           if (to_return)
3116             return to_return;
3117           node = TREE_OPERAND (node, 1);
3118           continue;
3119
3120         case LOOP_EXPR:
3121           node = TREE_OPERAND (node, 0);
3122           continue;
3123
3124         case LABELED_BLOCK_EXPR:
3125           node = TREE_OPERAND (node, 1);
3126           continue;
3127
3128         default:
3129           code = TREE_CODE_CLASS (TREE_CODE (node));
3130           if (((code == '1') || (code == '2') || (code == 'e'))
3131               && EXPR_WFL_LINECOL (node))
3132             return node;
3133           return NULL_TREE;
3134         }
3135     }
3136   return NULL_TREE;
3137 }
3138
3139 /* Issue a missing return statement error. Uses METHOD to figure the
3140    last line of the method the error occurs in.  */
3141
3142 static void
3143 missing_return_error (tree method)
3144 {
3145   EXPR_WFL_SET_LINECOL (wfl_operator, DECL_FUNCTION_LAST_LINE (method), -2);
3146   parse_error_context (wfl_operator, "Missing return statement");
3147 }
3148
3149 /* Issue an unreachable statement error. From NODE, find the next
3150    statement to report appropriately.  */
3151 static void
3152 unreachable_stmt_error (tree node)
3153 {
3154   /* Browse node to find the next expression node that has a WFL. Use
3155      the location to report the error */
3156   if (TREE_CODE (node) == COMPOUND_EXPR)
3157     node = find_expr_with_wfl (TREE_OPERAND (node, 1));
3158   else
3159     node = find_expr_with_wfl (node);
3160
3161   if (node)
3162     {
3163       EXPR_WFL_SET_LINECOL (wfl_operator, EXPR_WFL_LINENO (node), -2);
3164       parse_error_context (wfl_operator, "Unreachable statement");
3165     }
3166   else
3167     abort ();
3168 }
3169
3170 static int
3171 not_accessible_field_error (tree wfl, tree decl)
3172 {
3173   parse_error_context 
3174     (wfl, "Can't access %s field `%s.%s' from `%s'",
3175      java_accstring_lookup (get_access_flags_from_decl (decl)),
3176      GET_TYPE_NAME (DECL_CONTEXT (decl)),
3177      IDENTIFIER_POINTER (DECL_NAME (decl)),
3178      IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (current_class))));
3179   return 1;
3180 }
3181
3182 int
3183 java_report_errors (void)
3184 {
3185   if (java_error_count)
3186     fprintf (stderr, "%d error%s",
3187              java_error_count, (java_error_count == 1 ? "" : "s"));
3188   if (java_warning_count)
3189     fprintf (stderr, "%s%d warning%s", (java_error_count ? ", " : ""),
3190              java_warning_count, (java_warning_count == 1 ? "" : "s"));
3191   if (java_error_count || java_warning_count)
3192     putc ('\n', stderr);
3193   return java_error_count;
3194 }
3195
3196 static char *
3197 java_accstring_lookup (int flags)
3198 {
3199   static char buffer [80];
3200 #define COPY_RETURN(S) {strcpy (buffer, S); return buffer;}
3201
3202   /* Access modifier looked-up first for easier report on forbidden
3203      access. */
3204   if (flags & ACC_PUBLIC) COPY_RETURN ("public");
3205   if (flags & ACC_PRIVATE) COPY_RETURN ("private");
3206   if (flags & ACC_PROTECTED) COPY_RETURN ("protected");
3207   if (flags & ACC_STATIC) COPY_RETURN ("static");
3208   if (flags & ACC_FINAL) COPY_RETURN ("final");
3209   if (flags & ACC_SYNCHRONIZED) COPY_RETURN ("synchronized");
3210   if (flags & ACC_VOLATILE) COPY_RETURN ("volatile");
3211   if (flags & ACC_TRANSIENT) COPY_RETURN ("transient");
3212   if (flags & ACC_NATIVE) COPY_RETURN ("native");
3213   if (flags & ACC_INTERFACE) COPY_RETURN ("interface");
3214   if (flags & ACC_ABSTRACT) COPY_RETURN ("abstract");
3215
3216   buffer [0] = '\0';
3217   return buffer;
3218 #undef COPY_RETURN
3219 }
3220
3221 /* Issuing error messages upon redefinition of classes, interfaces or
3222    variables. */
3223
3224 static void
3225 classitf_redefinition_error (const char *context, tree id, tree decl, tree cl)
3226 {
3227   parse_error_context (cl, "%s `%s' already defined in %s:%d",
3228                        context, IDENTIFIER_POINTER (id),
3229                        DECL_SOURCE_FILE (decl), DECL_SOURCE_LINE (decl));
3230   /* Here we should point out where its redefined. It's a unicode. FIXME */
3231 }
3232
3233 static void
3234 variable_redefinition_error (tree context, tree name, tree type, int line)
3235 {
3236   const char *type_name;
3237
3238   /* Figure a proper name for type. We might haven't resolved it */
3239   if (TREE_CODE (type) == POINTER_TYPE && !TREE_TYPE (type))
3240     type_name = IDENTIFIER_POINTER (TYPE_NAME (type));
3241   else
3242     type_name = lang_printable_name (type, 0);
3243
3244   parse_error_context (context,
3245                        "Variable `%s' is already defined in this method and was declared `%s %s' at line %d",
3246                        IDENTIFIER_POINTER (name),
3247                        type_name, IDENTIFIER_POINTER (name), line);
3248 }
3249
3250 /* If ANAME is terminated with `[]', it indicates an array. This
3251    function returns the number of `[]' found and if this number is
3252    greater than zero, it extracts the array type name and places it in
3253    the node pointed to by TRIMMED unless TRIMMED is null.  */
3254
3255 static int
3256 build_type_name_from_array_name (tree aname, tree *trimmed)
3257 {
3258   const char *name = IDENTIFIER_POINTER (aname);
3259   int len = IDENTIFIER_LENGTH (aname);
3260   int array_dims;
3261
3262   STRING_STRIP_BRACKETS (name, len, array_dims);
3263
3264   if (array_dims && trimmed)
3265     *trimmed = get_identifier_with_length (name, len);
3266
3267   return array_dims;
3268 }
3269
3270 static tree
3271 build_array_from_name (tree type, tree type_wfl, tree name, tree *ret_name)
3272 {
3273   int more_dims = 0;
3274
3275   /* Eventually get more dims */
3276   more_dims = build_type_name_from_array_name (name, &name);
3277
3278   /* If we have, then craft a new type for this variable */
3279   if (more_dims)
3280     {
3281       tree save = type;
3282
3283       /* If we have a pointer, use its type */
3284       if (TREE_CODE (type) == POINTER_TYPE)
3285         type = TREE_TYPE (type);
3286
3287       /* Building the first dimension of a primitive type uses this
3288          function */
3289       if (JPRIMITIVE_TYPE_P (type))
3290         {
3291           type = build_java_array_type (type, -1);
3292           more_dims--;
3293         }
3294       /* Otherwise, if we have a WFL for this type, use it (the type
3295          is already an array on an unresolved type, and we just keep
3296          on adding dimensions) */
3297       else if (type_wfl)
3298         {
3299           type = type_wfl;
3300           more_dims += build_type_name_from_array_name (TYPE_NAME (save),
3301                                                         NULL);
3302         }
3303
3304       /* Add all the dimensions */
3305       while (more_dims--)
3306         type = build_unresolved_array_type (type);
3307
3308       /* The type may have been incomplete in the first place */
3309       if (type_wfl)
3310         type = obtain_incomplete_type (type);
3311     }
3312
3313   if (ret_name)
3314     *ret_name = name;
3315   return type;
3316 }
3317
3318 /* Build something that the type identifier resolver will identify as
3319    being an array to an unresolved type. TYPE_WFL is a WFL on a
3320    identifier. */
3321
3322 static tree
3323 build_unresolved_array_type (tree type_or_wfl)
3324 {
3325   const char *ptr;
3326   tree wfl;
3327
3328   /* TYPE_OR_WFL might be an array on a resolved type. In this case,
3329      just create a array type */
3330   if (TREE_CODE (type_or_wfl) == RECORD_TYPE)
3331     return build_java_array_type (type_or_wfl, -1);
3332
3333   obstack_grow (&temporary_obstack,
3334                  IDENTIFIER_POINTER (EXPR_WFL_NODE (type_or_wfl)),
3335                  IDENTIFIER_LENGTH (EXPR_WFL_NODE (type_or_wfl)));
3336   obstack_grow0 (&temporary_obstack, "[]", 2);
3337   ptr = obstack_finish (&temporary_obstack);
3338   wfl = build_expr_wfl (get_identifier (ptr),
3339                         EXPR_WFL_FILENAME (type_or_wfl),
3340                         EXPR_WFL_LINENO (type_or_wfl),
3341                         EXPR_WFL_COLNO (type_or_wfl));
3342   /* Re-install the existing qualifications so that the type can be
3343      resolved properly. */
3344   EXPR_WFL_QUALIFICATION (wfl) = EXPR_WFL_QUALIFICATION (type_or_wfl);
3345   return wfl;
3346 }
3347
3348 static void
3349 parser_add_interface (tree class_decl, tree interface_decl, tree wfl)
3350 {
3351   if (maybe_add_interface (TREE_TYPE (class_decl), TREE_TYPE (interface_decl)))
3352     parse_error_context (wfl, "Interface `%s' repeated",
3353                          IDENTIFIER_POINTER (DECL_NAME (interface_decl)));
3354 }
3355
3356 /* Bulk of common class/interface checks. Return 1 if an error was
3357    encountered. TAG is 0 for a class, 1 for an interface.  */
3358
3359 static int
3360 check_class_interface_creation (int is_interface, int flags, tree raw_name,
3361                                 tree qualified_name, tree decl, tree cl)
3362 {
3363   tree node;
3364   int sca = 0;                  /* Static class allowed */
3365   int icaf = 0;                 /* Inner class allowed flags */
3366   int uaaf = CLASS_MODIFIERS;   /* Usually allowed access flags */
3367
3368   if (!quiet_flag)
3369     fprintf (stderr, " %s%s %s",
3370              (CPC_INNER_P () ? "inner" : ""),
3371              (is_interface ? "interface" : "class"),
3372              IDENTIFIER_POINTER (qualified_name));
3373
3374   /* Scope of an interface/class type name:
3375        - Can't be imported by a single type import
3376        - Can't already exists in the package */
3377   if (IS_A_SINGLE_IMPORT_CLASSFILE_NAME_P (raw_name)
3378       && (node = find_name_in_single_imports (raw_name))
3379       && !CPC_INNER_P ())
3380     {
3381       parse_error_context
3382         (cl, "%s name `%s' clashes with imported type `%s'",
3383          (is_interface ? "Interface" : "Class"),
3384          IDENTIFIER_POINTER (raw_name), IDENTIFIER_POINTER (node));
3385       return 1;
3386     }
3387   if (decl && CLASS_COMPLETE_P (decl))
3388     {
3389       classitf_redefinition_error ((is_interface ? "Interface" : "Class"),
3390                                    qualified_name, decl, cl);
3391       return 1;
3392     }
3393
3394   if (check_inner_class_redefinition (raw_name, cl))
3395     return 1;
3396
3397   /* If public, file name should match class/interface name, except
3398      when dealing with an inner class */
3399   if (!CPC_INNER_P () && (flags & ACC_PUBLIC ))
3400     {
3401       const char *f;
3402
3403       for (f = &input_filename [strlen (input_filename)];
3404            f != input_filename && ! IS_DIR_SEPARATOR (f[0]);
3405            f--)
3406         ;
3407       if (IS_DIR_SEPARATOR (f[0]))
3408         f++;
3409       if (strncmp (IDENTIFIER_POINTER (raw_name),
3410                    f , IDENTIFIER_LENGTH (raw_name)) ||
3411           f [IDENTIFIER_LENGTH (raw_name)] != '.')
3412         parse_error_context
3413           (cl, "Public %s `%s' must be defined in a file called `%s.java'",
3414                              (is_interface ? "interface" : "class"),
3415                              IDENTIFIER_POINTER (qualified_name),
3416                              IDENTIFIER_POINTER (raw_name));
3417     }
3418
3419   /* Static classes can be declared only in top level classes. Note:
3420      once static, a inner class is a top level class. */
3421   if (flags & ACC_STATIC)
3422     {
3423       /* Catch the specific error of declaring an class inner class
3424          with no toplevel enclosing class. Prevent check_modifiers from
3425          complaining a second time */
3426       if (CPC_INNER_P () && !TOPLEVEL_CLASS_DECL_P (GET_CPC()))
3427         {
3428           parse_error_context (cl, "Inner class `%s' can't be static. Static classes can only occur in interfaces and top-level classes",
3429                                IDENTIFIER_POINTER (qualified_name));
3430           sca = ACC_STATIC;
3431         }
3432       /* Else, in the context of a top-level class declaration, let
3433          `check_modifiers' do its job, otherwise, give it a go */
3434       else
3435         sca = (GET_CPC_LIST () ? ACC_STATIC : 0);
3436     }
3437
3438   /* Inner classes can be declared private or protected
3439      within their enclosing classes. */
3440   if (CPC_INNER_P ())
3441     {
3442       /* A class which is local to a block can't be public, private,
3443          protected or static. But it is created final, so allow this
3444          one. */
3445       if (current_function_decl)
3446         icaf = sca = uaaf = ACC_FINAL;
3447       else
3448         {
3449           check_modifiers_consistency (flags);
3450           icaf = ACC_PROTECTED;
3451           if (! CLASS_INTERFACE (GET_CPC ()))
3452             icaf |= ACC_PRIVATE;
3453         }
3454     }
3455
3456   if (is_interface)
3457     {
3458       if (CPC_INNER_P ())
3459         uaaf = INTERFACE_INNER_MODIFIERS;
3460       else
3461         uaaf = INTERFACE_MODIFIERS;
3462
3463       check_modifiers ("Illegal modifier `%s' for interface declaration",
3464                        flags, uaaf);
3465     }
3466   else
3467     check_modifiers ((current_function_decl ?
3468                       "Illegal modifier `%s' for local class declaration" :
3469                       "Illegal modifier `%s' for class declaration"),
3470                      flags, uaaf|sca|icaf);
3471   return 0;
3472 }
3473
3474 /* Construct a nested class name.  If the final component starts with
3475    a digit, return true.  Otherwise return false.  */
3476 static int
3477 make_nested_class_name (tree cpc_list)
3478 {
3479   tree name;
3480
3481   if (!cpc_list)
3482     return 0;
3483
3484   make_nested_class_name (TREE_CHAIN (cpc_list));
3485
3486   /* Pick the qualified name when dealing with the first upmost
3487      enclosing class */
3488   name = (TREE_CHAIN (cpc_list)
3489           ? TREE_PURPOSE (cpc_list) : DECL_NAME (TREE_VALUE (cpc_list)));
3490   obstack_grow (&temporary_obstack,
3491                 IDENTIFIER_POINTER (name), IDENTIFIER_LENGTH (name));
3492   obstack_1grow (&temporary_obstack, '$');
3493
3494   return ISDIGIT (IDENTIFIER_POINTER (name)[0]);
3495 }
3496
3497 /* Can't redefine a class already defined in an earlier scope. */
3498
3499 static int
3500 check_inner_class_redefinition (tree raw_name, tree cl)
3501 {
3502   tree scope_list;
3503
3504   for (scope_list = GET_CPC_LIST (); scope_list;
3505        scope_list = GET_NEXT_ENCLOSING_CPC (scope_list))
3506     if (raw_name == GET_CPC_UN_NODE (scope_list))
3507       {
3508         parse_error_context
3509           (cl, "The class name `%s' is already defined in this scope. An inner class may not have the same simple name as any of its enclosing classes",
3510            IDENTIFIER_POINTER (raw_name));
3511         return 1;
3512       }
3513   return 0;
3514 }
3515
3516 /* Tries to find a decl for CLASS_TYPE within ENCLOSING. If we fail,
3517    we remember ENCLOSING and SUPER.  */
3518
3519 static tree
3520 resolve_inner_class (htab_t circularity_hash, tree cl, tree *enclosing,
3521                      tree *super, tree class_type)
3522 {
3523   tree local_enclosing = *enclosing;
3524   tree local_super = NULL_TREE;
3525
3526   while (local_enclosing)
3527     {
3528       tree intermediate, decl;
3529
3530       *htab_find_slot (circularity_hash, local_enclosing, INSERT) =
3531         local_enclosing;
3532
3533       if ((decl = find_as_inner_class (local_enclosing, class_type, cl)))
3534         return decl;
3535
3536       intermediate = local_enclosing;
3537       /* Explore enclosing contexts. */
3538       while (INNER_CLASS_DECL_P (intermediate))
3539         {
3540           intermediate = DECL_CONTEXT (intermediate);
3541           if ((decl = find_as_inner_class (intermediate, class_type, cl)))
3542             return decl;
3543         }
3544
3545       /* Now go to the upper classes, bail out if necessary.  We will
3546          analyze the returned SUPER and act accordingly (see
3547          do_resolve_class).  */
3548       if (JPRIMITIVE_TYPE_P (TREE_TYPE (local_enclosing))
3549           || TREE_TYPE (local_enclosing) == void_type_node)
3550         {
3551           parse_error_context (cl, "Qualifier must be a reference");
3552           local_enclosing = NULL_TREE;
3553           break;
3554         }
3555       local_super = CLASSTYPE_SUPER (TREE_TYPE (local_enclosing));
3556       if (!local_super || local_super == object_type_node)
3557         break;
3558
3559       if (TREE_CODE (local_super) == POINTER_TYPE)
3560         local_super = do_resolve_class (NULL, local_super, NULL, NULL);
3561       else
3562         local_super = TYPE_NAME (local_super);
3563
3564       /* We may not have checked for circular inheritance yet, so do so
3565          here to prevent an infinite loop. */
3566       if (htab_find (circularity_hash, local_super) != NULL)
3567         {
3568           if (!cl)
3569             cl = lookup_cl (local_enclosing);
3570
3571           parse_error_context
3572             (cl, "Cyclic inheritance involving %s",
3573              IDENTIFIER_POINTER (DECL_NAME (local_enclosing)));
3574           local_enclosing = NULL_TREE;
3575         }
3576       else
3577         local_enclosing = local_super;
3578     }
3579
3580   /* We failed. Return LOCAL_SUPER and LOCAL_ENCLOSING. */
3581   *super = local_super;
3582   *enclosing = local_enclosing;
3583
3584   return NULL_TREE;
3585 }
3586
3587 /* Within ENCLOSING, find a decl for NAME and return it. NAME can be
3588    qualified. */
3589
3590 static tree
3591 find_as_inner_class (tree enclosing, tree name, tree cl)
3592 {
3593   tree qual, to_return;
3594   if (!enclosing)
3595     return NULL_TREE;
3596
3597   name = TYPE_NAME (name);
3598
3599   /* First search: within the scope of `enclosing', search for name */
3600   if (QUALIFIED_P (name) && cl && EXPR_WFL_NODE (cl) == name)
3601     qual = EXPR_WFL_QUALIFICATION (cl);
3602   else if (cl)
3603     qual = build_tree_list (cl, NULL_TREE);
3604   else
3605     qual = build_tree_list (build_expr_wfl (name, NULL, 0, 0), NULL_TREE);
3606
3607   if ((to_return = find_as_inner_class_do (qual, enclosing)))
3608     return to_return;
3609
3610   /* We're dealing with a qualified name. Try to resolve thing until
3611      we get something that is an enclosing class. */
3612   if (QUALIFIED_P (name) && cl && EXPR_WFL_NODE (cl) == name)
3613     {
3614       tree acc = NULL_TREE, decl = NULL_TREE, ptr;
3615
3616       for (qual = EXPR_WFL_QUALIFICATION (cl); qual && !decl;
3617            qual = TREE_CHAIN (qual))
3618         {
3619           acc = merge_qualified_name (acc,
3620                                       EXPR_WFL_NODE (TREE_PURPOSE (qual)));
3621           BUILD_PTR_FROM_NAME (ptr, acc);
3622           decl = do_resolve_class (NULL_TREE, ptr, NULL_TREE, cl);
3623         }
3624
3625       /* A NULL qual and a decl means that the search ended
3626          successfully?!? We have to do something then. FIXME */
3627
3628       if (decl)
3629         enclosing = decl;
3630       else
3631         qual = EXPR_WFL_QUALIFICATION (cl);
3632     }
3633   /* Otherwise, create a qual for the other part of the resolution. */
3634   else
3635     qual = build_tree_list (build_expr_wfl (name, NULL, 0, 0), NULL_TREE);
3636
3637   return find_as_inner_class_do (qual, enclosing);
3638 }
3639
3640 /* We go inside the list of sub classes and try to find a way
3641    through. */
3642
3643 static tree
3644 find_as_inner_class_do (tree qual, tree enclosing)
3645 {
3646   if (!qual)
3647     return NULL_TREE;
3648
3649   for (; qual && enclosing; qual = TREE_CHAIN (qual))
3650     {
3651       tree name_to_match = EXPR_WFL_NODE (TREE_PURPOSE (qual));
3652       tree next_enclosing = NULL_TREE;
3653       tree inner_list;
3654
3655       for (inner_list = DECL_INNER_CLASS_LIST (enclosing);
3656            inner_list; inner_list = TREE_CHAIN (inner_list))
3657         {
3658           if (TREE_VALUE (inner_list) == name_to_match)
3659             {
3660               next_enclosing = TREE_PURPOSE (inner_list);
3661               break;
3662             }
3663         }
3664       enclosing = next_enclosing;
3665     }
3666
3667   return (!qual && enclosing ? enclosing : NULL_TREE);
3668 }
3669
3670 /* Reach all inner classes and tie their unqualified name to a
3671    DECL. */
3672
3673 static void
3674 set_nested_class_simple_name_value (tree outer, int set)
3675 {
3676   tree l;
3677
3678   for (l = DECL_INNER_CLASS_LIST (outer); l; l = TREE_CHAIN (l))
3679     IDENTIFIER_GLOBAL_VALUE (TREE_VALUE (l)) = (set ?
3680                                                 TREE_PURPOSE (l) : NULL_TREE);
3681 }
3682
3683 static void
3684 link_nested_class_to_enclosing (void)
3685 {
3686   if (GET_ENCLOSING_CPC ())
3687     {
3688       tree enclosing = GET_ENCLOSING_CPC_CONTEXT ();
3689       DECL_INNER_CLASS_LIST (enclosing) =
3690         tree_cons (GET_CPC (), GET_CPC_UN (),
3691                    DECL_INNER_CLASS_LIST (enclosing));
3692     }
3693 }
3694
3695 static tree
3696 maybe_make_nested_class_name (tree name)
3697 {
3698   tree id = NULL_TREE;
3699
3700   if (CPC_INNER_P ())
3701     {
3702       /* If we're in a function, we must append a number to create the
3703          nested class name.  However, we don't do this if the class we
3704          are constructing is anonymous, because in that case we'll
3705          already have a number as the class name.  */
3706       if (! make_nested_class_name (GET_CPC_LIST ())
3707           && current_function_decl != NULL_TREE
3708           && ! ISDIGIT (IDENTIFIER_POINTER (name)[0]))
3709         {
3710           char buf[10];
3711           sprintf (buf, "%d", anonymous_class_counter);
3712           ++anonymous_class_counter;
3713           obstack_grow (&temporary_obstack, buf, strlen (buf));
3714           obstack_1grow (&temporary_obstack, '$');
3715         }
3716       obstack_grow0 (&temporary_obstack,
3717                      IDENTIFIER_POINTER (name),
3718                      IDENTIFIER_LENGTH (name));
3719       id = get_identifier (obstack_finish (&temporary_obstack));
3720       if (ctxp->package)
3721         QUALIFIED_P (id) = 1;
3722     }
3723   return id;
3724 }
3725
3726 /* If DECL is NULL, create and push a new DECL, record the current
3727    line CL and do other maintenance things.  */
3728
3729 static tree
3730 maybe_create_class_interface_decl (tree decl, tree raw_name,
3731                                    tree qualified_name, tree cl)
3732 {
3733   if (!decl)
3734     decl = push_class (make_class (), qualified_name);
3735
3736   /* Take care of the file and line business */
3737   DECL_SOURCE_FILE (decl) = EXPR_WFL_FILENAME (cl);
3738   /* If we're emitting xrefs, store the line/col number information */
3739   if (flag_emit_xref)
3740     DECL_SOURCE_LINE (decl) = EXPR_WFL_LINECOL (cl);
3741   else
3742     DECL_SOURCE_LINE (decl) = EXPR_WFL_LINENO (cl);
3743   CLASS_FROM_SOURCE_P (TREE_TYPE (decl)) = 1;
3744   CLASS_PARSED_P (TREE_TYPE (decl)) = 1;
3745   CLASS_FROM_CURRENTLY_COMPILED_P (TREE_TYPE (decl)) =
3746     IS_A_COMMAND_LINE_FILENAME_P (EXPR_WFL_FILENAME_NODE (cl));
3747
3748   PUSH_CPC (decl, raw_name);
3749   DECL_CONTEXT (decl) = GET_ENCLOSING_CPC_CONTEXT ();
3750
3751   /* Link the declaration to the already seen ones */
3752   TREE_CHAIN (decl) = ctxp->class_list;
3753   ctxp->class_list = decl;
3754
3755   /* Create a new nodes in the global lists */
3756   gclass_list = tree_cons (NULL_TREE, decl, gclass_list);
3757   all_class_list = tree_cons (NULL_TREE, decl, all_class_list);
3758
3759   /* Install a new dependency list element */
3760   create_jdep_list (ctxp);
3761
3762   SOURCE_FRONTEND_DEBUG (("Defining class/interface %s",
3763                           IDENTIFIER_POINTER (qualified_name)));
3764   return decl;
3765 }
3766
3767 static void
3768 add_superinterfaces (tree decl, tree interface_list)
3769 {
3770   tree node;
3771   /* Superinterface(s): if present and defined, parser_check_super_interface ()
3772      takes care of ensuring that:
3773        - This is an accessible interface type,
3774        - Circularity detection.
3775    parser_add_interface is then called. If present but not defined,
3776    the check operation is delayed until the super interface gets
3777    defined.  */
3778   for (node = interface_list; node; node = TREE_CHAIN (node))
3779     {
3780       tree current = TREE_PURPOSE (node);
3781       tree idecl = IDENTIFIER_CLASS_VALUE (EXPR_WFL_NODE (current));
3782       if (idecl && CLASS_LOADED_P (TREE_TYPE (idecl)))
3783         {
3784           if (!parser_check_super_interface (idecl, decl, current))
3785             parser_add_interface (decl, idecl, current);
3786         }
3787       else
3788         register_incomplete_type (JDEP_INTERFACE,
3789                                   current, decl, NULL_TREE);
3790     }
3791 }
3792
3793 /* Create an interface in pass1 and return its decl. Return the
3794    interface's decl in pass 2.  */
3795
3796 static tree
3797 create_interface (int flags, tree id, tree super)
3798 {
3799   tree raw_name = EXPR_WFL_NODE (id);
3800   tree q_name = parser_qualified_classname (raw_name);
3801   tree decl = IDENTIFIER_CLASS_VALUE (q_name);
3802
3803   /* Certain syntax errors are making SUPER be like ID. Avoid this
3804      case. */
3805   if (ctxp->class_err && id == super)
3806     super = NULL;
3807
3808   EXPR_WFL_NODE (id) = q_name;  /* Keep source location, even if refined. */
3809
3810   /* Basic checks: scope, redefinition, modifiers */
3811   if (check_class_interface_creation (1, flags, raw_name, q_name, decl, id))
3812     {
3813       PUSH_ERROR ();
3814       return NULL_TREE;
3815     }
3816
3817   /* Suspend the current parsing context if we're parsing an inner
3818      interface */
3819   if (CPC_INNER_P ())
3820     {
3821       java_parser_context_suspend ();
3822       /* Interface members are public. */
3823       if (CLASS_INTERFACE (GET_CPC ()))
3824         flags |= ACC_PUBLIC;
3825     }
3826
3827   /* Push a new context for (static) initialized upon declaration fields */
3828   java_parser_context_push_initialized_field ();
3829
3830   /* Interface modifiers check
3831        - public/abstract allowed (already done at that point)
3832        - abstract is obsolete (comes first, it's a warning, or should be)
3833        - Can't use twice the same (checked in the modifier rule) */
3834   if ((flags & ACC_ABSTRACT) && flag_redundant)
3835     parse_warning_context
3836       (MODIFIER_WFL (ABSTRACT_TK),
3837        "Redundant use of `abstract' modifier. Interface `%s' is implicitly abstract", IDENTIFIER_POINTER (raw_name));
3838
3839   /* Create a new decl if DECL is NULL, otherwise fix it */
3840   decl = maybe_create_class_interface_decl (decl, raw_name, q_name, id);
3841
3842   /* Set super info and mark the class a complete */
3843   set_super_info (ACC_INTERFACE | flags, TREE_TYPE (decl),
3844                   object_type_node, ctxp->interface_number);
3845   ctxp->interface_number = 0;
3846   CLASS_COMPLETE_P (decl) = 1;
3847   add_superinterfaces (decl, super);
3848
3849   /* Eventually sets the @deprecated tag flag */
3850   CHECK_DEPRECATED (decl);
3851
3852   return decl;
3853 }
3854
3855 /* Patch anonymous class CLASS, by either extending or implementing
3856    DEP.  */
3857
3858 static void
3859 patch_anonymous_class (tree type_decl, tree class_decl, tree wfl)
3860 {
3861   tree class = TREE_TYPE (class_decl);
3862   tree type =  TREE_TYPE (type_decl);
3863   tree binfo = TYPE_BINFO (class);
3864
3865   /* If it's an interface, implement it */
3866   if (CLASS_INTERFACE (type_decl))
3867     {
3868       tree s_binfo;
3869       int length;
3870
3871       if (parser_check_super_interface (type_decl, class_decl, wfl))
3872         return;
3873
3874       s_binfo = TREE_VEC_ELT (BINFO_BASETYPES (TYPE_BINFO (class)), 0);
3875       length = TREE_VEC_LENGTH (TYPE_BINFO_BASETYPES (class))+1;
3876       TYPE_BINFO_BASETYPES (class) = make_tree_vec (length);
3877       TREE_VEC_ELT (BINFO_BASETYPES (TYPE_BINFO (class)), 0) = s_binfo;
3878       /* And add the interface */
3879       parser_add_interface (class_decl, type_decl, wfl);
3880     }
3881   /* Otherwise, it's a type we want to extend */
3882   else
3883     {
3884       if (parser_check_super (type_decl, class_decl, wfl))
3885         return;
3886       BINFO_TYPE (TREE_VEC_ELT (BINFO_BASETYPES (binfo), 0)) = type;
3887     }
3888 }
3889
3890 static tree
3891 create_anonymous_class (int location, tree type_name)
3892 {
3893   char buffer [80];
3894   tree super = NULL_TREE, itf = NULL_TREE;
3895   tree id, type_decl, class;
3896
3897   /* The unqualified name of the anonymous class. It's just a number. */
3898   sprintf (buffer, "%d", anonymous_class_counter++);
3899   id = build_wfl_node (get_identifier (buffer));
3900   EXPR_WFL_LINECOL (id) = location;
3901
3902   /* We know about the type to extend/implement. We go ahead */
3903   if ((type_decl = IDENTIFIER_CLASS_VALUE (EXPR_WFL_NODE (type_name))))
3904     {
3905       /* Create a class which either implements on extends the designated
3906          class. The class bears an inaccessible name. */
3907       if (CLASS_INTERFACE (type_decl))
3908         {
3909           /* It's OK to modify it here. It's been already used and
3910              shouldn't be reused */
3911           ctxp->interface_number = 1;
3912           /* Interfaces should presented as a list of WFLs */
3913           itf = build_tree_list (type_name, NULL_TREE);
3914         }
3915       else
3916         super = type_name;
3917     }
3918
3919   class = create_class (ACC_FINAL, id, super, itf);
3920
3921   /* We didn't know anything about the stuff. We register a dependence. */
3922   if (!type_decl)
3923     register_incomplete_type (JDEP_ANONYMOUS, type_name, class, NULL_TREE);
3924
3925   ANONYMOUS_CLASS_P (TREE_TYPE (class)) = 1;
3926   return class;
3927 }
3928
3929 /* Create a class in pass1 and return its decl. Return class
3930    interface's decl in pass 2.  */
3931
3932 static tree
3933 create_class (int flags, tree id, tree super, tree interfaces)
3934 {
3935   tree raw_name = EXPR_WFL_NODE (id);
3936   tree class_id, decl;
3937   tree super_decl_type;
3938
3939   /* Certain syntax errors are making SUPER be like ID. Avoid this
3940      case. */
3941   if (ctxp->class_err && id == super)
3942     super = NULL;
3943
3944   class_id = parser_qualified_classname (raw_name);
3945   decl = IDENTIFIER_CLASS_VALUE (class_id);
3946   EXPR_WFL_NODE (id) = class_id;
3947
3948   /* Basic check: scope, redefinition, modifiers */
3949   if (check_class_interface_creation (0, flags, raw_name, class_id, decl, id))
3950     {
3951       PUSH_ERROR ();
3952       return NULL_TREE;
3953     }
3954
3955   /* Suspend the current parsing context if we're parsing an inner
3956      class or an anonymous class. */
3957   if (CPC_INNER_P ())
3958     {
3959       java_parser_context_suspend ();
3960       /* Interface members are public. */
3961       if (CLASS_INTERFACE (GET_CPC ()))
3962         flags |= ACC_PUBLIC;
3963     }
3964
3965   /* Push a new context for (static) initialized upon declaration fields */
3966   java_parser_context_push_initialized_field ();
3967
3968   /* Class modifier check:
3969        - Allowed modifier (already done at that point)
3970        - abstract AND final forbidden
3971        - Public classes defined in the correct file */
3972   if ((flags & ACC_ABSTRACT) && (flags & ACC_FINAL))
3973     parse_error_context
3974       (id, "Class `%s' can't be declared both abstract and final",
3975        IDENTIFIER_POINTER (raw_name));
3976
3977   /* Create a new decl if DECL is NULL, otherwise fix it */
3978   decl = maybe_create_class_interface_decl (decl, raw_name, class_id, id);
3979
3980   /* If SUPER exists, use it, otherwise use Object */
3981   if (super)
3982     {
3983       /* Can't extend java.lang.Object */
3984       if (TREE_TYPE (IDENTIFIER_CLASS_VALUE (class_id)) == object_type_node)
3985         {
3986           parse_error_context (id, "Can't extend `java.lang.Object'");
3987           return NULL_TREE;
3988         }
3989
3990       super_decl_type =
3991         register_incomplete_type (JDEP_SUPER, super, decl, NULL_TREE);
3992     }
3993   else if (TREE_TYPE (decl) != object_type_node)
3994     super_decl_type = object_type_node;
3995   /* We're defining java.lang.Object */
3996   else
3997     super_decl_type = NULL_TREE;
3998
3999   /* A class nested in an interface is implicitly static. */
4000   if (INNER_CLASS_DECL_P (decl)
4001       && CLASS_INTERFACE (TYPE_NAME (TREE_TYPE (DECL_CONTEXT (decl)))))
4002     {
4003       flags |= ACC_STATIC;
4004     }
4005
4006   /* Set super info and mark the class as complete. */
4007   set_super_info (flags, TREE_TYPE (decl), super_decl_type,
4008                   ctxp->interface_number);
4009   ctxp->interface_number = 0;
4010   CLASS_COMPLETE_P (decl) = 1;
4011   add_superinterfaces (decl, interfaces);
4012
4013   /* Add the private this$<n> field, Replicate final locals still in
4014      scope as private final fields mangled like val$<local_name>.
4015      This doesn't not occur for top level (static) inner classes. */
4016   if (PURE_INNER_CLASS_DECL_P (decl))
4017     add_inner_class_fields (decl, current_function_decl);
4018
4019   /* If doing xref, store the location at which the inherited class
4020      (if any) was seen. */
4021   if (flag_emit_xref && super)
4022     DECL_INHERITED_SOURCE_LINE (decl) = EXPR_WFL_LINECOL (super);
4023
4024   /* Eventually sets the @deprecated tag flag */
4025   CHECK_DEPRECATED (decl);
4026
4027   /* Reset the anonymous class counter when declaring non inner classes */
4028   if (!INNER_CLASS_DECL_P (decl))
4029     anonymous_class_counter = 1;
4030
4031   return decl;
4032 }
4033
4034 /* End a class declaration: register the statements used to create
4035    finit$ and <clinit>, pop the current class and resume the prior
4036    parser context if necessary.  */
4037
4038 static void
4039 end_class_declaration (int resume)
4040 {
4041   /* If an error occurred, context weren't pushed and won't need to be
4042      popped by a resume. */
4043   int no_error_occurred = ctxp->next && GET_CPC () != error_mark_node;
4044
4045   if (GET_CPC () != error_mark_node)
4046     dump_java_tree (TDI_class, GET_CPC ());
4047
4048   java_parser_context_pop_initialized_field ();
4049   POP_CPC ();
4050   if (resume && no_error_occurred)
4051     java_parser_context_resume ();
4052
4053   /* We're ending a class declaration, this is a good time to reset
4054      the interface cout. Note that might have been already done in
4055      create_interface, but if at that time an inner class was being
4056      dealt with, the interface count was reset in a context created
4057      for the sake of handling inner classes declaration. */
4058   ctxp->interface_number = 0;
4059 }
4060
4061 static void
4062 add_inner_class_fields (tree class_decl, tree fct_decl)
4063 {
4064   tree block, marker, f;
4065
4066   f = add_field (TREE_TYPE (class_decl),
4067                  build_current_thisn (TREE_TYPE (class_decl)),
4068                  build_pointer_type (TREE_TYPE (DECL_CONTEXT (class_decl))),
4069                  ACC_PRIVATE);
4070   FIELD_THISN (f) = 1;
4071
4072   if (!fct_decl)
4073     return;
4074
4075   for (block = GET_CURRENT_BLOCK (fct_decl);
4076        block && TREE_CODE (block) == BLOCK; block = BLOCK_SUPERCONTEXT (block))
4077     {
4078       tree decl;
4079       for (decl = BLOCK_EXPR_DECLS (block); decl; decl = TREE_CHAIN (decl))
4080         {
4081           tree name, pname;
4082           tree wfl, init, list;
4083
4084           /* Avoid non final arguments. */
4085           if (!LOCAL_FINAL_P (decl))
4086             continue;
4087
4088           MANGLE_OUTER_LOCAL_VARIABLE_NAME (name, DECL_NAME (decl));
4089           MANGLE_ALIAS_INITIALIZER_PARAMETER_NAME_ID (pname, DECL_NAME (decl));
4090           wfl = build_wfl_node (name);
4091           init = build_wfl_node (pname);
4092           /* Build an initialization for the field: it will be
4093              initialized by a parameter added to finit$, bearing a
4094              mangled name of the field itself (param$<n>.) The
4095              parameter is provided to finit$ by the constructor
4096              invoking it (hence the constructor will also feature a
4097              hidden parameter, set to the value of the outer context
4098              local at the time the inner class is created.)
4099
4100              Note: we take into account all possible locals that can
4101              be accessed by the inner class. It's actually not trivial
4102              to minimize these aliases down to the ones really
4103              used. One way to do that would be to expand all regular
4104              methods first, then finit$ to get a picture of what's
4105              used.  It works with the exception that we would have to
4106              go back on all constructor invoked in regular methods to
4107              have their invocation reworked (to include the right amount
4108              of alias initializer parameters.)
4109
4110              The only real way around, I think, is a first pass to
4111              identify locals really used in the inner class. We leave
4112              the flag FIELD_LOCAL_ALIAS_USED around for that future
4113              use.
4114
4115              On the other hand, it only affect local inner classes,
4116              whose constructors (and finit$ call) will be featuring
4117              unnecessary arguments. It's easy for a developer to keep
4118              this number of parameter down by using the `final'
4119              keyword only when necessary. For the time being, we can
4120              issue a warning on unnecessary finals. FIXME */
4121           init = build_assignment (ASSIGN_TK, EXPR_WFL_LINECOL (wfl),
4122                                    wfl, init);
4123
4124           /* Register the field. The TREE_LIST holding the part
4125              initialized/initializer will be marked ARG_FINAL_P so
4126              that the created field can be marked
4127              FIELD_LOCAL_ALIAS. */
4128           list = build_tree_list (wfl, init);
4129           ARG_FINAL_P (list) = 1;
4130           register_fields (ACC_PRIVATE | ACC_FINAL, TREE_TYPE (decl), list);
4131         }
4132     }
4133
4134   if (!CPC_INITIALIZER_STMT (ctxp))
4135     return;
4136
4137   /* If we ever registered an alias field, insert and marker to
4138      remember where the list ends. The second part of the list (the one
4139      featuring initialized fields) so it can be later reversed to
4140      enforce 8.5. The marker will be removed during that operation. */
4141   marker = build_tree_list (NULL_TREE, NULL_TREE);
4142   TREE_CHAIN (marker) = CPC_INITIALIZER_STMT (ctxp);
4143   SET_CPC_INITIALIZER_STMT (ctxp, marker);
4144 }
4145
4146 /* Can't use lookup_field () since we don't want to load the class and
4147    can't set the CLASS_LOADED_P flag */
4148
4149 static tree
4150 find_field (tree class, tree name)
4151 {
4152   tree decl;
4153   for (decl = TYPE_FIELDS (class); decl; decl = TREE_CHAIN (decl))
4154     {
4155       if (DECL_NAME (decl) == name)
4156         return decl;
4157     }
4158   return NULL_TREE;
4159 }
4160
4161 /* Wrap around lookup_field that doesn't potentially upset the value
4162    of CLASS */
4163
4164 static tree
4165 lookup_field_wrapper (tree class, tree name)
4166 {
4167   tree type = class;
4168   tree decl = NULL_TREE;
4169   java_parser_context_save_global ();
4170
4171   /* Last chance: if we're within the context of an inner class, we
4172      might be trying to access a local variable defined in an outer
4173      context. We try to look for it now. */
4174   if (INNER_CLASS_TYPE_P (class) && TREE_CODE (name) == IDENTIFIER_NODE)
4175     {
4176       tree new_name;
4177       MANGLE_OUTER_LOCAL_VARIABLE_NAME (new_name, name);
4178       decl = lookup_field (&type, new_name);
4179       if (decl && decl != error_mark_node)
4180         FIELD_LOCAL_ALIAS_USED (decl) = 1;
4181     }
4182   if (!decl || decl == error_mark_node)
4183     {
4184       type = class;
4185       decl = lookup_field (&type, name);
4186     }
4187
4188   /* If the field still hasn't been found, try the next enclosing context. */
4189   if (!decl && INNER_CLASS_TYPE_P (class))
4190     {
4191       tree outer_type = TREE_TYPE (DECL_CONTEXT (TYPE_NAME (class)));
4192       decl = lookup_field_wrapper (outer_type, name);
4193     }
4194
4195   java_parser_context_restore_global ();
4196   return decl == error_mark_node ? NULL : decl;
4197 }
4198
4199 /* Find duplicate field within the same class declarations and report
4200    the error. Returns 1 if a duplicated field was found, 0
4201    otherwise.  */
4202
4203 static int
4204 duplicate_declaration_error_p (tree new_field_name, tree new_type, tree cl)
4205 {
4206   /* This might be modified to work with method decl as well */
4207   tree decl = find_field (TREE_TYPE (GET_CPC ()), new_field_name);
4208   if (decl)
4209     {
4210       char *t1 = xstrdup (purify_type_name
4211                          ((TREE_CODE (new_type) == POINTER_TYPE
4212                            && TREE_TYPE (new_type) == NULL_TREE) ?
4213                           IDENTIFIER_POINTER (TYPE_NAME (new_type)) :
4214                           lang_printable_name (new_type, 1)));
4215       /* The type may not have been completed by the time we report
4216          the error */
4217       char *t2 = xstrdup (purify_type_name
4218                          ((TREE_CODE (TREE_TYPE (decl)) == POINTER_TYPE
4219                            && TREE_TYPE (TREE_TYPE (decl)) == NULL_TREE) ?
4220                           IDENTIFIER_POINTER (TYPE_NAME (TREE_TYPE (decl))) :
4221                           lang_printable_name (TREE_TYPE (decl), 1)));
4222       parse_error_context
4223         (cl , "Duplicate variable declaration: `%s %s' was `%s %s' (%s:%d)",
4224          t1, IDENTIFIER_POINTER (new_field_name),
4225          t2, IDENTIFIER_POINTER (DECL_NAME (decl)),
4226          DECL_SOURCE_FILE (decl), DECL_SOURCE_LINE (decl));
4227       free (t1);
4228       free (t2);
4229       return 1;
4230     }
4231   return 0;
4232 }
4233
4234 /* Field registration routine. If TYPE doesn't exist, field
4235    declarations are linked to the undefined TYPE dependency list, to
4236    be later resolved in java_complete_class () */
4237
4238 static void
4239 register_fields (int flags, tree type, tree variable_list)
4240 {
4241   tree current, saved_type;
4242   tree class_type = NULL_TREE;
4243   int saved_lineno = input_line;
4244   int must_chain = 0;
4245   tree wfl = NULL_TREE;
4246
4247   if (GET_CPC ())
4248     class_type = TREE_TYPE (GET_CPC ());
4249
4250   if (!class_type || class_type == error_mark_node)
4251     return;
4252
4253   /* If we're adding fields to interfaces, those fields are public,
4254      static, final */
4255   if (CLASS_INTERFACE (TYPE_NAME (class_type)))
4256     {
4257       OBSOLETE_MODIFIER_WARNING (MODIFIER_WFL (PUBLIC_TK),
4258                                  flags, ACC_PUBLIC, "interface field(s)");
4259       OBSOLETE_MODIFIER_WARNING (MODIFIER_WFL (STATIC_TK),
4260                                  flags, ACC_STATIC, "interface field(s)");
4261       OBSOLETE_MODIFIER_WARNING (MODIFIER_WFL (FINAL_TK),
4262                                  flags, ACC_FINAL, "interface field(s)");
4263       check_modifiers ("Illegal interface member modifier `%s'", flags,
4264                        INTERFACE_FIELD_MODIFIERS);
4265       flags |= (ACC_PUBLIC | ACC_STATIC | ACC_FINAL);
4266     }
4267
4268   /* Obtain a suitable type for resolution, if necessary */
4269   SET_TYPE_FOR_RESOLUTION (type, wfl, must_chain);
4270
4271   /* If TYPE is fully resolved and we don't have a reference, make one */
4272   PROMOTE_RECORD_IF_COMPLETE (type, must_chain);
4273
4274   for (current = variable_list, saved_type = type; current;
4275        current = TREE_CHAIN (current), type = saved_type)
4276     {
4277       tree real_type;
4278       tree field_decl;
4279       tree cl = TREE_PURPOSE (current);
4280       tree init = TREE_VALUE (current);
4281       tree current_name = EXPR_WFL_NODE (cl);
4282
4283       /* Can't declare non-final static fields in inner classes */
4284       if ((flags & ACC_STATIC) && !TOPLEVEL_CLASS_TYPE_P (class_type)
4285           && !(flags & ACC_FINAL))
4286         parse_error_context
4287           (cl, "Field `%s' can't be static in inner class `%s' unless it is final",
4288            IDENTIFIER_POINTER (EXPR_WFL_NODE (cl)),
4289            lang_printable_name (class_type, 0));
4290
4291       /* Process NAME, as it may specify extra dimension(s) for it */
4292       type = build_array_from_name (type, wfl, current_name, &current_name);
4293
4294       /* Type adjustment. We may have just readjusted TYPE because
4295          the variable specified more dimensions. Make sure we have
4296          a reference if we can and don't have one already. Also
4297          change the name if we have an init. */
4298       if (type != saved_type)
4299         {
4300           PROMOTE_RECORD_IF_COMPLETE (type, must_chain);
4301           if (init)
4302             EXPR_WFL_NODE (TREE_OPERAND (init, 0)) = current_name;
4303         }
4304
4305       real_type = GET_REAL_TYPE (type);
4306       /* Check for redeclarations */
4307       if (duplicate_declaration_error_p (current_name, real_type, cl))
4308         continue;
4309
4310       /* Set lineno to the line the field was found and create a
4311          declaration for it. Eventually sets the @deprecated tag flag. */
4312       if (flag_emit_xref)
4313         input_line = EXPR_WFL_LINECOL (cl);
4314       else
4315         input_line = EXPR_WFL_LINENO (cl);
4316       field_decl = add_field (class_type, current_name, real_type, flags);
4317       CHECK_DEPRECATED_NO_RESET (field_decl);
4318
4319       /* If the field denotes a final instance variable, then we
4320          allocate a LANG_DECL_SPECIFIC part to keep track of its
4321          initialization. We also mark whether the field was
4322          initialized upon its declaration. We don't do that if the
4323          created field is an alias to a final local. */
4324       if (!ARG_FINAL_P (current) && (flags & ACC_FINAL))
4325         {
4326           MAYBE_CREATE_VAR_LANG_DECL_SPECIFIC (field_decl);
4327           DECL_FIELD_FINAL_WFL (field_decl) = cl;
4328         }
4329
4330       /* If the couple initializer/initialized is marked ARG_FINAL_P,
4331          we mark the created field FIELD_LOCAL_ALIAS, so that we can
4332          hide parameters to this inner class finit$ and
4333          constructors. It also means that the field isn't final per
4334          say. */
4335       if (ARG_FINAL_P (current))
4336         {
4337           FIELD_LOCAL_ALIAS (field_decl) = 1;
4338           FIELD_FINAL (field_decl) = 0;
4339         }
4340
4341       /* Check if we must chain. */
4342       if (must_chain)
4343         register_incomplete_type (JDEP_FIELD, wfl, field_decl, type);
4344
4345       /* If we have an initialization value tied to the field */
4346       if (init)
4347         {
4348           /* The field is declared static */
4349           if (flags & ACC_STATIC)
4350             {
4351               /* We include the field and its initialization part into
4352                  a list used to generate <clinit>. After <clinit> is
4353                  walked, field initializations will be processed and
4354                  fields initialized with known constants will be taken
4355                  out of <clinit> and have their DECL_INITIAL set
4356                  appropriately. */
4357               TREE_CHAIN (init) = CPC_STATIC_INITIALIZER_STMT (ctxp);
4358               SET_CPC_STATIC_INITIALIZER_STMT (ctxp, init);
4359               if (TREE_OPERAND (init, 1)
4360                   && TREE_CODE (TREE_OPERAND (init, 1)) == NEW_ARRAY_INIT)
4361                 TREE_STATIC (TREE_OPERAND (init, 1)) = 1;
4362             }
4363           /* A non-static field declared with an immediate initialization is
4364              to be initialized in <init>, if any.  This field is remembered
4365              to be processed at the time of the generation of <init>. */
4366           else
4367             {
4368               TREE_CHAIN (init) = CPC_INITIALIZER_STMT (ctxp);
4369               SET_CPC_INITIALIZER_STMT (ctxp, init);
4370             }
4371           MODIFY_EXPR_FROM_INITIALIZATION_P (init) = 1;
4372           DECL_INITIAL (field_decl) = TREE_OPERAND (init, 1);
4373         }
4374     }
4375
4376   CLEAR_DEPRECATED;
4377   input_line = saved_lineno;
4378 }
4379
4380 /* Generate finit$, using the list of initialized fields to populate
4381    its body. finit$'s parameter(s) list is adjusted to include the
4382    one(s) used to initialized the field(s) caching outer context
4383    local(s).  */
4384
4385 static tree
4386 generate_finit (tree class_type)
4387 {
4388   int count = 0;
4389   tree list = TYPE_FINIT_STMT_LIST (class_type);
4390   tree mdecl, current, parms;
4391
4392   parms = build_alias_initializer_parameter_list (AIPL_FUNCTION_CREATION,
4393                                                   class_type, NULL_TREE,
4394                                                   &count);
4395   CRAFTED_PARAM_LIST_FIXUP (parms);
4396   mdecl = create_artificial_method (class_type, ACC_PRIVATE, void_type_node,
4397                                     finit_identifier_node, parms);
4398   fix_method_argument_names (parms, mdecl);
4399   layout_class_method (class_type, CLASSTYPE_SUPER (class_type),
4400                        mdecl, NULL_TREE);
4401   DECL_FUNCTION_NAP (mdecl) = count;
4402   start_artificial_method_body (mdecl);
4403
4404   for (current = list; current; current = TREE_CHAIN (current))
4405     java_method_add_stmt (mdecl,
4406                           build_debugable_stmt (EXPR_WFL_LINECOL (current),
4407                                                 current));
4408   end_artificial_method_body (mdecl);
4409   return mdecl;
4410 }
4411
4412 /* Generate a function to run the instance initialization code. The
4413    private method is called `instinit$'. Unless we're dealing with an
4414    anonymous class, we determine whether all ctors of CLASS_TYPE
4415    declare a checked exception in their `throws' clause in order to
4416    see whether it's necessary to encapsulate the instance initializer
4417    statements in a try/catch/rethrow sequence.  */
4418
4419 static tree
4420 generate_instinit (tree class_type)
4421 {
4422   tree current;
4423   tree compound = NULL_TREE;
4424   tree parms = tree_cons (this_identifier_node,
4425                           build_pointer_type (class_type), end_params_node);
4426   tree mdecl = create_artificial_method (class_type, ACC_PRIVATE,
4427                                          void_type_node,
4428                                          instinit_identifier_node, parms);
4429
4430   layout_class_method (class_type, CLASSTYPE_SUPER (class_type),
4431                        mdecl, NULL_TREE);
4432
4433   /* Gather all the statements in a compound */
4434   for (current = TYPE_II_STMT_LIST (class_type);
4435        current; current = TREE_CHAIN (current))
4436     compound = add_stmt_to_compound (compound, NULL_TREE, current);
4437
4438   /* We need to encapsulate COMPOUND by a try/catch statement to
4439      rethrow exceptions that might occur in the instance initializer.
4440      We do that only if all ctors of CLASS_TYPE are set to catch a
4441      checked exception. This doesn't apply to anonymous classes (since
4442      they don't have declared ctors.) */
4443   if (!ANONYMOUS_CLASS_P (class_type) &&
4444       ctors_unchecked_throws_clause_p (class_type))
4445     {
4446       compound = encapsulate_with_try_catch (0, exception_type_node, compound,
4447                                              build1 (THROW_EXPR, NULL_TREE,
4448                                                      build_wfl_node (wpv_id)));
4449       DECL_FUNCTION_THROWS (mdecl) = build_tree_list (NULL_TREE,
4450                                                       exception_type_node);
4451     }
4452
4453   start_artificial_method_body (mdecl);
4454   java_method_add_stmt (mdecl, compound);
4455   end_artificial_method_body (mdecl);
4456
4457   return mdecl;
4458 }
4459
4460 /* FIXME */
4461 static tree
4462 build_instinit_invocation (tree class_type)
4463 {
4464   tree to_return = NULL_TREE;
4465
4466   if (TYPE_II_STMT_LIST (class_type))
4467     {
4468       tree parm = build_tree_list (NULL_TREE,
4469                                    build_wfl_node (this_identifier_node));
4470       to_return =
4471         build_method_invocation (build_wfl_node (instinit_identifier_node),
4472                                  parm);
4473     }
4474   return to_return;
4475 }
4476
4477 /* Shared across method_declarator and method_header to remember the
4478    patch stage that was reached during the declaration of the method.
4479    A method DECL is built differently is there is no patch
4480    (JDEP_NO_PATCH) or a patch (JDEP_METHOD or JDEP_METHOD_RETURN)
4481    pending on the currently defined method.  */
4482
4483 static int patch_stage;
4484
4485 /* Check the method declaration and add the method to its current
4486    class.  If the argument list is known to contain incomplete types,
4487    the method is partially added and the registration will be resume
4488    once the method arguments resolved. If TYPE is NULL, we're dealing
4489    with a constructor.  */
4490
4491 static tree
4492 method_header (int flags, tree type, tree mdecl, tree throws)
4493 {
4494   tree type_wfl = NULL_TREE;
4495   tree meth_name = NULL_TREE;
4496   tree current, orig_arg, this_class = NULL;
4497   tree id, meth;
4498   int saved_lineno;
4499   int constructor_ok = 0, must_chain;
4500   int count;
4501
4502   if (mdecl == error_mark_node)
4503     return error_mark_node;
4504   meth = TREE_VALUE (mdecl);
4505   id = TREE_PURPOSE (mdecl);
4506
4507   check_modifiers_consistency (flags);
4508
4509   if (GET_CPC ())
4510     this_class = TREE_TYPE (GET_CPC ());
4511
4512   if (!this_class || this_class == error_mark_node)
4513     return NULL_TREE;
4514
4515   /* There are some forbidden modifiers for an abstract method and its
4516      class must be abstract as well.  */
4517   if (type && (flags & ACC_ABSTRACT))
4518     {
4519       ABSTRACT_CHECK (flags, ACC_PRIVATE, id, "Private");
4520       ABSTRACT_CHECK (flags, ACC_STATIC, id, "Static");
4521       ABSTRACT_CHECK (flags, ACC_FINAL, id, "Final");
4522       ABSTRACT_CHECK (flags, ACC_NATIVE, id, "Native");
4523       ABSTRACT_CHECK (flags, ACC_SYNCHRONIZED, id, "Synchronized");
4524       ABSTRACT_CHECK (flags, ACC_STRICT, id, "Strictfp");
4525       if (!CLASS_ABSTRACT (TYPE_NAME (this_class))
4526           && !CLASS_INTERFACE (TYPE_NAME (this_class)))
4527         parse_error_context
4528           (id, "Class `%s' must be declared abstract to define abstract method `%s'",
4529            IDENTIFIER_POINTER (DECL_NAME (GET_CPC ())),
4530            IDENTIFIER_POINTER (EXPR_WFL_NODE (id)));
4531     }
4532
4533   /* A native method can't be strictfp.  */
4534   if ((flags & ACC_NATIVE) && (flags & ACC_STRICT))
4535     parse_error_context (id, "native method `%s' can't be strictfp",
4536                          IDENTIFIER_POINTER (EXPR_WFL_NODE (id)));
4537   /* No such thing as a transient or volatile method.  */
4538   if ((flags & ACC_TRANSIENT))
4539     parse_error_context (id, "method `%s' can't be transient",
4540                          IDENTIFIER_POINTER (EXPR_WFL_NODE (id)));
4541   if ((flags & ACC_VOLATILE))
4542     parse_error_context (id, "method `%s' can't be volatile",
4543                          IDENTIFIER_POINTER (EXPR_WFL_NODE (id)));
4544
4545   /* Things to be checked when declaring a constructor */
4546   if (!type)
4547     {
4548       int ec = java_error_count;
4549       /* 8.6: Constructor declarations: we might be trying to define a
4550          method without specifying a return type. */
4551       if (EXPR_WFL_NODE (id) != GET_CPC_UN ())
4552         parse_error_context
4553           (id, "Invalid method declaration, return type required");
4554       /* 8.6.3: Constructor modifiers */
4555       else
4556         {
4557           JCONSTRUCTOR_CHECK (flags, ACC_ABSTRACT, id, "abstract");
4558           JCONSTRUCTOR_CHECK (flags, ACC_STATIC, id, "static");
4559           JCONSTRUCTOR_CHECK (flags, ACC_FINAL, id, "final");
4560           JCONSTRUCTOR_CHECK (flags, ACC_NATIVE, id, "native");
4561           JCONSTRUCTOR_CHECK (flags, ACC_SYNCHRONIZED, id, "synchronized");
4562           JCONSTRUCTOR_CHECK (flags, ACC_STRICT, id, "strictfp");
4563         }
4564       /* If we found error here, we don't consider it's OK to tread
4565          the method definition as a constructor, for the rest of this
4566          function */
4567       if (ec == java_error_count)
4568         constructor_ok = 1;
4569     }
4570
4571   /* Method declared within the scope of an interface are implicitly
4572      abstract and public. Conflicts with other erroneously provided
4573      modifiers are checked right after. */
4574
4575   if (CLASS_INTERFACE (TYPE_NAME (this_class)))
4576     {
4577       /* If FLAGS isn't set because of a modifier, turn the
4578          corresponding modifier WFL to NULL so we issue a warning on
4579          the obsolete use of the modifier */
4580       if (!(flags & ACC_PUBLIC))
4581         MODIFIER_WFL (PUBLIC_TK) = NULL;
4582       if (!(flags & ACC_ABSTRACT))
4583         MODIFIER_WFL (ABSTRACT_TK) = NULL;
4584       flags |= ACC_PUBLIC;
4585       flags |= ACC_ABSTRACT;
4586     }
4587
4588   /* Inner class can't declare static methods */
4589   if ((flags & ACC_STATIC) && !TOPLEVEL_CLASS_TYPE_P (this_class))
4590     {
4591       parse_error_context
4592         (id, "Method `%s' can't be static in inner class `%s'. Only members of interfaces and top-level classes can be static",
4593          IDENTIFIER_POINTER (EXPR_WFL_NODE (id)),
4594          lang_printable_name (this_class, 0));
4595     }
4596
4597   /* Modifiers context reset moved up, so abstract method declaration
4598      modifiers can be later checked.  */
4599
4600   /* Set constructor returned type to void and method name to <init>,
4601      unless we found an error identifier the constructor (in which
4602      case we retain the original name) */
4603   if (!type)
4604     {
4605       type = void_type_node;
4606       if (constructor_ok)
4607         meth_name = init_identifier_node;
4608     }
4609   else
4610     meth_name = EXPR_WFL_NODE (id);
4611
4612   /* Do the returned type resolution and registration if necessary */
4613   SET_TYPE_FOR_RESOLUTION (type, type_wfl, must_chain);
4614
4615   if (meth_name)
4616     type = build_array_from_name (type, type_wfl, meth_name, &meth_name);
4617   EXPR_WFL_NODE (id) = meth_name;
4618   PROMOTE_RECORD_IF_COMPLETE (type, must_chain);
4619
4620   if (must_chain)
4621     {
4622       patch_stage = JDEP_METHOD_RETURN;
4623       register_incomplete_type (patch_stage, type_wfl, id, type);
4624       TREE_TYPE (meth) = GET_REAL_TYPE (type);
4625     }
4626   else
4627     TREE_TYPE (meth) = type;
4628
4629   saved_lineno = input_line;
4630   /* When defining an abstract or interface method, the curly
4631      bracket at level 1 doesn't exist because there is no function
4632      body */
4633   input_line = (ctxp->first_ccb_indent1 ? ctxp->first_ccb_indent1 :
4634             EXPR_WFL_LINENO (id));
4635
4636   /* Remember the original argument list */
4637   orig_arg = TYPE_ARG_TYPES (meth);
4638
4639   if (patch_stage)              /* includes ret type and/or all args */
4640     {
4641       jdep *jdep;
4642       meth = add_method_1 (this_class, flags, meth_name, meth);
4643       /* Patch for the return type */
4644       if (patch_stage == JDEP_METHOD_RETURN)
4645         {
4646           jdep = CLASSD_LAST (ctxp->classd_list);
4647           JDEP_GET_PATCH (jdep) = &TREE_TYPE (TREE_TYPE (meth));
4648         }
4649       /* This is the stop JDEP. METH allows the function's signature
4650          to be computed. */
4651       register_incomplete_type (JDEP_METHOD_END, NULL_TREE, meth, NULL_TREE);
4652     }
4653   else
4654     meth = add_method (this_class, flags, meth_name,
4655                        build_java_signature (meth));
4656
4657   /* Remember final parameters */
4658   MARK_FINAL_PARMS (meth, orig_arg);
4659
4660   /* Fix the method argument list so we have the argument name
4661      information */
4662   fix_method_argument_names (orig_arg, meth);
4663
4664   /* Register the parameter number and re-install the current line
4665      number */
4666   DECL_MAX_LOCALS (meth) = ctxp->formal_parameter_number+1;
4667   input_line = saved_lineno;
4668
4669   /* Register exception specified by the `throws' keyword for
4670      resolution and set the method decl appropriate field to the list.
4671      Note: the grammar ensures that what we get here are class
4672      types. */
4673   if (throws)
4674     {
4675       throws = nreverse (throws);
4676       for (current = throws; current; current = TREE_CHAIN (current))
4677         {
4678           register_incomplete_type (JDEP_EXCEPTION, TREE_VALUE (current),
4679                                     NULL_TREE, NULL_TREE);
4680           JDEP_GET_PATCH (CLASSD_LAST (ctxp->classd_list)) =
4681             &TREE_VALUE (current);
4682         }
4683       DECL_FUNCTION_THROWS (meth) = throws;
4684     }
4685
4686   if (TREE_TYPE (GET_CPC ()) != object_type_node)
4687     DECL_FUNCTION_WFL (meth) = id;
4688
4689   /* Set the flag if we correctly processed a constructor */
4690   if (constructor_ok)
4691     {
4692       DECL_CONSTRUCTOR_P (meth) = 1;
4693       /* Compute and store the number of artificial parameters declared
4694          for this constructor */
4695       for (count = 0, current = TYPE_FIELDS (this_class); current;
4696            current = TREE_CHAIN (current))
4697         if (FIELD_LOCAL_ALIAS (current))
4698           count++;
4699       DECL_FUNCTION_NAP (meth) = count;
4700     }
4701
4702   /* Eventually set the @deprecated tag flag */
4703   CHECK_DEPRECATED (meth);
4704
4705   /* If doing xref, store column and line number information instead
4706      of the line number only. */
4707   if (flag_emit_xref)
4708     DECL_SOURCE_LINE (meth) = EXPR_WFL_LINECOL (id);
4709
4710   return meth;
4711 }
4712
4713 static void
4714 fix_method_argument_names (tree orig_arg, tree meth)
4715 {
4716   tree arg = TYPE_ARG_TYPES (TREE_TYPE (meth));
4717   if (TREE_CODE (TREE_TYPE (meth)) == METHOD_TYPE)
4718     {
4719       TREE_PURPOSE (arg) = this_identifier_node;
4720       arg = TREE_CHAIN (arg);
4721     }
4722   while (orig_arg != end_params_node)
4723     {
4724       TREE_PURPOSE (arg) = TREE_PURPOSE (orig_arg);
4725       orig_arg = TREE_CHAIN (orig_arg);
4726       arg = TREE_CHAIN (arg);
4727     }
4728 }
4729
4730 /* Complete the method declaration with METHOD_BODY.  */
4731
4732 static void
4733 finish_method_declaration (tree method_body)
4734 {
4735   int flags;
4736
4737   if (!current_function_decl)
4738     return;
4739
4740   flags = get_access_flags_from_decl (current_function_decl);
4741
4742   /* 8.4.5 Method Body */
4743   if ((flags & ACC_ABSTRACT || flags & ACC_NATIVE) && method_body)
4744     {
4745       tree name = DECL_NAME (current_function_decl);
4746       parse_error_context (DECL_FUNCTION_WFL (current_function_decl),
4747                            "%s method `%s' can't have a body defined",
4748                            (METHOD_NATIVE (current_function_decl) ?
4749                             "Native" : "Abstract"),
4750                            IDENTIFIER_POINTER (name));
4751       method_body = NULL_TREE;
4752     }
4753   else if (!(flags & ACC_ABSTRACT) && !(flags & ACC_NATIVE) && !method_body)
4754     {
4755       tree name = DECL_NAME (current_function_decl);
4756       parse_error_context
4757         (DECL_FUNCTION_WFL (current_function_decl),
4758          "Non native and non abstract method `%s' must have a body defined",
4759          IDENTIFIER_POINTER (name));
4760       method_body = NULL_TREE;
4761     }
4762
4763   if (flag_emit_class_files && method_body
4764       && TREE_CODE (method_body) == NOP_EXPR
4765       && TREE_TYPE (current_function_decl)
4766       && TREE_TYPE (TREE_TYPE (current_function_decl)) == void_type_node)
4767     method_body = build1 (RETURN_EXPR, void_type_node, NULL);
4768
4769   BLOCK_EXPR_BODY (DECL_FUNCTION_BODY (current_function_decl)) = method_body;
4770   maybe_absorb_scoping_blocks ();
4771   /* Exit function's body */
4772   exit_block ();
4773   /* Merge last line of the function with first line, directly in the
4774      function decl. It will be used to emit correct debug info. */
4775   if (!flag_emit_xref)
4776     DECL_FUNCTION_LAST_LINE (current_function_decl) = ctxp->last_ccb_indent1;
4777
4778   /* Since function's argument's list are shared, reset the
4779      ARG_FINAL_P parameter that might have been set on some of this
4780      function parameters. */
4781   UNMARK_FINAL_PARMS (current_function_decl);
4782
4783   /* So we don't have an irrelevant function declaration context for
4784      the next static block we'll see. */
4785   current_function_decl = NULL_TREE;
4786 }
4787
4788 /* Build a an error message for constructor circularity errors.  */
4789
4790 static char *
4791 constructor_circularity_msg (tree from, tree to)
4792 {
4793   static char string [4096];
4794   char *t = xstrdup (lang_printable_name (from, 0));
4795   sprintf (string, "`%s' invokes `%s'", t, lang_printable_name (to, 0));
4796   free (t);
4797   return string;
4798 }
4799
4800 /* Verify a circular call to METH. Return 1 if an error is found, 0
4801    otherwise.  */
4802
4803 static GTY(()) tree vcc_list;
4804 static int
4805 verify_constructor_circularity (tree meth, tree current)
4806 {
4807   tree c;
4808
4809   for (c = DECL_CONSTRUCTOR_CALLS (current); c; c = TREE_CHAIN (c))
4810     {
4811       if (TREE_VALUE (c) == meth)
4812         {
4813           char *t;
4814           if (vcc_list)
4815             {
4816               tree liste;
4817               vcc_list = nreverse (vcc_list);
4818               for (liste = vcc_list; liste; liste = TREE_CHAIN (liste))
4819                 {
4820                   parse_error_context
4821                     (TREE_PURPOSE (TREE_PURPOSE (liste)), "%s",
4822                      constructor_circularity_msg
4823                       (TREE_VALUE (liste), TREE_VALUE (TREE_PURPOSE (liste))));
4824                   java_error_count--;
4825                 }
4826             }
4827           t = xstrdup (lang_printable_name (meth, 0));
4828           parse_error_context (TREE_PURPOSE (c),
4829                                "%s: recursive invocation of constructor `%s'",
4830                                constructor_circularity_msg (current, meth), t);
4831           free (t);
4832           vcc_list = NULL_TREE;
4833           return 1;
4834         }
4835     }
4836   for (c = DECL_CONSTRUCTOR_CALLS (current); c; c = TREE_CHAIN (c))
4837     {
4838       vcc_list = tree_cons (c, current, vcc_list);
4839       if (verify_constructor_circularity (meth, TREE_VALUE (c)))
4840         return 1;
4841       vcc_list = TREE_CHAIN (vcc_list);
4842     }
4843   return 0;
4844 }
4845
4846 /* Check modifiers that can be declared but exclusively */
4847
4848 static void
4849 check_modifiers_consistency (int flags)
4850 {
4851   int acc_count = 0;
4852   tree cl = NULL_TREE;
4853
4854   THIS_MODIFIER_ONLY (flags, ACC_PUBLIC, PUBLIC_TK, acc_count, cl);
4855   THIS_MODIFIER_ONLY (flags, ACC_PRIVATE, PRIVATE_TK, acc_count, cl);
4856   THIS_MODIFIER_ONLY (flags, ACC_PROTECTED, PROTECTED_TK, acc_count, cl);
4857   if (acc_count > 1)
4858     parse_error_context
4859       (cl, "Inconsistent member declaration.  At most one of `public', `private', or `protected' may be specified");
4860
4861   acc_count = 0;
4862   cl = NULL_TREE;
4863   THIS_MODIFIER_ONLY (flags, ACC_FINAL, FINAL_TK, acc_count, cl);
4864   THIS_MODIFIER_ONLY (flags, ACC_VOLATILE, VOLATILE_TK, acc_count, cl);
4865   if (acc_count > 1)
4866     parse_error_context (cl,
4867                          "Inconsistent member declaration.  At most one of `final' or `volatile' may be specified");
4868 }
4869
4870 /* Check the methode header METH for abstract specifics features */
4871
4872 static void
4873 check_abstract_method_header (tree meth)
4874 {
4875   int flags = get_access_flags_from_decl (meth);
4876
4877   OBSOLETE_MODIFIER_WARNING2 (MODIFIER_WFL (ABSTRACT_TK), flags,
4878                               ACC_ABSTRACT, "abstract method",
4879                               IDENTIFIER_POINTER (DECL_NAME (meth)));
4880   OBSOLETE_MODIFIER_WARNING2 (MODIFIER_WFL (PUBLIC_TK), flags,
4881                               ACC_PUBLIC, "abstract method",
4882                               IDENTIFIER_POINTER (DECL_NAME (meth)));
4883
4884   check_modifiers ("Illegal modifier `%s' for interface method",
4885                   flags, INTERFACE_METHOD_MODIFIERS);
4886 }
4887
4888 /* Create a FUNCTION_TYPE node and start augmenting it with the
4889    declared function arguments. Arguments type that can't be resolved
4890    are left as they are, but the returned node is marked as containing
4891    incomplete types.  */
4892
4893 static tree
4894 method_declarator (tree id, tree list)
4895 {
4896   tree arg_types = NULL_TREE, current, node;
4897   tree meth = make_node (FUNCTION_TYPE);
4898   jdep *jdep;
4899
4900   patch_stage = JDEP_NO_PATCH;
4901
4902   if (GET_CPC () == error_mark_node)
4903     return error_mark_node;
4904
4905   /* If we're dealing with an inner class constructor, we hide the
4906      this$<n> decl in the name field of its parameter declaration.  We
4907      also might have to hide the outer context local alias
4908      initializers. Not done when the class is a toplevel class. */
4909   if (PURE_INNER_CLASS_DECL_P (GET_CPC ())
4910       && EXPR_WFL_NODE (id) == GET_CPC_UN ())
4911     {
4912       tree aliases_list, type, thisn;
4913       /* First the aliases, linked to the regular parameters */
4914       aliases_list =
4915         build_alias_initializer_parameter_list (AIPL_FUNCTION_DECLARATION,
4916                                                 TREE_TYPE (GET_CPC ()),
4917                                                 NULL_TREE, NULL);
4918       list = chainon (nreverse (aliases_list), list);
4919
4920       /* Then this$<n> */
4921       type = TREE_TYPE (DECL_CONTEXT (GET_CPC ()));
4922       thisn = build_current_thisn (TREE_TYPE (GET_CPC ()));
4923       list = tree_cons (build_wfl_node (thisn), build_pointer_type (type),
4924                         list);
4925     }
4926
4927   for (current = list; current; current = TREE_CHAIN (current))
4928     {
4929       int must_chain = 0;
4930       tree wfl_name = TREE_PURPOSE (current);
4931       tree type = TREE_VALUE (current);
4932       tree name = EXPR_WFL_NODE (wfl_name);
4933       tree already, arg_node;
4934       tree type_wfl = NULL_TREE;
4935       tree real_type;
4936
4937       /* Obtain a suitable type for resolution, if necessary */
4938       SET_TYPE_FOR_RESOLUTION (type, type_wfl, must_chain);
4939
4940       /* Process NAME, as it may specify extra dimension(s) for it */
4941       type = build_array_from_name (type, type_wfl, name, &name);
4942       EXPR_WFL_NODE (wfl_name) = name;
4943
4944       real_type = GET_REAL_TYPE (type);
4945       if (TREE_CODE (real_type) == RECORD_TYPE)
4946         {
4947           real_type = promote_type (real_type);
4948           if (TREE_CODE (type) == TREE_LIST)
4949             TREE_PURPOSE (type) = real_type;
4950         }
4951
4952       /* Check redefinition */
4953       for (already = arg_types; already; already = TREE_CHAIN (already))
4954         if (TREE_PURPOSE (already) == name)
4955           {
4956             parse_error_context
4957               (wfl_name, "Variable `%s' is used more than once in the argument list of method `%s'",
4958                IDENTIFIER_POINTER (name),
4959                IDENTIFIER_POINTER (EXPR_WFL_NODE (id)));
4960             break;
4961           }
4962
4963       /* If we've an incomplete argument type, we know there is a location
4964          to patch when the type get resolved, later.  */
4965       jdep = NULL;
4966       if (must_chain)
4967         {
4968           patch_stage = JDEP_METHOD;
4969           type = register_incomplete_type (patch_stage,
4970                                            type_wfl, wfl_name, type);
4971           jdep = CLASSD_LAST (ctxp->classd_list);
4972           JDEP_MISC (jdep) = id;
4973         }
4974
4975       /* The argument node: a name and a (possibly) incomplete type.  */
4976       arg_node = build_tree_list (name, real_type);
4977       /* Remember arguments declared final. */
4978       ARG_FINAL_P (arg_node) = ARG_FINAL_P (current);
4979
4980       if (jdep)
4981         JDEP_GET_PATCH (jdep) = &TREE_VALUE (arg_node);
4982       TREE_CHAIN (arg_node) = arg_types;
4983       arg_types = arg_node;
4984     }
4985   TYPE_ARG_TYPES (meth) = chainon (nreverse (arg_types), end_params_node);
4986   node = build_tree_list (id, meth);
4987   return node;
4988 }
4989
4990 static int
4991 unresolved_type_p (tree wfl, tree *returned)
4992
4993 {
4994   if (TREE_CODE (wfl) == EXPR_WITH_FILE_LOCATION)
4995     {
4996       if (returned)
4997         {
4998           tree decl = IDENTIFIER_CLASS_VALUE (EXPR_WFL_NODE (wfl));
4999           if (decl && current_class && (decl == TYPE_NAME (current_class)))
5000             *returned = TREE_TYPE (decl);
5001           else if (GET_CPC_UN () == EXPR_WFL_NODE (wfl))
5002             *returned = TREE_TYPE (GET_CPC ());
5003           else
5004             *returned = NULL_TREE;
5005         }
5006       return 1;
5007     }
5008   if (returned)
5009     *returned = wfl;
5010   return 0;
5011 }
5012
5013 /* From NAME, build a qualified identifier node using the
5014    qualification from the current package definition. */
5015
5016 static tree
5017 parser_qualified_classname (tree name)
5018 {
5019   tree nested_class_name;
5020
5021   if ((nested_class_name = maybe_make_nested_class_name (name)))
5022     return nested_class_name;
5023
5024   if (ctxp->package)
5025     return merge_qualified_name (ctxp->package, name);
5026   else
5027     return name;
5028 }
5029
5030 /* Called once the type a interface extends is resolved. Returns 0 if
5031    everything is OK.  */
5032
5033 static int
5034 parser_check_super_interface (tree super_decl, tree this_decl, tree this_wfl)
5035 {
5036   tree super_type = TREE_TYPE (super_decl);
5037
5038   /* Has to be an interface */
5039   if (!CLASS_INTERFACE (super_decl))
5040     {
5041       parse_error_context
5042         (this_wfl, "%s `%s' can't implement/extend %s `%s'",
5043          (CLASS_INTERFACE (TYPE_NAME (TREE_TYPE (this_decl))) ?
5044           "Interface" : "Class"),
5045          IDENTIFIER_POINTER (DECL_NAME (this_decl)),
5046          (TYPE_ARRAY_P (super_type) ? "array" : "class"),
5047          IDENTIFIER_POINTER (DECL_NAME (super_decl)));
5048       return 1;
5049     }
5050
5051   /* Check top-level interface access. Inner classes are subject to member
5052      access rules (6.6.1). */
5053   if (! INNER_CLASS_P (super_type)
5054       && check_pkg_class_access (DECL_NAME (super_decl),
5055                                  lookup_cl (this_decl), true))
5056     return 1;
5057
5058   SOURCE_FRONTEND_DEBUG (("Completing interface %s with %s",
5059                           IDENTIFIER_POINTER (DECL_NAME (this_decl)),
5060                           IDENTIFIER_POINTER (DECL_NAME (super_decl))));
5061   return 0;
5062 }
5063
5064 /* Makes sure that SUPER_DECL is suitable to extend THIS_DECL. Returns
5065    0 if everything is OK.  */
5066
5067 static int
5068 parser_check_super (tree super_decl, tree this_decl, tree wfl)
5069 {
5070   tree super_type = TREE_TYPE (super_decl);
5071
5072   /* SUPER should be a CLASS (neither an array nor an interface) */
5073   if (TYPE_ARRAY_P (super_type) || CLASS_INTERFACE (TYPE_NAME (super_type)))
5074     {
5075       parse_error_context
5076         (wfl, "Class `%s' can't subclass %s `%s'",
5077          IDENTIFIER_POINTER (DECL_NAME (this_decl)),
5078          (CLASS_INTERFACE (TYPE_NAME (super_type)) ? "interface" : "array"),
5079          IDENTIFIER_POINTER (DECL_NAME (super_decl)));
5080       return 1;
5081     }
5082
5083   if (CLASS_FINAL (TYPE_NAME (super_type)))
5084     {
5085       parse_error_context (wfl, "Can't subclass final classes: %s",
5086                            IDENTIFIER_POINTER (DECL_NAME (super_decl)));
5087       return 1;
5088     }
5089
5090   /* Check top-level class scope. Inner classes are subject to member access
5091      rules (6.6.1). */
5092   if (! INNER_CLASS_P (super_type)
5093       && (check_pkg_class_access (DECL_NAME (super_decl), wfl, true)))
5094     return 1;
5095
5096   SOURCE_FRONTEND_DEBUG (("Completing class %s with %s",
5097                           IDENTIFIER_POINTER (DECL_NAME (this_decl)),
5098                           IDENTIFIER_POINTER (DECL_NAME (super_decl))));
5099   return 0;
5100 }
5101
5102 /* Create a new dependency list and link it (in a LIFO manner) to the
5103    CTXP list of type dependency list.  */
5104
5105 static void
5106 create_jdep_list (struct parser_ctxt *ctxp)
5107 {
5108   jdeplist *new = xmalloc (sizeof (jdeplist));
5109   new->first = new->last = NULL;
5110   new->next = ctxp->classd_list;
5111   ctxp->classd_list = new;
5112 }
5113
5114 static jdeplist *
5115 reverse_jdep_list (struct parser_ctxt *ctxp)
5116 {
5117   register jdeplist *prev = NULL, *current, *next;
5118   for (current = ctxp->classd_list; current; current = next)
5119     {
5120       next = current->next;
5121       current->next = prev;
5122       prev = current;
5123     }
5124   return prev;
5125 }
5126
5127 /* Create a fake pointer based on the ID stored in
5128    TYPE_NAME. TYPE_NAME can be a WFL or a incomplete type asking to be
5129    registered again. */
5130
5131 static tree
5132 obtain_incomplete_type (tree type_name)
5133 {
5134   tree ptr = NULL_TREE, name;
5135
5136   if (TREE_CODE (type_name) == EXPR_WITH_FILE_LOCATION)
5137     name = EXPR_WFL_NODE (type_name);
5138   else if (INCOMPLETE_TYPE_P (type_name))
5139     name = TYPE_NAME (type_name);
5140   else
5141     abort ();
5142
5143   /* Workaround from build_pointer_type for incomplete types.  */
5144   BUILD_PTR_FROM_NAME (ptr, name);
5145   TYPE_MODE (ptr) = ptr_mode;
5146   layout_type (ptr);
5147
5148   return ptr;
5149 }
5150
5151 /* Register a incomplete type whose name is WFL. Reuse PTR if PTR is
5152    non NULL instead of computing a new fake type based on WFL. The new
5153    dependency is inserted in the current type dependency list, in FIFO
5154    manner.  */
5155
5156 static tree
5157 register_incomplete_type (int kind, tree wfl, tree decl, tree ptr)
5158 {
5159   jdep *new = xmalloc (sizeof (jdep));
5160
5161   if (!ptr && kind != JDEP_METHOD_END) /* JDEP_METHOD_END is a mere marker */
5162     ptr = obtain_incomplete_type (wfl);
5163
5164   JDEP_KIND (new) = kind;
5165   JDEP_DECL (new) = decl;
5166   JDEP_TO_RESOLVE (new) = ptr;
5167   JDEP_WFL (new) = wfl;
5168   JDEP_CHAIN (new) = NULL;
5169   JDEP_MISC (new) = NULL_TREE;
5170   /* For some dependencies, set the enclosing class of the current
5171      class to be the enclosing context */
5172   if ((kind == JDEP_INTERFACE  || kind == JDEP_ANONYMOUS)
5173       && GET_ENCLOSING_CPC ())
5174     JDEP_ENCLOSING (new) = TREE_VALUE (GET_ENCLOSING_CPC ());
5175   else if (kind == JDEP_SUPER)
5176     JDEP_ENCLOSING (new) = (GET_ENCLOSING_CPC () ?
5177                             TREE_VALUE (GET_ENCLOSING_CPC ()) : NULL_TREE);
5178   else
5179     JDEP_ENCLOSING (new) = GET_CPC ();
5180   JDEP_GET_PATCH (new) = (tree *)NULL;
5181
5182   JDEP_INSERT (ctxp->classd_list, new);
5183
5184   return ptr;
5185 }
5186
5187 /* This checks for circular references with innerclasses. We start
5188    from SOURCE and should never reach TARGET. Extended/implemented
5189    types in SOURCE have their enclosing context checked not to reach
5190    TARGET. When the last enclosing context of SOURCE is reached, its
5191    extended/implemented types are also checked not to reach TARGET.
5192    In case of error, WFL of the offending type is returned; NULL_TREE
5193    otherwise.  */
5194
5195 static tree
5196 check_inner_circular_reference (tree source, tree target)
5197 {
5198   tree basetype_vec = TYPE_BINFO_BASETYPES (source);
5199   tree ctx, cl;
5200   int i;
5201
5202   if (!basetype_vec)
5203     return NULL_TREE;
5204
5205   for (i = 0; i < TREE_VEC_LENGTH (basetype_vec); i++)
5206     {
5207       tree su;
5208
5209       /* We can end up with a NULL_TREE or an incomplete type here if
5210          we encountered previous type resolution errors. It's safe to
5211          simply ignore these cases.  */
5212       if (TREE_VEC_ELT (basetype_vec, i) == NULL_TREE)
5213         continue;
5214       su = BINFO_TYPE (TREE_VEC_ELT (basetype_vec, i));
5215       if (INCOMPLETE_TYPE_P (su))
5216         continue;
5217
5218       if (inherits_from_p (su, target))
5219         return lookup_cl (TYPE_NAME (su));
5220
5221       for (ctx = DECL_CONTEXT (TYPE_NAME (su)); ctx; ctx = DECL_CONTEXT (ctx))
5222         {
5223           /* An enclosing context shouldn't be TARGET */
5224           if (ctx == TYPE_NAME (target))
5225             return lookup_cl (TYPE_NAME (su));
5226
5227           /* When we reach the enclosing last context, start a check
5228              on it, with the same target */
5229           if (! DECL_CONTEXT (ctx) &&
5230               (cl = check_inner_circular_reference (TREE_TYPE (ctx), target)))
5231             return cl;
5232         }
5233     }
5234   return NULL_TREE;
5235 }
5236
5237 /* Explore TYPE's `extends' clause member(s) and return the WFL of the
5238    offending type if a circularity is detected. NULL_TREE is returned
5239    otherwise. TYPE can be an interface or a class.   */
5240
5241 static tree
5242 check_circular_reference (tree type)
5243 {
5244   tree basetype_vec = TYPE_BINFO_BASETYPES (type);
5245   int i;
5246
5247   if (!basetype_vec)
5248     return NULL_TREE;
5249
5250   if (! CLASS_INTERFACE (TYPE_NAME (type)))
5251     {
5252       if (inherits_from_p (CLASSTYPE_SUPER (type), type))
5253         return lookup_cl (TYPE_NAME (type));
5254       return NULL_TREE;
5255     }
5256
5257   for (i = 0; i < TREE_VEC_LENGTH (basetype_vec); i++)
5258     {
5259       tree vec_elt = TREE_VEC_ELT (basetype_vec, i);
5260       if (vec_elt && BINFO_TYPE (vec_elt) != object_type_node
5261           && interface_of_p (type, BINFO_TYPE (vec_elt)))
5262         return lookup_cl (TYPE_NAME (BINFO_TYPE (vec_elt)));
5263     }
5264   return NULL_TREE;
5265 }
5266
5267 void
5268 java_check_circular_reference (void)
5269 {
5270   tree current;
5271   for (current = ctxp->class_list; current; current = TREE_CHAIN (current))
5272     {
5273       tree type = TREE_TYPE (current);
5274       tree cl;
5275
5276       cl = check_circular_reference (type);
5277       if (! cl)
5278         cl = check_inner_circular_reference (type, type);
5279       if (cl)
5280         parse_error_context (cl, "Cyclic class inheritance%s",
5281                              (cyclic_inheritance_report ?
5282                               cyclic_inheritance_report : ""));
5283     }
5284 }
5285
5286 /* Augment the parameter list PARM with parameters crafted to
5287    initialize outer context locals aliases. Through ARTIFICIAL, a
5288    count is kept of the number of crafted parameters. MODE governs
5289    what eventually gets created: something suitable for a function
5290    creation or a function invocation, either the constructor or
5291    finit$.  */
5292
5293 static tree
5294 build_alias_initializer_parameter_list (int mode, tree class_type, tree parm,
5295                                         int *artificial)
5296 {
5297   tree field;
5298   tree additional_parms = NULL_TREE;
5299
5300   for (field = TYPE_FIELDS (class_type); field; field = TREE_CHAIN (field))
5301     if (FIELD_LOCAL_ALIAS (field))
5302       {
5303         const char *buffer = IDENTIFIER_POINTER (DECL_NAME (field));
5304         tree purpose = NULL_TREE, value = NULL_TREE, name = NULL_TREE;
5305         tree mangled_id;
5306
5307         switch (mode)
5308           {
5309           case AIPL_FUNCTION_DECLARATION:
5310             MANGLE_ALIAS_INITIALIZER_PARAMETER_NAME_STR (mangled_id,
5311                                                          &buffer [4]);
5312             purpose = build_wfl_node (mangled_id);
5313             if (TREE_CODE (TREE_TYPE (field)) == POINTER_TYPE)
5314               value = build_wfl_node (TYPE_NAME (TREE_TYPE (field)));
5315             else
5316               value = TREE_TYPE (field);
5317             break;
5318
5319           case AIPL_FUNCTION_CREATION:
5320             MANGLE_ALIAS_INITIALIZER_PARAMETER_NAME_STR (purpose,
5321                                                          &buffer [4]);
5322             value = TREE_TYPE (field);
5323             break;
5324
5325           case AIPL_FUNCTION_FINIT_INVOCATION:
5326             MANGLE_ALIAS_INITIALIZER_PARAMETER_NAME_STR (mangled_id,
5327                                                          &buffer [4]);
5328             /* Now, this is wrong. purpose should always be the NAME
5329                of something and value its matching value (decl, type,
5330                etc...) FIXME -- but there is a lot to fix. */
5331
5332             /* When invoked for this kind of operation, we already
5333                know whether a field is used or not. */
5334             purpose = TREE_TYPE (field);
5335             value = build_wfl_node (mangled_id);
5336             break;
5337
5338           case AIPL_FUNCTION_CTOR_INVOCATION:
5339             /* There are two case: the constructor invocation happens
5340                outside the local inner, in which case, locales from the outer
5341                context are directly used.
5342
5343                Otherwise, we fold to using the alias directly. */
5344             if (class_type == current_class)
5345               value = field;
5346             else
5347               {
5348                 name = get_identifier (&buffer[4]);
5349                 value = IDENTIFIER_LOCAL_VALUE (name);
5350               }
5351             break;
5352           }
5353         additional_parms = tree_cons (purpose, value, additional_parms);
5354         if (artificial)
5355           *artificial +=1;
5356       }
5357   if (additional_parms)
5358     {
5359       if (ANONYMOUS_CLASS_P (class_type)
5360           && mode == AIPL_FUNCTION_CTOR_INVOCATION)
5361         additional_parms = nreverse (additional_parms);
5362       parm = chainon (additional_parms, parm);
5363     }
5364
5365    return parm;
5366 }
5367
5368 /* Craft a constructor for CLASS_DECL -- what we should do when none
5369    where found. ARGS is non NULL when a special signature must be
5370    enforced. This is the case for anonymous classes.  */
5371
5372 static tree
5373 craft_constructor (tree class_decl, tree args)
5374 {
5375   tree class_type = TREE_TYPE (class_decl);
5376   tree parm = NULL_TREE;
5377   int flags = (get_access_flags_from_decl (class_decl) & ACC_PUBLIC ?
5378                ACC_PUBLIC : 0);
5379   int i = 0, artificial = 0;
5380   tree decl, ctor_name;
5381   char buffer [80];
5382
5383   /* The constructor name is <init> unless we're dealing with an
5384      anonymous class, in which case the name will be fixed after having
5385      be expanded. */
5386   if (ANONYMOUS_CLASS_P (class_type))
5387     ctor_name = DECL_NAME (class_decl);
5388   else
5389     ctor_name = init_identifier_node;
5390
5391   /* If we're dealing with an inner class constructor, we hide the
5392      this$<n> decl in the name field of its parameter declaration. */
5393   if (PURE_INNER_CLASS_TYPE_P (class_type))
5394     {
5395       tree type = TREE_TYPE (DECL_CONTEXT (TYPE_NAME (class_type)));
5396       parm = tree_cons (build_current_thisn (class_type),
5397                         build_pointer_type (type), parm);
5398
5399       /* Some more arguments to be hidden here. The values of the local
5400          variables of the outer context that the inner class needs to see. */
5401       parm = build_alias_initializer_parameter_list (AIPL_FUNCTION_CREATION,
5402                                                      class_type, parm,
5403                                                      &artificial);
5404     }
5405
5406   /* Then if there are any args to be enforced, enforce them now */
5407   for (; args && args != end_params_node; args = TREE_CHAIN (args))
5408     {
5409       sprintf (buffer, "parm%d", i++);
5410       parm = tree_cons (get_identifier (buffer), TREE_VALUE (args), parm);
5411     }
5412
5413   CRAFTED_PARAM_LIST_FIXUP (parm);
5414   decl = create_artificial_method (class_type, flags, void_type_node,
5415                                    ctor_name, parm);
5416   fix_method_argument_names (parm, decl);
5417   /* Now, mark the artificial parameters. */
5418   DECL_FUNCTION_NAP (decl) = artificial;
5419   DECL_FUNCTION_SYNTHETIC_CTOR (decl) = DECL_CONSTRUCTOR_P (decl) = 1;
5420   DECL_INLINE (decl) = 1;
5421   return decl;
5422 }
5423
5424
5425 /* Fix the constructors. This will be called right after circular
5426    references have been checked. It is necessary to fix constructors
5427    early even if no code generation will take place for that class:
5428    some generated constructor might be required by the class whose
5429    compilation triggered this one to be simply loaded.  */
5430
5431 void
5432 java_fix_constructors (void)
5433 {
5434   tree current;
5435
5436   for (current = ctxp->class_list; current; current = TREE_CHAIN (current))
5437     {
5438       tree class_type = TREE_TYPE (current);
5439       int saw_ctor = 0;
5440       tree decl;
5441
5442       if (CLASS_INTERFACE (TYPE_NAME (class_type)))
5443         continue;
5444
5445       current_class = class_type;
5446       for (decl = TYPE_METHODS (class_type); decl; decl = TREE_CHAIN (decl))
5447         {
5448           if (DECL_CONSTRUCTOR_P (decl))
5449             {
5450               fix_constructors (decl);
5451               saw_ctor = 1;
5452             }
5453         }
5454
5455       /* Anonymous class constructor can't be generated that early. */
5456       if (!saw_ctor && !ANONYMOUS_CLASS_P (class_type))
5457         craft_constructor (current, NULL_TREE);
5458     }
5459 }
5460
5461 /* safe_layout_class just makes sure that we can load a class without
5462    disrupting the current_class, input_file, lineno, etc, information
5463    about the class processed currently.  */
5464
5465 void
5466 safe_layout_class (tree class)
5467 {
5468   tree save_current_class = current_class;
5469   location_t save_location = input_location;
5470
5471   layout_class (class);
5472
5473   current_class = save_current_class;
5474   input_location = save_location;
5475 }
5476
5477 static tree
5478 jdep_resolve_class (jdep *dep)
5479 {
5480   tree decl;
5481
5482   if (JDEP_RESOLVED_P (dep))
5483     decl = JDEP_RESOLVED_DECL (dep);
5484   else
5485     {
5486       decl = resolve_class (JDEP_ENCLOSING (dep), JDEP_TO_RESOLVE (dep),
5487                             JDEP_DECL (dep), JDEP_WFL (dep));
5488       JDEP_RESOLVED (dep, decl);
5489       /* If there is no WFL, that's ok.  We generate this warning
5490          elsewhere.  */
5491       if (decl && JDEP_WFL (dep) != NULL_TREE)
5492         check_deprecation (JDEP_WFL (dep), decl);
5493     }
5494
5495   if (!decl)
5496     complete_class_report_errors (dep);
5497   else if (PURE_INNER_CLASS_DECL_P (decl))
5498     {
5499       tree inner = TREE_TYPE (decl);
5500       if (! CLASS_LOADED_P (inner))
5501         {
5502           safe_layout_class (inner);
5503           if (TYPE_SIZE (inner) == error_mark_node)
5504             TYPE_SIZE (inner) = NULL_TREE;
5505         }
5506       check_inner_class_access (decl, JDEP_ENCLOSING (dep), JDEP_WFL (dep));
5507     }
5508   return decl;
5509 }
5510
5511 /* Complete unsatisfied class declaration and their dependencies */
5512
5513 void
5514 java_complete_class (void)
5515 {
5516   tree cclass;
5517   jdeplist *cclassd;
5518   int error_found;
5519   tree type;
5520
5521   /* Process imports */
5522   process_imports ();
5523
5524   /* Reverse things so we have the right order */
5525   ctxp->class_list = nreverse (ctxp->class_list);
5526   ctxp->classd_list = reverse_jdep_list (ctxp);
5527
5528   for (cclassd = ctxp->classd_list, cclass = ctxp->class_list;
5529        cclass && cclassd;
5530        cclass = TREE_CHAIN (cclass), cclassd = CLASSD_CHAIN (cclassd))
5531     {
5532       jdep *dep;
5533
5534       /* We keep the compilation unit imports in the class so that
5535          they can be used later to resolve type dependencies that
5536          aren't necessary to solve now. */
5537       TYPE_IMPORT_LIST (TREE_TYPE (cclass)) = ctxp->import_list;
5538       TYPE_IMPORT_DEMAND_LIST (TREE_TYPE (cclass)) = ctxp->import_demand_list;
5539
5540       for (dep = CLASSD_FIRST (cclassd); dep; dep = JDEP_CHAIN (dep))
5541         {
5542           tree decl;
5543           if (!(decl = jdep_resolve_class (dep)))
5544             continue;
5545
5546           /* Now it's time to patch */
5547           switch (JDEP_KIND (dep))
5548             {
5549             case JDEP_SUPER:
5550               /* Simply patch super */
5551               if (parser_check_super (decl, JDEP_DECL (dep), JDEP_WFL (dep)))
5552                 continue;
5553               BINFO_TYPE (TREE_VEC_ELT (BINFO_BASETYPES (TYPE_BINFO
5554                 (TREE_TYPE (JDEP_DECL (dep)))), 0)) = TREE_TYPE (decl);
5555               break;
5556
5557             case JDEP_FIELD:
5558               {
5559                 /* We do part of the job done in add_field */
5560                 tree field_decl = JDEP_DECL (dep);
5561                 tree field_type = TREE_TYPE (decl);
5562                 if (TREE_CODE (field_type) == RECORD_TYPE)
5563                   field_type = promote_type (field_type);
5564                 TREE_TYPE (field_decl) = field_type;
5565                 DECL_ALIGN (field_decl) = 0;
5566                 DECL_USER_ALIGN (field_decl) = 0;
5567                 layout_decl (field_decl, 0);
5568                 SOURCE_FRONTEND_DEBUG
5569                   (("Completed field/var decl `%s' with `%s'",
5570                     IDENTIFIER_POINTER (DECL_NAME (field_decl)),
5571                     IDENTIFIER_POINTER (DECL_NAME (decl))));
5572                 break;
5573               }
5574             case JDEP_METHOD:   /* We start patching a method */
5575             case JDEP_METHOD_RETURN:
5576               error_found = 0;
5577               while (1)
5578                 {
5579                   if (decl)
5580                     {
5581                       type = TREE_TYPE(decl);
5582                       if (TREE_CODE (type) == RECORD_TYPE)
5583                         type = promote_type (type);
5584                       JDEP_APPLY_PATCH (dep, type);
5585                       SOURCE_FRONTEND_DEBUG
5586                         (((JDEP_KIND (dep) == JDEP_METHOD_RETURN ?
5587                            "Completing fct `%s' with ret type `%s'":
5588                            "Completing arg `%s' with type `%s'"),
5589                           IDENTIFIER_POINTER (EXPR_WFL_NODE
5590                                               (JDEP_DECL_WFL (dep))),
5591                           IDENTIFIER_POINTER (DECL_NAME (decl))));
5592                     }
5593                   else
5594                     error_found = 1;
5595                   dep = JDEP_CHAIN (dep);
5596                   if (JDEP_KIND (dep) == JDEP_METHOD_END)
5597                     break;
5598                   else
5599                     decl = jdep_resolve_class (dep);
5600                 }
5601               if (!error_found)
5602                 {
5603                   tree mdecl = JDEP_DECL (dep), signature;
5604                   /* Recompute and reset the signature, check first that
5605                      all types are now defined. If they're not,
5606                      don't build the signature. */
5607                   if (check_method_types_complete (mdecl))
5608                     {
5609                       signature = build_java_signature (TREE_TYPE (mdecl));
5610                       set_java_signature (TREE_TYPE (mdecl), signature);
5611                     }
5612                 }
5613               else
5614                 continue;
5615               break;
5616
5617             case JDEP_INTERFACE:
5618               if (parser_check_super_interface (decl, JDEP_DECL (dep),
5619                                                 JDEP_WFL (dep)))
5620                 continue;
5621               parser_add_interface (JDEP_DECL (dep), decl, JDEP_WFL (dep));
5622               break;
5623
5624             case JDEP_PARM:
5625             case JDEP_VARIABLE:
5626               type = TREE_TYPE(decl);
5627               if (TREE_CODE (type) == RECORD_TYPE)
5628                 type = promote_type (type);
5629               JDEP_APPLY_PATCH (dep, type);
5630               break;
5631
5632             case JDEP_TYPE:
5633               JDEP_APPLY_PATCH (dep, TREE_TYPE (decl));
5634               SOURCE_FRONTEND_DEBUG
5635                 (("Completing a random type dependency on a '%s' node",
5636                   tree_code_name [TREE_CODE (JDEP_DECL (dep))]));
5637               break;
5638
5639             case JDEP_EXCEPTION:
5640               JDEP_APPLY_PATCH (dep, TREE_TYPE (decl));
5641               SOURCE_FRONTEND_DEBUG
5642                 (("Completing `%s' `throws' argument node",
5643                   IDENTIFIER_POINTER (EXPR_WFL_NODE (JDEP_WFL (dep)))));
5644               break;
5645
5646             case JDEP_ANONYMOUS:
5647               patch_anonymous_class (decl, JDEP_DECL (dep), JDEP_WFL (dep));
5648               break;
5649
5650             default:
5651               abort ();
5652             }
5653         }
5654     }
5655   return;
5656 }
5657
5658 /* Resolve class CLASS_TYPE. Handle the case of trying to resolve an
5659    array.  */
5660
5661 static tree
5662 resolve_class (tree enclosing, tree class_type, tree decl, tree cl)
5663 {
5664   tree tname = TYPE_NAME (class_type);
5665   tree resolved_type = TREE_TYPE (class_type);
5666   int array_dims = 0;
5667   tree resolved_type_decl;
5668
5669   if (resolved_type != NULL_TREE)
5670     {
5671       tree resolved_type_decl = TYPE_NAME (resolved_type);
5672       if (resolved_type_decl == NULL_TREE
5673           || TREE_CODE (resolved_type_decl) == IDENTIFIER_NODE)
5674         {
5675           resolved_type_decl = build_decl (TYPE_DECL,
5676                                            TYPE_NAME (class_type),
5677                                            resolved_type);
5678         }
5679       return resolved_type_decl;
5680     }
5681
5682   /* 1- Check to see if we have an array. If true, find what we really
5683      want to resolve  */
5684   if ((array_dims = build_type_name_from_array_name (tname,
5685                                                      &TYPE_NAME (class_type))))
5686     WFL_STRIP_BRACKET (cl, cl);
5687
5688   /* 2- Resolve the bare type */
5689   if (!(resolved_type_decl = do_resolve_class (enclosing, class_type,
5690                                                decl, cl)))
5691     return NULL_TREE;
5692   resolved_type = TREE_TYPE (resolved_type_decl);
5693
5694   /* 3- If we have an array, reconstruct the array down to its nesting */
5695   if (array_dims)
5696     {
5697       for (; array_dims; array_dims--)
5698         resolved_type = build_java_array_type (resolved_type, -1);
5699       resolved_type_decl = TYPE_NAME (resolved_type);
5700     }
5701   TREE_TYPE (class_type) = resolved_type;
5702   return resolved_type_decl;
5703 }
5704
5705 /* Effectively perform the resolution of class CLASS_TYPE.  DECL or CL
5706    are used to report error messages; CL must either be NULL_TREE or a
5707    WFL wrapping a class.  Do not try to replace TYPE_NAME (class_type)
5708    by a variable, since it is changed by find_in_imports{_on_demand}
5709    and (but it doesn't really matter) qualify_and_find.  */
5710
5711 tree
5712 do_resolve_class (tree enclosing, tree class_type, tree decl, tree cl)
5713 {
5714   tree new_class_decl = NULL_TREE, super = NULL_TREE;
5715   tree saved_enclosing_type = enclosing ? TREE_TYPE (enclosing) : NULL_TREE;
5716   tree decl_result;
5717   htab_t circularity_hash;
5718
5719   if (QUALIFIED_P (TYPE_NAME (class_type)))
5720     {
5721       /* If the type name is of the form `Q . Id', then Q is either a
5722          package name or a class name.  First we try to find Q as a
5723          class and then treat Id as a member type.  If we can't find Q
5724          as a class then we fall through.  */
5725       tree q, left, left_type, right;
5726       if (breakdown_qualified (&left, &right, TYPE_NAME (class_type)) == 0)
5727         {
5728           BUILD_PTR_FROM_NAME (left_type, left);
5729           q = do_resolve_class (enclosing, left_type, decl, cl);
5730           if (q)
5731             {
5732               enclosing = q;
5733               saved_enclosing_type = TREE_TYPE (q);
5734               BUILD_PTR_FROM_NAME (class_type, right);
5735             }
5736         }
5737     }
5738
5739   if (enclosing)
5740     {
5741       /* This hash table is used to register the classes we're going
5742          through when searching the current class as an inner class, in
5743          order to detect circular references. Remember to free it before
5744          returning the section 0- of this function. */
5745       circularity_hash = htab_create (20, htab_hash_pointer, htab_eq_pointer,
5746                                       NULL);
5747
5748       /* 0- Search in the current class as an inner class.
5749          Maybe some code here should be added to load the class or
5750          something, at least if the class isn't an inner class and ended
5751          being loaded from class file. FIXME. */
5752       while (enclosing)
5753         {
5754           new_class_decl = resolve_inner_class (circularity_hash, cl, &enclosing,
5755                                                 &super, class_type);
5756           if (new_class_decl)
5757             break;
5758
5759           /* If we haven't found anything because SUPER reached Object and
5760              ENCLOSING happens to be an innerclass, try the enclosing context. */
5761           if ((!super || super == object_type_node) &&
5762               enclosing && INNER_CLASS_DECL_P (enclosing))
5763             enclosing = DECL_CONTEXT (enclosing);
5764           else
5765             enclosing = NULL_TREE;
5766         }
5767
5768       htab_delete (circularity_hash);
5769
5770       if (new_class_decl)
5771         return new_class_decl;
5772     }
5773
5774   /* 1- Check for the type in single imports. This will change
5775      TYPE_NAME() if something relevant is found */
5776   find_in_imports (saved_enclosing_type, class_type);
5777
5778   /* 2- And check for the type in the current compilation unit */
5779   if ((new_class_decl = IDENTIFIER_CLASS_VALUE (TYPE_NAME (class_type))))
5780     {
5781       if (!CLASS_LOADED_P (TREE_TYPE (new_class_decl)) &&
5782           !CLASS_FROM_SOURCE_P (TREE_TYPE (new_class_decl)))
5783         load_class (TYPE_NAME (class_type), 0);
5784       return IDENTIFIER_CLASS_VALUE (TYPE_NAME (class_type));
5785     }
5786
5787   /* 3- Search according to the current package definition */
5788   if (!QUALIFIED_P (TYPE_NAME (class_type)))
5789     {
5790       if ((new_class_decl = qualify_and_find (class_type, ctxp->package,
5791                                              TYPE_NAME (class_type))))
5792         return new_class_decl;
5793     }
5794
5795   /* 4- Check the import on demands. Don't allow bar.baz to be
5796      imported from foo.* */
5797   if (!QUALIFIED_P (TYPE_NAME (class_type)))
5798     if (find_in_imports_on_demand (saved_enclosing_type, class_type))
5799       return NULL_TREE;
5800
5801   /* If found in find_in_imports_on_demand, the type has already been
5802      loaded. */
5803   if ((new_class_decl = IDENTIFIER_CLASS_VALUE (TYPE_NAME (class_type))))
5804     return new_class_decl;
5805
5806   /* 5- Try with a name qualified with the package name we've seen so far */
5807   if (!QUALIFIED_P (TYPE_NAME (class_type)))
5808     {
5809       tree package;
5810
5811       /* If there is a current package (ctxp->package), it's the first
5812          element of package_list and we can skip it. */
5813       for (package = (ctxp->package ?
5814                       TREE_CHAIN (package_list) : package_list);
5815            package; package = TREE_CHAIN (package))
5816         if ((new_class_decl = qualify_and_find (class_type,
5817                                                TREE_PURPOSE (package),
5818                                                TYPE_NAME (class_type))))
5819           return new_class_decl;
5820     }
5821
5822   /* 5- Check another compilation unit that bears the name of type */
5823   load_class (TYPE_NAME (class_type), 0);
5824
5825   if (!cl)
5826     cl = lookup_cl (decl);
5827
5828   /* If we don't have a value for CL, then we're being called recursively.
5829      We can't check package access just yet, but it will be taken care of
5830      by the caller. */
5831   if (cl)
5832     {
5833       if (check_pkg_class_access (TYPE_NAME (class_type), cl, true))
5834         return NULL_TREE;
5835     }
5836
5837   /* 6- Last call for a resolution */
5838   decl_result = IDENTIFIER_CLASS_VALUE (TYPE_NAME (class_type));
5839
5840   /* The final lookup might have registered a.b.c into a.b$c If we
5841      failed at the first lookup, progressively change the name if
5842      applicable and use the matching DECL instead. */
5843   if (!decl_result && QUALIFIED_P (TYPE_NAME (class_type)))
5844     {
5845       char *separator;
5846       tree name = TYPE_NAME (class_type);
5847       char *namebuffer = alloca (IDENTIFIER_LENGTH (name) + 1);
5848
5849       strcpy (namebuffer, IDENTIFIER_POINTER (name));
5850
5851       do {
5852
5853        /* Reach the last '.', and if applicable, replace it by a `$' and
5854           see if this exists as a type. */
5855        if ((separator = strrchr (namebuffer, '.')))
5856          {
5857            *separator = '$';
5858            name = get_identifier (namebuffer);
5859            decl_result = IDENTIFIER_CLASS_VALUE (name);
5860          }
5861       } while (!decl_result && separator);
5862     }
5863   return decl_result;
5864 }
5865
5866 static tree
5867 qualify_and_find (tree class_type, tree package, tree name)
5868 {
5869   tree new_qualified = merge_qualified_name (package, name);
5870   tree new_class_decl;
5871
5872   if (!IDENTIFIER_CLASS_VALUE (new_qualified))
5873     load_class (new_qualified, 0);
5874   if ((new_class_decl = IDENTIFIER_CLASS_VALUE (new_qualified)))
5875     {
5876       if (!CLASS_LOADED_P (TREE_TYPE (new_class_decl)) &&
5877           !CLASS_FROM_SOURCE_P (TREE_TYPE (new_class_decl)))
5878         load_class (new_qualified, 0);
5879       TYPE_NAME (class_type) = new_qualified;
5880       return IDENTIFIER_CLASS_VALUE (new_qualified);
5881     }
5882   return NULL_TREE;
5883 }
5884
5885 /* Resolve NAME and lay it out (if not done and if not the current
5886    parsed class). Return a decl node. This function is meant to be
5887    called when type resolution is necessary during the walk pass.  */
5888
5889 static tree
5890 resolve_and_layout (tree something, tree cl)
5891 {
5892   tree decl, decl_type;
5893
5894   /* Don't do that on the current class */
5895   if (something == current_class)
5896     return TYPE_NAME (current_class);
5897
5898   /* Don't do anything for void and other primitive types */
5899   if (JPRIMITIVE_TYPE_P (something) || something == void_type_node)
5900     return NULL_TREE;
5901
5902   /* Pointer types can be reall pointer types or fake pointers. When
5903      finding a real pointer, recheck for primitive types */
5904   if (TREE_CODE (something) == POINTER_TYPE)
5905     {
5906       if (TREE_TYPE (something))
5907         {
5908           something = TREE_TYPE (something);
5909           if (JPRIMITIVE_TYPE_P (something) || something == void_type_node)
5910             return NULL_TREE;
5911         }
5912       else
5913         something = TYPE_NAME (something);
5914     }
5915
5916   /* Don't do anything for arrays of primitive types */
5917   if (TREE_CODE (something) == RECORD_TYPE && TYPE_ARRAY_P (something)
5918       && JPRIMITIVE_TYPE_P (TYPE_ARRAY_ELEMENT (something)))
5919     return NULL_TREE;
5920
5921   /* Something might be a WFL */
5922   if (TREE_CODE (something) == EXPR_WITH_FILE_LOCATION)
5923     something = EXPR_WFL_NODE (something);
5924
5925   /* Otherwise, if something is not and IDENTIFIER_NODE, it can be a a
5926      TYPE_DECL or a real TYPE */
5927   else if (TREE_CODE (something) != IDENTIFIER_NODE)
5928     something = (TREE_CODE (TYPE_NAME (something)) == TYPE_DECL ?
5929             DECL_NAME (TYPE_NAME (something)) : TYPE_NAME (something));
5930
5931   if (!(decl = resolve_no_layout (something, cl)))
5932     return NULL_TREE;
5933
5934   /* Resolve and layout if necessary */
5935   decl_type = TREE_TYPE (decl);
5936   layout_class_methods (decl_type);
5937   /* Check methods */
5938   if (CLASS_FROM_SOURCE_P (decl_type))
5939     java_check_methods (decl);
5940   /* Layout the type if necessary */
5941   if (decl_type != current_class && !CLASS_LOADED_P (decl_type))
5942     safe_layout_class (decl_type);
5943
5944   return decl;
5945 }
5946
5947 /* Resolve a class, returns its decl but doesn't perform any
5948    layout. The current parsing context is saved and restored */
5949
5950 static tree
5951 resolve_no_layout (tree name, tree cl)
5952 {
5953   tree ptr, decl;
5954   BUILD_PTR_FROM_NAME (ptr, name);
5955   java_parser_context_save_global ();
5956   decl = resolve_class (TYPE_NAME (current_class), ptr, NULL_TREE, cl);
5957   java_parser_context_restore_global ();
5958
5959   return decl;
5960 }
5961
5962 /* Called when reporting errors. Skip the '[]'s in a complex array
5963    type description that failed to be resolved. purify_type_name can't
5964    use an identifier tree.  */
5965
5966 static const char *
5967 purify_type_name (const char *name)
5968 {
5969   int len = strlen (name);
5970   int bracket_found;
5971
5972   STRING_STRIP_BRACKETS (name, len, bracket_found);
5973   if (bracket_found)
5974     {
5975       char *stripped_name = xmemdup (name, len, len+1);
5976       stripped_name [len] = '\0';
5977       return stripped_name;
5978     }
5979   return name;
5980 }
5981
5982 /* The type CURRENT refers to can't be found. We print error messages.  */
5983
5984 static void
5985 complete_class_report_errors (jdep *dep)
5986 {
5987   const char *name;
5988
5989   if (!JDEP_WFL (dep))
5990     return;
5991
5992   name = IDENTIFIER_POINTER (EXPR_WFL_NODE (JDEP_WFL (dep)));
5993   switch (JDEP_KIND (dep))
5994     {
5995     case JDEP_SUPER:
5996       parse_error_context
5997         (JDEP_WFL (dep), "Superclass `%s' of class `%s' not found",
5998          purify_type_name (name),
5999          IDENTIFIER_POINTER (DECL_NAME (JDEP_DECL (dep))));
6000       break;
6001     case JDEP_FIELD:
6002       parse_error_context
6003         (JDEP_WFL (dep), "Type `%s' not found in declaration of field `%s'",
6004          purify_type_name (name),
6005          IDENTIFIER_POINTER (DECL_NAME (JDEP_DECL (dep))));
6006       break;
6007     case JDEP_METHOD:           /* Covers arguments */
6008       parse_error_context
6009         (JDEP_WFL (dep), "Type `%s' not found in the declaration of the argument `%s' of method `%s'",
6010          purify_type_name (name),
6011          IDENTIFIER_POINTER (EXPR_WFL_NODE (JDEP_DECL_WFL (dep))),
6012          IDENTIFIER_POINTER (EXPR_WFL_NODE (JDEP_MISC (dep))));
6013       break;
6014     case JDEP_METHOD_RETURN:    /* Covers return type */
6015       parse_error_context
6016         (JDEP_WFL (dep), "Type `%s' not found in the declaration of the return type of method `%s'",
6017          purify_type_name (name),
6018          IDENTIFIER_POINTER (EXPR_WFL_NODE (JDEP_DECL_WFL (dep))));
6019       break;
6020     case JDEP_INTERFACE:
6021       parse_error_context
6022         (JDEP_WFL (dep), "Superinterface `%s' of %s `%s' not found",
6023          IDENTIFIER_POINTER (EXPR_WFL_NODE (JDEP_WFL (dep))),
6024          (CLASS_OR_INTERFACE (JDEP_DECL (dep), "class", "interface")),
6025          IDENTIFIER_POINTER (DECL_NAME (JDEP_DECL (dep))));
6026       break;
6027     case JDEP_VARIABLE:
6028       parse_error_context
6029         (JDEP_WFL (dep), "Type `%s' not found in the declaration of the local variable `%s'",
6030          purify_type_name (IDENTIFIER_POINTER
6031                            (EXPR_WFL_NODE (JDEP_WFL (dep)))),
6032          IDENTIFIER_POINTER (DECL_NAME (JDEP_DECL (dep))));
6033       break;
6034     case JDEP_EXCEPTION:        /* As specified by `throws' */
6035       parse_error_context
6036           (JDEP_WFL (dep), "Class `%s' not found in `throws'",
6037          IDENTIFIER_POINTER (EXPR_WFL_NODE (JDEP_WFL (dep))));
6038       break;
6039     default:
6040       /* Fix for -Wall. Just break doing nothing. The error will be
6041          caught later */
6042       break;
6043     }
6044 }
6045
6046 /* Return a static string containing the DECL prototype string. If
6047    DECL is a constructor, use the class name instead of the form
6048    <init> */
6049
6050 static const char *
6051 get_printable_method_name (tree decl)
6052 {
6053   const char *to_return;
6054   tree name = NULL_TREE;
6055
6056   if (DECL_CONSTRUCTOR_P (decl))
6057     {
6058       name = DECL_NAME (decl);
6059       DECL_NAME (decl) = DECL_NAME (TYPE_NAME (DECL_CONTEXT (decl)));
6060     }
6061
6062   to_return = lang_printable_name (decl, 0);
6063   if (DECL_CONSTRUCTOR_P (decl))
6064     DECL_NAME (decl) = name;
6065
6066   return to_return;
6067 }
6068
6069 /* Track method being redefined inside the same class. As a side
6070    effect, set DECL_NAME to an IDENTIFIER (prior entering this
6071    function it's a FWL, so we can track errors more accurately.)  */
6072
6073 static int
6074 check_method_redefinition (tree class, tree method)
6075 {
6076   tree redef, sig;
6077
6078   /* There's no need to verify <clinit> and finit$ and instinit$ */
6079   if (DECL_CLINIT_P (method)
6080       || DECL_FINIT_P (method) || DECL_INSTINIT_P (method))
6081     return 0;
6082
6083   sig = TYPE_ARGUMENT_SIGNATURE (TREE_TYPE (method));
6084   for (redef = TYPE_METHODS (class); redef; redef = TREE_CHAIN (redef))
6085     {
6086       if (redef == method)
6087         break;
6088       if (DECL_NAME (redef) == DECL_NAME (method)
6089           && sig == TYPE_ARGUMENT_SIGNATURE (TREE_TYPE (redef))
6090           && !DECL_ARTIFICIAL (method))
6091         {
6092           parse_error_context
6093             (DECL_FUNCTION_WFL (method), "Duplicate %s declaration `%s'",
6094              (DECL_CONSTRUCTOR_P (redef) ? "constructor" : "method"),
6095              get_printable_method_name (redef));
6096           return 1;
6097         }
6098     }
6099   return 0;
6100 }
6101
6102 /* Return 1 if check went ok, 0 otherwise.  */
6103 static int
6104 check_abstract_method_definitions (int do_interface, tree class_decl,
6105                                    tree type)
6106 {
6107   tree class = TREE_TYPE (class_decl);
6108   tree method, end_type;
6109   int ok = 1;
6110
6111   end_type = (do_interface ? object_type_node : type);
6112   for (method = TYPE_METHODS (type); method; method = TREE_CHAIN (method))
6113     {
6114       tree other_super, other_method, method_sig, method_name;
6115       int found = 0;
6116       int end_type_reached = 0;
6117
6118       if (!METHOD_ABSTRACT (method) || METHOD_FINAL (method))
6119         continue;
6120
6121       /* Now verify that somewhere in between TYPE and CLASS,
6122          abstract method METHOD gets a non abstract definition
6123          that is inherited by CLASS.  */
6124
6125       method_sig = build_java_signature (TREE_TYPE (method));
6126       method_name = DECL_NAME (method);
6127       if (TREE_CODE (method_name) == EXPR_WITH_FILE_LOCATION)
6128         method_name = EXPR_WFL_NODE (method_name);
6129
6130       other_super = class;
6131       do {
6132         if (other_super == end_type)
6133           end_type_reached = 1;
6134
6135         /* Method search */
6136         for (other_method = TYPE_METHODS (other_super); other_method;
6137             other_method = TREE_CHAIN (other_method))
6138           {
6139             tree s = build_java_signature (TREE_TYPE (other_method));
6140             tree other_name = DECL_NAME (other_method);
6141
6142             if (TREE_CODE (other_name) == EXPR_WITH_FILE_LOCATION)
6143               other_name = EXPR_WFL_NODE (other_name);
6144             if (!DECL_CLINIT_P (other_method)
6145                 && !DECL_CONSTRUCTOR_P (other_method)
6146                 && method_name == other_name
6147                 && method_sig == s
6148                 && !METHOD_ABSTRACT (other_method))
6149              {
6150                found = 1;
6151                break;
6152              }
6153           }
6154         other_super = CLASSTYPE_SUPER (other_super);
6155       } while (!end_type_reached);
6156
6157       /* Report that abstract METHOD didn't find an implementation
6158          that CLASS can use. */
6159       if (!found)
6160         {
6161           char *t = xstrdup (lang_printable_name
6162                             (TREE_TYPE (TREE_TYPE (method)), 0));
6163           tree ccn = DECL_NAME (TYPE_NAME (DECL_CONTEXT (method)));
6164
6165           parse_error_context
6166             (lookup_cl (class_decl),
6167              "Class `%s' doesn't define the abstract method `%s %s' from %s `%s'. This method must be defined or %s `%s' must be declared abstract",
6168              IDENTIFIER_POINTER (DECL_NAME (class_decl)),
6169              t, lang_printable_name (method, 0),
6170              (CLASS_INTERFACE (TYPE_NAME (DECL_CONTEXT (method))) ?
6171               "interface" : "class"),
6172              IDENTIFIER_POINTER (ccn),
6173              (CLASS_INTERFACE (class_decl) ? "interface" : "class"),
6174              IDENTIFIER_POINTER (DECL_NAME (class_decl)));
6175           ok = 0;
6176           free (t);
6177         }
6178     }
6179
6180   if (ok && do_interface)
6181     {
6182       /* Check for implemented interfaces. */
6183       int i;
6184       tree vector = TYPE_BINFO_BASETYPES (type);
6185       for (i = 1; ok && vector && i < TREE_VEC_LENGTH (vector); i++)
6186         {
6187           tree super = BINFO_TYPE (TREE_VEC_ELT (vector, i));
6188           ok = check_abstract_method_definitions (1, class_decl, super);
6189         }
6190     }
6191
6192   return ok;
6193 }
6194
6195 /* Check that CLASS_DECL somehow implements all inherited abstract
6196    methods.  */
6197
6198 static void
6199 java_check_abstract_method_definitions (tree class_decl)
6200 {
6201   tree class = TREE_TYPE (class_decl);
6202   tree super, vector;
6203   int i;
6204
6205   if (CLASS_ABSTRACT (class_decl))
6206     return;
6207
6208   /* Check for inherited types */
6209   super = class;
6210   do {
6211     super = CLASSTYPE_SUPER (super);
6212     check_abstract_method_definitions (0, class_decl, super);
6213   } while (super != object_type_node);
6214
6215   /* Check for implemented interfaces. */
6216   vector = TYPE_BINFO_BASETYPES (class);
6217   for (i = 1; i < TREE_VEC_LENGTH (vector); i++)
6218     {
6219       super = BINFO_TYPE (TREE_VEC_ELT (vector, i));
6220       check_abstract_method_definitions (1, class_decl, super);
6221     }
6222 }
6223
6224 /* Check all the types method DECL uses and return 1 if all of them
6225    are now complete, 0 otherwise. This is used to check whether its
6226    safe to build a method signature or not.  */
6227
6228 static int
6229 check_method_types_complete (tree decl)
6230 {
6231   tree type = TREE_TYPE (decl);
6232   tree args;
6233
6234   if (!INCOMPLETE_TYPE_P (TREE_TYPE (type)))
6235     return 0;
6236
6237   args = TYPE_ARG_TYPES (type);
6238   if (TREE_CODE (type) == METHOD_TYPE)
6239     args = TREE_CHAIN (args);
6240   for (; args != end_params_node; args = TREE_CHAIN (args))
6241     if (INCOMPLETE_TYPE_P (TREE_VALUE (args)))
6242       return 0;
6243
6244   return 1;
6245 }
6246
6247 /* Visible interface to check methods contained in CLASS_DECL */
6248
6249 void
6250 java_check_methods (tree class_decl)
6251 {
6252   if (CLASS_METHOD_CHECKED_P (TREE_TYPE (class_decl)))
6253     return;
6254
6255   if (CLASS_INTERFACE (class_decl))
6256     java_check_abstract_methods (class_decl);
6257   else
6258     java_check_regular_methods (class_decl);
6259
6260   CLASS_METHOD_CHECKED_P (TREE_TYPE (class_decl)) = 1;
6261 }
6262
6263 /* Like not_accessible_p, but doesn't refer to the current class at
6264    all.  */
6265 static bool
6266 hack_is_accessible_p (tree member, tree from_where)
6267 {
6268   int flags = get_access_flags_from_decl (member);
6269
6270   if (from_where == DECL_CONTEXT (member)
6271       || (flags & ACC_PUBLIC))
6272     return true;
6273
6274   if ((flags & ACC_PROTECTED))
6275     {
6276       if (inherits_from_p (from_where, DECL_CONTEXT (member)))
6277         return true;
6278     }
6279
6280   if ((flags & ACC_PRIVATE))
6281     return false;
6282
6283   /* Package private, or protected.  */
6284   return in_same_package (TYPE_NAME (from_where),
6285                           TYPE_NAME (DECL_CONTEXT (member)));
6286 }
6287
6288 /* Check all the methods of CLASS_DECL. Methods are first completed
6289    then checked according to regular method existence rules.  If no
6290    constructor for CLASS_DECL were encountered, then build its
6291    declaration.  */
6292 static void
6293 java_check_regular_methods (tree class_decl)
6294 {
6295   int saw_constructor = ANONYMOUS_CLASS_P (TREE_TYPE (class_decl));
6296   tree method;
6297   tree class = TREE_TYPE (class_decl);
6298   tree found = NULL_TREE;
6299   tree mthrows;
6300
6301   /* It is not necessary to check methods defined in java.lang.Object */
6302   if (class == object_type_node)
6303     return;
6304
6305   if (!TYPE_NVIRTUALS (class))
6306     TYPE_METHODS (class) = nreverse (TYPE_METHODS (class));
6307
6308   /* Should take interfaces into account. FIXME */
6309   for (method = TYPE_METHODS (class); method; method = TREE_CHAIN (method))
6310     {
6311       tree sig;
6312       tree method_wfl = DECL_FUNCTION_WFL (method);
6313       int aflags;
6314
6315       /* Check for redefinitions */
6316       if (check_method_redefinition (class, method))
6317         continue;
6318
6319       /* We verify things thrown by the method.  They must inherit from
6320          java.lang.Throwable.  */
6321       for (mthrows = DECL_FUNCTION_THROWS (method);
6322            mthrows; mthrows = TREE_CHAIN (mthrows))
6323         {
6324           if (!inherits_from_p (TREE_VALUE (mthrows), throwable_type_node))
6325             parse_error_context
6326               (TREE_PURPOSE (mthrows), "Class `%s' in `throws' clause must be a subclass of class `java.lang.Throwable'",
6327                IDENTIFIER_POINTER
6328                  (DECL_NAME (TYPE_NAME (TREE_VALUE (mthrows)))));
6329         }
6330
6331       /* If we see one constructor a mark so we don't generate the
6332          default one.  Also skip other verifications: constructors
6333          can't be inherited hence hidden or overridden.  */
6334       if (DECL_CONSTRUCTOR_P (method))
6335         {
6336           saw_constructor = 1;
6337           continue;
6338         }
6339
6340       sig = build_java_argument_signature (TREE_TYPE (method));
6341       found = lookup_argument_method_generic (class, DECL_NAME (method), sig,
6342                                               SEARCH_SUPER | SEARCH_INTERFACE);
6343
6344       /* Inner class can't declare static methods */
6345       if (METHOD_STATIC (method) && !TOPLEVEL_CLASS_DECL_P (class_decl))
6346         {
6347           char *t = xstrdup (lang_printable_name (class, 0));
6348           parse_error_context
6349             (method_wfl, "Method `%s' can't be static in inner class `%s'. Only members of interfaces and top-level classes can be static",
6350              lang_printable_name (method, 0), t);
6351           free (t);
6352         }
6353
6354       /* Nothing overrides or it's a private method. */
6355       if (!found)
6356         continue;
6357       if (METHOD_PRIVATE (found))
6358         {
6359           found = NULL_TREE;
6360           continue;
6361         }
6362
6363       /* If `found' is declared in an interface, make sure the
6364          modifier matches. */
6365       if (CLASS_INTERFACE (TYPE_NAME (DECL_CONTEXT (found)))
6366           && clinit_identifier_node != DECL_NAME (found)
6367           && !METHOD_PUBLIC (method))
6368         {
6369           tree found_decl = TYPE_NAME (DECL_CONTEXT (found));
6370           parse_error_context (method_wfl, "Class `%s' must override `%s' with a public method in order to implement interface `%s'",
6371                                IDENTIFIER_POINTER (DECL_NAME (class_decl)),
6372                                lang_printable_name (method, 0),
6373                                IDENTIFIER_POINTER (DECL_NAME (found_decl)));
6374         }
6375
6376       /* Can't override a method with the same name and different return
6377          types. */
6378       if (TREE_TYPE (TREE_TYPE (found)) != TREE_TYPE (TREE_TYPE (method)))
6379         {
6380           char *t = xstrdup
6381             (lang_printable_name (TREE_TYPE (TREE_TYPE (found)), 0));
6382           parse_error_context
6383             (method_wfl,
6384              "Method `%s' was defined with return type `%s' in class `%s'",
6385              lang_printable_name (found, 0), t,
6386              IDENTIFIER_POINTER
6387                (DECL_NAME (TYPE_NAME (DECL_CONTEXT (found)))));
6388           free (t);
6389         }
6390
6391       aflags = get_access_flags_from_decl (found);
6392
6393       /* Can't override final. Can't override static. */
6394       if (METHOD_FINAL (found) || METHOD_STATIC (found))
6395         {
6396           /* Static *can* override static */
6397           if (METHOD_STATIC (found) && METHOD_STATIC (method))
6398             continue;
6399           parse_error_context
6400             (method_wfl,
6401              "%s methods can't be overridden. Method `%s' is %s in class `%s'",
6402              (METHOD_FINAL (found) ? "Final" : "Static"),
6403              lang_printable_name (found, 0),
6404              (METHOD_FINAL (found) ? "final" : "static"),
6405              IDENTIFIER_POINTER
6406                (DECL_NAME (TYPE_NAME (DECL_CONTEXT (found)))));
6407           continue;
6408         }
6409
6410       /* Static method can't override instance method. */
6411       if (METHOD_STATIC (method))
6412         {
6413           parse_error_context
6414             (method_wfl,
6415              "Instance methods can't be overridden by a static method. Method `%s' is an instance method in class `%s'",
6416              lang_printable_name (found, 0),
6417              IDENTIFIER_POINTER
6418                (DECL_NAME (TYPE_NAME (DECL_CONTEXT (found)))));
6419           continue;
6420         }
6421
6422       /* - Overriding/hiding public must be public
6423          - Overriding/hiding protected must be protected or public
6424          - If the overridden or hidden method has default (package)
6425            access, then the overriding or hiding method must not be
6426            private; otherwise, a compile-time error occurs.  If
6427            `found' belongs to an interface, things have been already
6428            taken care of.  */
6429       if (!CLASS_INTERFACE (TYPE_NAME (DECL_CONTEXT (found)))
6430           && ((METHOD_PUBLIC (found) && !METHOD_PUBLIC (method))
6431               || (METHOD_PROTECTED (found)
6432                   && !(METHOD_PUBLIC (method) || METHOD_PROTECTED (method)))
6433               || (!(aflags & (ACC_PUBLIC | ACC_PRIVATE | ACC_STATIC))
6434                   && METHOD_PRIVATE (method))))
6435         {
6436           parse_error_context
6437             (method_wfl,
6438              "Methods can't be overridden to be more private. Method `%s' is not %s in class `%s'", lang_printable_name (method, 0),
6439              (METHOD_PUBLIC (method) ? "public" :
6440               (METHOD_PRIVATE (method) ? "private" : "protected")),
6441              IDENTIFIER_POINTER (DECL_NAME
6442                                  (TYPE_NAME (DECL_CONTEXT (found)))));
6443           continue;
6444         }
6445
6446       /* Check this method against all the other implementations it
6447          overrides.  Here we only check the class hierarchy; the rest
6448          of the checking is done later.  If this method is just a
6449          Miranda method, we can skip the check.  */
6450       if (! METHOD_INVISIBLE (method))
6451         check_concrete_throws_clauses (class, method, DECL_NAME (method), sig);
6452     }
6453
6454   /* The above throws clause check only looked at superclasses.  Now
6455      we must also make sure that all methods declared in interfaces
6456      have compatible throws clauses.  FIXME: there are more efficient
6457      ways to organize this checking; we should implement one.  */
6458   check_interface_throws_clauses (class, class);
6459
6460   if (!TYPE_NVIRTUALS (class))
6461     TYPE_METHODS (class) = nreverse (TYPE_METHODS (class));
6462
6463   /* Search for inherited abstract method not yet implemented in this
6464      class.  */
6465   java_check_abstract_method_definitions (class_decl);
6466
6467   if (!saw_constructor)
6468     abort ();
6469 }
6470
6471 /* Check to make sure that all the methods in all the interfaces
6472    implemented by CLASS_DECL are compatible with the concrete
6473    implementations available in CHECK_CLASS_DECL.  */
6474 static void
6475 check_interface_throws_clauses (tree check_class_decl, tree class_decl)
6476 {
6477   for (; class_decl != NULL_TREE; class_decl = CLASSTYPE_SUPER (class_decl))
6478     {
6479       tree bases = TYPE_BINFO_BASETYPES (class_decl);
6480       int iface_len = TREE_VEC_LENGTH (bases) - 1;
6481       int i;
6482
6483       for (i = iface_len; i > 0; --i)
6484         {
6485           tree interface = BINFO_TYPE (TREE_VEC_ELT (bases, i));
6486           tree iface_method;
6487
6488           for (iface_method = TYPE_METHODS (interface);
6489                iface_method != NULL_TREE;
6490                iface_method = TREE_CHAIN (iface_method))
6491             {
6492               tree sig, method;
6493
6494               /* First look for a concrete method implemented or
6495                  inherited by this class.  No need to search
6496                  interfaces here, since we're already looking through
6497                  all of them.  */
6498               sig = build_java_argument_signature (TREE_TYPE (iface_method));
6499               method
6500                 = lookup_argument_method_generic (check_class_decl,
6501                                                   DECL_NAME (iface_method),
6502                                                   sig, SEARCH_VISIBLE);
6503               /* If we don't find an implementation, that is ok.  Any
6504                  potential errors from that are diagnosed elsewhere.
6505                  Also, multiple inheritance with conflicting throws
6506                  clauses is fine in the absence of a concrete
6507                  implementation.  */
6508               if (method != NULL_TREE && !METHOD_ABSTRACT (method))
6509                 {
6510                   tree method_wfl = DECL_FUNCTION_WFL (method);
6511                   check_throws_clauses (method, method_wfl, iface_method);
6512                 }
6513             }
6514
6515           /* Now check superinterfaces.  */
6516           check_interface_throws_clauses (check_class_decl, interface);
6517         }
6518     }
6519 }
6520
6521 /* Check throws clauses of a method against the clauses of all the
6522    methods it overrides.  We do this by searching up the class
6523    hierarchy, examining all matching accessible methods.  */
6524 static void
6525 check_concrete_throws_clauses (tree class, tree self_method,
6526                                tree name, tree signature)
6527 {
6528   tree method = lookup_argument_method_generic (class, name, signature,
6529                                                 SEARCH_SUPER | SEARCH_VISIBLE);
6530   while (method != NULL_TREE)
6531     {
6532       if (! METHOD_INVISIBLE (method) && hack_is_accessible_p (method, class))
6533         check_throws_clauses (self_method, DECL_FUNCTION_WFL (self_method),
6534                               method);
6535
6536       method = lookup_argument_method_generic (DECL_CONTEXT (method),
6537                                                name, signature,
6538                                                SEARCH_SUPER | SEARCH_VISIBLE);
6539     }
6540 }
6541
6542 /* Generate an error if the `throws' clause of METHOD (if any) is
6543    incompatible with the `throws' clause of FOUND (if any).  */
6544 static void
6545 check_throws_clauses (tree method, tree method_wfl, tree found)
6546 {
6547   tree mthrows;
6548
6549   /* Can't check these things with class loaded from bytecode. FIXME */
6550   if (!CLASS_FROM_SOURCE_P (DECL_CONTEXT (found)))
6551     return;
6552
6553   for (mthrows = DECL_FUNCTION_THROWS (method);
6554        mthrows; mthrows = TREE_CHAIN (mthrows))
6555     {
6556       tree fthrows;
6557
6558       /* We don't verify unchecked expressions */
6559       if (IS_UNCHECKED_EXCEPTION_P (TREE_VALUE (mthrows)))
6560         continue;
6561       /* Checked expression must be compatible */
6562       for (fthrows = DECL_FUNCTION_THROWS (found);
6563            fthrows; fthrows = TREE_CHAIN (fthrows))
6564         {
6565           if (inherits_from_p (TREE_VALUE (mthrows), TREE_VALUE (fthrows)))
6566             break;
6567         }
6568       if (!fthrows)
6569         {
6570           parse_error_context
6571             (method_wfl, "Invalid checked exception class `%s' in `throws' clause.  The exception must be a subclass of an exception thrown by `%s' from class `%s'",
6572              IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (TREE_VALUE (mthrows)))),
6573              lang_printable_name (found, 0),
6574              IDENTIFIER_POINTER
6575              (DECL_NAME (TYPE_NAME (DECL_CONTEXT (found)))));
6576         }
6577     }
6578 }
6579
6580 /* Check abstract method of interface INTERFACE */
6581 static void
6582 java_check_abstract_methods (tree interface_decl)
6583 {
6584   int i, n;
6585   tree method, basetype_vec, found;
6586   tree interface = TREE_TYPE (interface_decl);
6587
6588   for (method = TYPE_METHODS (interface); method; method = TREE_CHAIN (method))
6589     {
6590       /* 2- Check for double definition inside the defining interface */
6591       if (check_method_redefinition (interface, method))
6592         continue;
6593
6594       /* 3- Overriding is OK as far as we preserve the return type.  */
6595       found = lookup_java_interface_method2 (interface, method);
6596       if (found)
6597         {
6598           char *t;
6599           t = xstrdup (lang_printable_name (TREE_TYPE (TREE_TYPE (found)), 0));
6600           parse_error_context
6601             (DECL_FUNCTION_WFL (found),
6602              "Method `%s' was defined with return type `%s' in class `%s'",
6603              lang_printable_name (found, 0), t,
6604              IDENTIFIER_POINTER
6605                (DECL_NAME (TYPE_NAME (DECL_CONTEXT (found)))));
6606           free (t);
6607           continue;
6608         }
6609     }
6610
6611   /* 4- Inherited methods can't differ by their returned types */
6612   if (!(basetype_vec = TYPE_BINFO_BASETYPES (interface)))
6613     return;
6614   n = TREE_VEC_LENGTH (basetype_vec);
6615   for (i = 0; i < n; i++)
6616     {
6617       tree sub_interface_method, sub_interface;
6618       tree vec_elt = TREE_VEC_ELT (basetype_vec, i);
6619       if (!vec_elt)
6620         continue;
6621       sub_interface = BINFO_TYPE (vec_elt);
6622       for (sub_interface_method = TYPE_METHODS (sub_interface);
6623            sub_interface_method;
6624            sub_interface_method = TREE_CHAIN (sub_interface_method))
6625         {
6626           found = lookup_java_interface_method2 (interface,
6627                                                  sub_interface_method);
6628           if (found && (found != sub_interface_method))
6629             {
6630               parse_error_context
6631                 (lookup_cl (sub_interface_method),
6632                  "Interface `%s' inherits method `%s' from interface `%s'. This method is redefined with a different return type in interface `%s'",
6633                  IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (interface))),
6634                  lang_printable_name (found, 0),
6635                  IDENTIFIER_POINTER
6636                    (DECL_NAME (TYPE_NAME
6637                                (DECL_CONTEXT (sub_interface_method)))),
6638                  IDENTIFIER_POINTER
6639                    (DECL_NAME (TYPE_NAME (DECL_CONTEXT (found)))));
6640             }
6641         }
6642     }
6643 }
6644
6645 /* Lookup methods in interfaces using their name and partial
6646    signature. Return a matching method only if their types differ.  */
6647
6648 static tree
6649 lookup_java_interface_method2 (tree class, tree method_decl)
6650 {
6651   int i, n;
6652   tree basetype_vec = TYPE_BINFO_BASETYPES (class), to_return;
6653
6654   if (!basetype_vec)
6655     return NULL_TREE;
6656
6657   n = TREE_VEC_LENGTH (basetype_vec);
6658   for (i = 0; i < n; i++)
6659     {
6660       tree vec_elt = TREE_VEC_ELT (basetype_vec, i), to_return;
6661       if ((BINFO_TYPE (vec_elt) != object_type_node)
6662           && (to_return =
6663               lookup_java_method2 (BINFO_TYPE (vec_elt), method_decl, 1)))
6664         return to_return;
6665     }
6666   for (i = 0; i < n; i++)
6667     {
6668       to_return = lookup_java_interface_method2
6669         (BINFO_TYPE (TREE_VEC_ELT (basetype_vec, i)), method_decl);
6670       if (to_return)
6671         return to_return;
6672     }
6673
6674   return NULL_TREE;
6675 }
6676
6677 /* Lookup method using their name and partial signature. Return a
6678    matching method only if their types differ.  */
6679
6680 static tree
6681 lookup_java_method2 (tree clas, tree method_decl, int do_interface)
6682 {
6683   tree method, method_signature, method_name, method_type, name;
6684
6685   method_signature = build_java_argument_signature (TREE_TYPE (method_decl));
6686   name = DECL_NAME (method_decl);
6687   method_name = (TREE_CODE (name) == EXPR_WITH_FILE_LOCATION ?
6688                  EXPR_WFL_NODE (name) : name);
6689   method_type = TREE_TYPE (TREE_TYPE (method_decl));
6690
6691   while (clas != NULL_TREE)
6692     {
6693       for (method = TYPE_METHODS (clas);
6694            method != NULL_TREE;  method = TREE_CHAIN (method))
6695         {
6696           tree method_sig = build_java_argument_signature (TREE_TYPE (method));
6697           tree name = DECL_NAME (method);
6698           if ((TREE_CODE (name) == EXPR_WITH_FILE_LOCATION ?
6699                EXPR_WFL_NODE (name) : name) == method_name
6700               && method_sig == method_signature
6701               && TREE_TYPE (TREE_TYPE (method)) != method_type)
6702             return method;
6703         }
6704       clas = (do_interface ? NULL_TREE : CLASSTYPE_SUPER (clas));
6705     }
6706   return NULL_TREE;
6707 }
6708
6709 /* Return the line that matches DECL line number, and try its best to
6710    position the column number. Used during error reports.  */
6711
6712 static GTY(()) tree cl_v;
6713 static tree
6714 lookup_cl (tree decl)
6715 {
6716   char *line, *found;
6717
6718   if (!decl)
6719     return NULL_TREE;
6720
6721   if (cl_v == NULL_TREE)
6722     {
6723       cl_v = build_expr_wfl (NULL_TREE, NULL, 0, 0);
6724     }
6725
6726   EXPR_WFL_FILENAME_NODE (cl_v) = get_identifier (DECL_SOURCE_FILE (decl));
6727   EXPR_WFL_SET_LINECOL (cl_v, DECL_SOURCE_LINE (decl), -1);
6728
6729   line = java_get_line_col (EXPR_WFL_FILENAME (cl_v),
6730                             EXPR_WFL_LINENO (cl_v), EXPR_WFL_COLNO (cl_v));
6731
6732   found = strstr ((const char *)line,
6733                   (const char *)IDENTIFIER_POINTER (DECL_NAME (decl)));
6734   if (found)
6735     EXPR_WFL_SET_LINECOL (cl_v, EXPR_WFL_LINENO (cl_v), found - line);
6736
6737   return cl_v;
6738 }
6739
6740 /* Look for a simple name in the single-type import list */
6741
6742 static tree
6743 find_name_in_single_imports (tree name)
6744 {
6745   tree node;
6746
6747   for (node = ctxp->import_list; node; node = TREE_CHAIN (node))
6748     if (TREE_VALUE (node) == name)
6749       return (EXPR_WFL_NODE (TREE_PURPOSE (node)));
6750
6751   return NULL_TREE;
6752 }
6753
6754 /* Process all single-type import. */
6755
6756 static int
6757 process_imports (void)
6758 {
6759   tree import;
6760   int error_found;
6761
6762   for (import = ctxp->import_list; import; import = TREE_CHAIN (import))
6763     {
6764       tree to_be_found = EXPR_WFL_NODE (TREE_PURPOSE (import));
6765       char *original_name;
6766
6767       original_name = xmemdup (IDENTIFIER_POINTER (to_be_found),
6768                                IDENTIFIER_LENGTH (to_be_found),
6769                                IDENTIFIER_LENGTH (to_be_found) + 1);
6770
6771       /* Don't load twice something already defined. */
6772       if (IDENTIFIER_CLASS_VALUE (to_be_found))
6773         continue;
6774
6775       while (1)
6776         {
6777           tree left;
6778
6779           QUALIFIED_P (to_be_found) = 1;
6780           load_class (to_be_found, 0);
6781           error_found =
6782             check_pkg_class_access (to_be_found, TREE_PURPOSE (import), true);
6783
6784           /* We found it, we can bail out */
6785           if (IDENTIFIER_CLASS_VALUE (to_be_found))
6786             {
6787               check_deprecation (TREE_PURPOSE (import),
6788                                  IDENTIFIER_CLASS_VALUE (to_be_found));
6789               break;
6790             }
6791
6792           /* We haven't found it. Maybe we're trying to access an
6793              inner class.  The only way for us to know is to try again
6794              after having dropped a qualifier. If we can't break it further,
6795              we have an error. */
6796           if (breakdown_qualified (&left, NULL, to_be_found))
6797             break;
6798
6799           to_be_found = left;
6800         }
6801       if (!IDENTIFIER_CLASS_VALUE (to_be_found))
6802         {
6803           parse_error_context (TREE_PURPOSE (import),
6804                                "Class or interface `%s' not found in import",
6805                                original_name);
6806           error_found = 1;
6807         }
6808
6809       free (original_name);
6810       if (error_found)
6811         return 1;
6812     }
6813   return 0;
6814 }
6815
6816 /* Possibly find and mark a class imported by a single-type import
6817    statement.  */
6818
6819 static void
6820 find_in_imports (tree enclosing_type, tree class_type)
6821 {
6822   tree import = (enclosing_type ? TYPE_IMPORT_LIST (enclosing_type) :
6823                  ctxp->import_list);
6824   while (import)
6825     {
6826       if (TREE_VALUE (import) == TYPE_NAME (class_type))
6827         {
6828           TYPE_NAME (class_type) = EXPR_WFL_NODE (TREE_PURPOSE (import));
6829           QUALIFIED_P (TYPE_NAME (class_type)) = 1;
6830           return;
6831         }
6832       import = TREE_CHAIN (import);
6833     }
6834 }
6835
6836 static int
6837 note_possible_classname (const char *name, int len)
6838 {
6839   tree node;
6840   if (len > 5 && strncmp (&name [len-5], ".java", 5) == 0)
6841     len = len - 5;
6842   else if (len > 6 && strncmp (&name [len-6], ".class", 6) == 0)
6843     len = len - 6;
6844   else
6845     return 0;
6846   node = ident_subst (name, len, "", '/', '.', "");
6847   IS_A_CLASSFILE_NAME (node) = 1; /* Or soon to be */
6848   QUALIFIED_P (node) = strchr (name, '/') ? 1 : 0;
6849   return 1;
6850 }
6851
6852 /* Read a import directory, gathering potential match for further type
6853    references. Indifferently reads a filesystem or a ZIP archive
6854    directory.  */
6855
6856 static void
6857 read_import_dir (tree wfl)
6858 {
6859   tree package_id = EXPR_WFL_NODE (wfl);
6860   const char *package_name = IDENTIFIER_POINTER (package_id);
6861   int package_length = IDENTIFIER_LENGTH (package_id);
6862   DIR *dirp = NULL;
6863   JCF *saved_jcf = current_jcf;
6864
6865   int found = 0;
6866   int k;
6867   void *entry;
6868   struct buffer filename[1];
6869
6870   if (IS_AN_IMPORT_ON_DEMAND_P (package_id))
6871     return;
6872   IS_AN_IMPORT_ON_DEMAND_P (package_id) = 1;
6873
6874   BUFFER_INIT (filename);
6875   buffer_grow (filename, package_length + 100);
6876
6877   for (entry = jcf_path_start (); entry != NULL; entry = jcf_path_next (entry))
6878     {
6879       const char *entry_name = jcf_path_name (entry);
6880       int entry_length = strlen (entry_name);
6881       if (jcf_path_is_zipfile (entry))
6882         {
6883           ZipFile *zipf;
6884           buffer_grow (filename, entry_length);
6885           memcpy (filename->data, entry_name, entry_length - 1);
6886           filename->data[entry_length-1] = '\0';
6887           zipf = opendir_in_zip (filename->data, jcf_path_is_system (entry));
6888           if (zipf == NULL)
6889             error ("malformed .zip archive in CLASSPATH: %s", entry_name);
6890           else
6891             {
6892               ZipDirectory *zipd = (ZipDirectory *) zipf->central_directory;
6893               BUFFER_RESET (filename);
6894               for (k = 0; k < package_length; k++)
6895                 {
6896                   char ch = package_name[k];
6897                   *filename->ptr++ = ch == '.' ? '/' : ch;
6898                 }
6899               *filename->ptr++ = '/';
6900
6901               for (k = 0; k < zipf->count;  k++, zipd = ZIPDIR_NEXT (zipd))
6902                 {
6903                   const char *current_entry = ZIPDIR_FILENAME (zipd);
6904                   int current_entry_len = zipd->filename_length;
6905
6906                   if (current_entry_len >= BUFFER_LENGTH (filename)
6907                       && strncmp (filename->data, current_entry,
6908                                   BUFFER_LENGTH (filename)) != 0)
6909                     continue;
6910                   found |= note_possible_classname (current_entry,
6911                                                     current_entry_len);
6912                 }
6913             }
6914         }
6915       else
6916         {
6917           BUFFER_RESET (filename);
6918           buffer_grow (filename, entry_length + package_length + 4);
6919           strcpy (filename->data, entry_name);
6920           filename->ptr = filename->data + entry_length;
6921           for (k = 0; k < package_length; k++)
6922             {
6923               char ch = package_name[k];
6924               *filename->ptr++ = ch == '.' ? '/' : ch;
6925             }
6926           *filename->ptr = '\0';
6927
6928           dirp = opendir (filename->data);
6929           if (dirp == NULL)
6930             continue;
6931           *filename->ptr++ = '/';
6932           for (;;)
6933             {
6934               int len;
6935               const char *d_name;
6936               struct dirent *direntp = readdir (dirp);
6937               if (!direntp)
6938                 break;
6939               d_name = direntp->d_name;
6940               len = strlen (direntp->d_name);
6941               buffer_grow (filename, len+1);
6942               strcpy (filename->ptr, d_name);
6943               found |= note_possible_classname (filename->data + entry_length,
6944                                                 package_length+len+1);
6945             }
6946           if (dirp)
6947             closedir (dirp);
6948         }
6949     }
6950
6951   free (filename->data);
6952
6953   /* Here we should have a unified way of retrieving an entry, to be
6954      indexed. */
6955   if (!found)
6956     {
6957       static int first = 1;
6958       if (first)
6959         {
6960           error ("Can't find default package `%s'. Check the CLASSPATH environment variable and the access to the archives", package_name);
6961           java_error_count++;
6962           first = 0;
6963         }
6964       else
6965         parse_error_context (wfl, "Package `%s' not found in import",
6966                              package_name);
6967       current_jcf = saved_jcf;
6968       return;
6969     }
6970   current_jcf = saved_jcf;
6971 }
6972
6973 /* Possibly find a type in the import on demands specified
6974    types. Returns 1 if an error occurred, 0 otherwise. Run through the
6975    entire list, to detected potential double definitions.  */
6976
6977 static int
6978 find_in_imports_on_demand (tree enclosing_type, tree class_type)
6979 {
6980   tree class_type_name = TYPE_NAME (class_type);
6981   tree import = (enclosing_type ? TYPE_IMPORT_DEMAND_LIST (enclosing_type) :
6982                   ctxp->import_demand_list);
6983   tree cl = NULL_TREE;
6984   int seen_once = -1;   /* -1 when not set, 1 if seen once, >1 otherwise. */
6985   int to_return = -1;   /* -1 when not set, 0 or 1 otherwise */
6986   tree node;
6987
6988   for (; import; import = TREE_CHAIN (import))
6989     {
6990       int saved_lineno = input_line;
6991       int access_check;
6992       const char *id_name;
6993       tree decl, type_name_copy;
6994
6995       obstack_grow (&temporary_obstack,
6996                     IDENTIFIER_POINTER (EXPR_WFL_NODE (TREE_PURPOSE (import))),
6997                     IDENTIFIER_LENGTH (EXPR_WFL_NODE (TREE_PURPOSE (import))));
6998       obstack_1grow (&temporary_obstack, '.');
6999       obstack_grow0 (&temporary_obstack,
7000                      IDENTIFIER_POINTER (class_type_name),
7001                      IDENTIFIER_LENGTH (class_type_name));
7002       id_name = obstack_finish (&temporary_obstack);
7003
7004       if (! (node = maybe_get_identifier (id_name)))
7005         continue;
7006
7007       /* Setup lineno so that it refers to the line of the import (in
7008          case we parse a class file and encounter errors */
7009       input_line = EXPR_WFL_LINENO (TREE_PURPOSE (import));
7010
7011       type_name_copy = TYPE_NAME (class_type);
7012       TYPE_NAME (class_type) = node;
7013       QUALIFIED_P (node) = 1;
7014       decl = IDENTIFIER_CLASS_VALUE (node);
7015       access_check = -1;
7016       /* If there is no DECL set for the class or if the class isn't
7017          loaded and not seen in source yet, then load */
7018       if (!decl || (!CLASS_LOADED_P (TREE_TYPE (decl))
7019                     && !CLASS_FROM_SOURCE_P (TREE_TYPE (decl))))
7020         {
7021           load_class (node, 0);
7022           decl = IDENTIFIER_CLASS_VALUE (node);
7023         }
7024       if (decl && ! INNER_CLASS_P (TREE_TYPE (decl)))
7025         access_check = check_pkg_class_access (node, TREE_PURPOSE (import),
7026                                                false);
7027       else
7028         /* 6.6.1: Inner classes are subject to member access rules. */
7029         access_check = 0;
7030
7031       input_line = saved_lineno;
7032
7033       /* If the loaded class is not accessible or couldn't be loaded,
7034          we restore the original TYPE_NAME and process the next
7035          import. */
7036       if (access_check || !decl)
7037         {
7038           TYPE_NAME (class_type) = type_name_copy;
7039           continue;
7040         }
7041
7042       /* If the loaded class is accessible, we keep a tab on it to
7043          detect and report multiple inclusions. */
7044       if (IS_A_CLASSFILE_NAME (node))
7045         {
7046           if (seen_once < 0)
7047             {
7048               cl = TREE_PURPOSE (import);
7049               seen_once = 1;
7050             }
7051           else if (seen_once >= 0)
7052             {
7053               tree location = (cl ? cl : TREE_PURPOSE (import));
7054               tree package = (cl ? EXPR_WFL_NODE (cl) :
7055                               EXPR_WFL_NODE (TREE_PURPOSE (import)));
7056               seen_once++;
7057               parse_error_context
7058                 (location,
7059                  "Type `%s' also potentially defined in package `%s'",
7060                  IDENTIFIER_POINTER (TYPE_NAME (class_type)),
7061                  IDENTIFIER_POINTER (package));
7062             }
7063         }
7064       to_return = access_check;
7065     }
7066
7067   if (seen_once == 1)
7068     return to_return;
7069   else
7070     return (seen_once < 0 ? 0 : seen_once); /* It's ok not to have found */
7071 }
7072
7073 /* Add package NAME to the list of packages encountered so far. To
7074    speed up class lookup in do_resolve_class, we make sure a
7075    particular package is added only once.  */
7076
7077 static void
7078 register_package (tree name)
7079 {
7080   static htab_t pht;
7081   void **e;
7082
7083   if (pht == NULL)
7084     pht = htab_create (50, htab_hash_pointer, htab_eq_pointer, NULL);
7085
7086   e = htab_find_slot (pht, name, INSERT);
7087   if (*e == NULL)
7088     {
7089       package_list = chainon (package_list, build_tree_list (name, NULL));
7090       *e = name;
7091     }
7092 }
7093
7094 static tree
7095 resolve_package (tree pkg, tree *next, tree *type_name)
7096 {
7097   tree current;
7098   tree decl = NULL_TREE;
7099   *type_name = NULL_TREE;
7100
7101   /* The trick is to determine when the package name stops and were
7102      the name of something contained in the package starts. Then we
7103      return a fully qualified name of what we want to get. */
7104
7105   *next = EXPR_WFL_QUALIFICATION (pkg);
7106
7107   /* Try to progressively construct a type name */
7108   if (TREE_CODE (pkg) == EXPR_WITH_FILE_LOCATION)
7109     for (current = EXPR_WFL_QUALIFICATION (pkg);
7110          current; current = TREE_CHAIN (current))
7111       {
7112         /* If we don't have what we're expecting, exit now. TYPE_NAME
7113            will be null and the error caught later. */
7114         if (TREE_CODE (QUAL_WFL (current)) != EXPR_WITH_FILE_LOCATION)
7115           break;
7116         *type_name =
7117           merge_qualified_name (*type_name, EXPR_WFL_NODE (QUAL_WFL (current)));
7118         if ((decl = resolve_no_layout (*type_name, NULL_TREE)))
7119           {
7120             /* resolve_package should be used in a loop, hence we
7121                point at this one to naturally process the next one at
7122                the next iteration. */
7123             *next = current;
7124             break;
7125           }
7126       }
7127   return decl;
7128 }
7129
7130
7131 /* Check accessibility of inner classes according to member access rules.
7132    DECL is the inner class, ENCLOSING_DECL is the class from which the
7133    access is being attempted. */
7134
7135 static void
7136 check_inner_class_access (tree decl, tree enclosing_decl, tree cl)
7137 {
7138   const char *access;
7139   tree enclosing_decl_type;
7140
7141   /* We don't issue an error message when CL is null. CL can be null
7142      as a result of processing a JDEP crafted by source_start_java_method
7143      for the purpose of patching its parm decl. But the error would
7144      have been already trapped when fixing the method's signature.
7145      DECL can also be NULL in case of earlier errors. */
7146   if (!decl || !cl)
7147     return;
7148
7149   enclosing_decl_type = TREE_TYPE (enclosing_decl);
7150
7151   if (CLASS_PRIVATE (decl))
7152     {
7153       /* Access is permitted only within the body of the top-level
7154          class in which DECL is declared. */
7155       tree top_level = decl;
7156       while (DECL_CONTEXT (top_level))
7157         top_level = DECL_CONTEXT (top_level);
7158       while (DECL_CONTEXT (enclosing_decl))
7159         enclosing_decl = DECL_CONTEXT (enclosing_decl);
7160       if (top_level == enclosing_decl)
7161         return;
7162       access = "private";
7163     }
7164   else if (CLASS_PROTECTED (decl))
7165     {
7166       tree decl_context;
7167       /* Access is permitted from within the same package... */
7168       if (in_same_package (decl, enclosing_decl))
7169         return;
7170
7171       /* ... or from within the body of a subtype of the context in which
7172          DECL is declared. */
7173       decl_context = DECL_CONTEXT (decl);
7174       while (enclosing_decl)
7175         {
7176           if (CLASS_INTERFACE (decl))
7177             {
7178               if (interface_of_p (TREE_TYPE (decl_context),
7179                                   enclosing_decl_type))
7180                 return;
7181             }
7182           else
7183             {
7184               /* Eww. The order of the arguments is different!! */
7185               if (inherits_from_p (enclosing_decl_type,
7186                                    TREE_TYPE (decl_context)))
7187                 return;
7188             }
7189           enclosing_decl = DECL_CONTEXT (enclosing_decl);
7190         }
7191       access = "protected";
7192     }
7193   else if (! CLASS_PUBLIC (decl))
7194     {
7195       /* Access is permitted only from within the same package as DECL. */
7196       if (in_same_package (decl, enclosing_decl))
7197         return;
7198       access = "non-public";
7199     }
7200   else
7201     /* Class is public. */
7202     return;
7203
7204   parse_error_context (cl, "Nested %s %s is %s; cannot be accessed from here",
7205                        (CLASS_INTERFACE (decl) ? "interface" : "class"),
7206                        lang_printable_name (decl, 0), access);
7207 }
7208
7209 /* Accessibility check for top-level classes. If CLASS_NAME is in a
7210    foreign package, it must be PUBLIC. Return 0 if no access
7211    violations were found, 1 otherwise. If VERBOSE is true and an error
7212    was found, it is reported and accounted for.  */
7213
7214 static int
7215 check_pkg_class_access (tree class_name, tree cl, bool verbose)
7216 {
7217   tree type;
7218
7219   if (!IDENTIFIER_CLASS_VALUE (class_name))
7220     return 0;
7221
7222   if (!(type = TREE_TYPE (IDENTIFIER_CLASS_VALUE (class_name))))
7223     return 0;
7224
7225   if (!CLASS_PUBLIC (TYPE_NAME (type)))
7226     {
7227       /* Access to a private class within the same package is
7228          allowed. */
7229       tree l, r;
7230       breakdown_qualified (&l, &r, class_name);
7231       if (!QUALIFIED_P (class_name) && !ctxp->package)
7232         /* Both in the empty package. */
7233         return 0;
7234       if (l == ctxp->package)
7235         /* Both in the same package. */
7236         return 0;
7237
7238       if (verbose)
7239         parse_error_context
7240           (cl, "Can't access %s `%s'. Only public classes and interfaces in other packages can be accessed",
7241            (CLASS_INTERFACE (TYPE_NAME (type)) ? "interface" : "class"),
7242            IDENTIFIER_POINTER (class_name));
7243       return 1;
7244     }
7245   return 0;
7246 }
7247
7248 /* Local variable declaration. */
7249
7250 static void
7251 declare_local_variables (int modifier, tree type, tree vlist)
7252 {
7253   tree decl, current, saved_type;
7254   tree type_wfl = NULL_TREE;
7255   int must_chain = 0;
7256   int final_p = 0;
7257
7258   /* Push a new block if statements were seen between the last time we
7259      pushed a block and now. Keep a count of blocks to close */
7260   if (BLOCK_EXPR_BODY (GET_CURRENT_BLOCK (current_function_decl)))
7261     {
7262       tree b = enter_block ();
7263       BLOCK_IS_IMPLICIT (b) = 1;
7264     }
7265
7266   if (modifier)
7267     {
7268       size_t i;
7269       for (i = 0; i < ARRAY_SIZE (ctxp->modifier_ctx); i++)
7270         if (1 << i & modifier)
7271           break;
7272       if (modifier == ACC_FINAL)
7273         final_p = 1;
7274       else
7275         {
7276           parse_error_context
7277             (ctxp->modifier_ctx [i],
7278              "Only `final' is allowed as a local variables modifier");
7279           return;
7280         }
7281     }
7282
7283   /* Obtain an incomplete type if TYPE is not complete. TYPE_WFL will
7284      hold the TYPE value if a new incomplete has to be created (as
7285      opposed to being found already existing and reused). */
7286   SET_TYPE_FOR_RESOLUTION (type, type_wfl, must_chain);
7287
7288   /* If TYPE is fully resolved and we don't have a reference, make one */
7289   PROMOTE_RECORD_IF_COMPLETE (type, must_chain);
7290
7291   /* Go through all the declared variables */
7292   for (current = vlist, saved_type = type; current;
7293        current = TREE_CHAIN (current), type = saved_type)
7294     {
7295       tree other, real_type;
7296       tree wfl  = TREE_PURPOSE (current);
7297       tree name = EXPR_WFL_NODE (wfl);
7298       tree init = TREE_VALUE (current);
7299
7300       /* Process NAME, as it may specify extra dimension(s) for it */
7301       type = build_array_from_name (type, type_wfl, name, &name);
7302
7303       /* Variable redefinition check */
7304       if ((other = lookup_name_in_blocks (name)))
7305         {
7306           variable_redefinition_error (wfl, name, TREE_TYPE (other),
7307                                        DECL_SOURCE_LINE (other));
7308           continue;
7309         }
7310
7311       /* Type adjustment. We may have just readjusted TYPE because
7312          the variable specified more dimensions. Make sure we have
7313          a reference if we can and don't have one already. */
7314       PROMOTE_RECORD_IF_COMPLETE (type, must_chain);
7315
7316       real_type = GET_REAL_TYPE (type);
7317       /* Never layout this decl. This will be done when its scope
7318          will be entered */
7319       decl = build_decl (VAR_DECL, name, real_type);
7320       MAYBE_CREATE_VAR_LANG_DECL_SPECIFIC (decl);
7321       DECL_FINAL (decl) = final_p;
7322       BLOCK_CHAIN_DECL (decl);
7323
7324       /* If doing xreferencing, replace the line number with the WFL
7325          compound value */
7326       if (flag_emit_xref)
7327         DECL_SOURCE_LINE (decl) = EXPR_WFL_LINECOL (wfl);
7328
7329       /* Don't try to use an INIT statement when an error was found */
7330       if (init && java_error_count)
7331         init = NULL_TREE;
7332
7333       /* Add the initialization function to the current function's code */
7334       if (init)
7335         {
7336           /* Name might have been readjusted */
7337           EXPR_WFL_NODE (TREE_OPERAND (init, 0)) = name;
7338           MODIFY_EXPR_FROM_INITIALIZATION_P (init) = 1;
7339           java_method_add_stmt (current_function_decl,
7340                                 build_debugable_stmt (EXPR_WFL_LINECOL (init),
7341                                                       init));
7342         }
7343
7344       /* Setup dependency the type of the decl */
7345       if (must_chain)
7346         {
7347           jdep *dep;
7348           register_incomplete_type (JDEP_VARIABLE, type_wfl, decl, type);
7349           dep = CLASSD_LAST (ctxp->classd_list);
7350           JDEP_GET_PATCH (dep) = &TREE_TYPE (decl);
7351         }
7352     }
7353   SOURCE_FRONTEND_DEBUG (("Defined locals"));
7354 }
7355
7356 /* Called during parsing. Build decls from argument list.  */
7357
7358 static void
7359 source_start_java_method (tree fndecl)
7360 {
7361   tree tem;
7362   tree parm_decl;
7363   int i;
7364
7365   if (!fndecl)
7366     return;
7367
7368   current_function_decl = fndecl;
7369
7370   /* New scope for the function */
7371   enter_block ();
7372   for (tem = TYPE_ARG_TYPES (TREE_TYPE (fndecl)), i = 0;
7373        tem != end_params_node; tem = TREE_CHAIN (tem), i++)
7374     {
7375       tree type = TREE_VALUE (tem);
7376       tree name = TREE_PURPOSE (tem);
7377
7378       /* If type is incomplete. Create an incomplete decl and ask for
7379          the decl to be patched later */
7380       if (INCOMPLETE_TYPE_P (type))
7381         {
7382           jdep *jdep;
7383           tree real_type = GET_REAL_TYPE (type);
7384           parm_decl = build_decl (PARM_DECL, name, real_type);
7385           type = obtain_incomplete_type (type);
7386           register_incomplete_type (JDEP_PARM, NULL_TREE, NULL_TREE, type);
7387           jdep = CLASSD_LAST (ctxp->classd_list);
7388           JDEP_MISC (jdep) = name;
7389           JDEP_GET_PATCH (jdep) = &TREE_TYPE (parm_decl);
7390         }
7391       else
7392         parm_decl = build_decl (PARM_DECL, name, type);
7393
7394       /* Remember if a local variable was declared final (via its
7395          TREE_LIST of type/name.) Set DECL_FINAL accordingly. */
7396       if (ARG_FINAL_P (tem))
7397         {
7398           MAYBE_CREATE_VAR_LANG_DECL_SPECIFIC (parm_decl);
7399           DECL_FINAL (parm_decl) = 1;
7400         }
7401
7402       BLOCK_CHAIN_DECL (parm_decl);
7403     }
7404   tem = BLOCK_EXPR_DECLS (DECL_FUNCTION_BODY (current_function_decl));
7405   BLOCK_EXPR_DECLS (DECL_FUNCTION_BODY (current_function_decl)) =
7406     nreverse (tem);
7407   DECL_ARG_SLOT_COUNT (current_function_decl) = i;
7408   DECL_MAX_LOCALS (current_function_decl) = i;
7409 }
7410
7411 /* Called during parsing. Creates an artificial method declaration.  */
7412
7413 static tree
7414 create_artificial_method (tree class, int flags, tree type,
7415                           tree name, tree args)
7416 {
7417   tree mdecl;
7418
7419   java_parser_context_save_global ();
7420   input_line = 0;
7421   mdecl = make_node (FUNCTION_TYPE);
7422   TREE_TYPE (mdecl) = type;
7423   TYPE_ARG_TYPES (mdecl) = args;
7424   mdecl = add_method (class, flags, name, build_java_signature (mdecl));
7425   java_parser_context_restore_global ();
7426   DECL_ARTIFICIAL (mdecl) = 1;
7427   return mdecl;
7428 }
7429
7430 /* Starts the body if an artificial method.  */
7431
7432 static void
7433 start_artificial_method_body (tree mdecl)
7434 {
7435   DECL_SOURCE_LINE (mdecl) = 1;
7436   DECL_FUNCTION_LAST_LINE (mdecl) = 1;
7437   source_start_java_method (mdecl);
7438   enter_block ();
7439 }
7440
7441 static void
7442 end_artificial_method_body (tree mdecl)
7443 {
7444   /* exit_block modifies DECL_FUNCTION_BODY (current_function_decl).
7445      It has to be evaluated first. (if mdecl is current_function_decl,
7446      we have an undefined behavior if no temporary variable is used.) */
7447   tree b = exit_block ();
7448   BLOCK_EXPR_BODY (DECL_FUNCTION_BODY (mdecl)) = b;
7449   exit_block ();
7450 }
7451
7452 /* Dump a tree of some kind.  This is a convenience wrapper for the
7453    dump_* functions in tree-dump.c.  */
7454 static void
7455 dump_java_tree (enum tree_dump_index phase, tree t)
7456 {
7457   FILE *stream;
7458   int flags;
7459
7460   stream = dump_begin (phase, &flags);
7461   flags |= TDF_SLIM;
7462   if (stream)
7463     {
7464       dump_node (t, flags, stream);
7465       dump_end (phase, stream);
7466     }
7467 }
7468
7469 /* Terminate a function and expand its body.  */
7470
7471 static void
7472 source_end_java_method (void)
7473 {
7474   tree fndecl = current_function_decl;
7475
7476   if (!fndecl)
7477     return;
7478
7479   java_parser_context_save_global ();
7480   input_line = ctxp->last_ccb_indent1;
7481
7482   /* Turn function bodies with only a NOP expr null, so they don't get
7483      generated at all and we won't get warnings when using the -W
7484      -Wall flags. */
7485   if (BLOCK_EXPR_BODY (DECL_FUNCTION_BODY (fndecl)) == empty_stmt_node)
7486     BLOCK_EXPR_BODY (DECL_FUNCTION_BODY (fndecl)) = NULL_TREE;
7487
7488   /* We've generated all the trees for this function, and it has been
7489      patched.  Dump it to a file if the user requested it.  */
7490   dump_java_tree (TDI_original, fndecl);
7491
7492   /* Defer expanding the method until cgraph analysis is complete.  */
7493   if (DECL_SAVED_TREE (fndecl))
7494     cgraph_finalize_function (fndecl, false);
7495
7496   current_function_decl = NULL_TREE;
7497   java_parser_context_restore_global ();
7498 }
7499
7500 /* Record EXPR in the current function block. Complements compound
7501    expression second operand if necessary.  */
7502
7503 tree
7504 java_method_add_stmt (tree fndecl, tree expr)
7505 {
7506   if (!GET_CURRENT_BLOCK (fndecl))
7507     return NULL_TREE;
7508   return add_stmt_to_block (GET_CURRENT_BLOCK (fndecl), NULL_TREE, expr);
7509 }
7510
7511 static tree
7512 add_stmt_to_block (tree b, tree type, tree stmt)
7513 {
7514   tree body = BLOCK_EXPR_BODY (b), c;
7515
7516   if (java_error_count)
7517     return body;
7518
7519   if ((c = add_stmt_to_compound (body, type, stmt)) == body)
7520     return body;
7521
7522   BLOCK_EXPR_BODY (b) = c;
7523   TREE_SIDE_EFFECTS (c) = 1;
7524   return c;
7525 }
7526
7527 /* Add STMT to EXISTING if possible, otherwise create a new
7528    COMPOUND_EXPR and add STMT to it. */
7529
7530 static tree
7531 add_stmt_to_compound (tree existing, tree type, tree stmt)
7532 {
7533   if (existing)
7534     return build (COMPOUND_EXPR, type, existing, stmt);
7535   else
7536     return stmt;
7537 }
7538
7539 void java_layout_seen_class_methods (void)
7540 {
7541   tree previous_list = all_class_list;
7542   tree end = NULL_TREE;
7543   tree current;
7544
7545   while (1)
7546     {
7547       for (current = previous_list;
7548            current != end; current = TREE_CHAIN (current))
7549         layout_class_methods (TREE_TYPE (TREE_VALUE (current)));
7550
7551       if (previous_list != all_class_list)
7552         {
7553           end = previous_list;
7554           previous_list = all_class_list;
7555         }
7556       else
7557         break;
7558     }
7559 }
7560
7561 static GTY(()) tree stop_reordering;
7562 void
7563 java_reorder_fields (void)
7564 {
7565   tree current;
7566
7567   for (current = gclass_list; current; current = TREE_CHAIN (current))
7568     {
7569       current_class = TREE_TYPE (TREE_VALUE (current));
7570
7571       if (current_class == stop_reordering)
7572         break;
7573
7574       /* Reverse the fields, but leave the dummy field in front.
7575          Fields are already ordered for Object and Class */
7576       if (TYPE_FIELDS (current_class) && current_class != object_type_node
7577           && current_class != class_type_node)
7578       {
7579         /* If the dummy field is there, reverse the right fields and
7580            just layout the type for proper fields offset */
7581         if (!DECL_NAME (TYPE_FIELDS (current_class)))
7582           {
7583             tree fields = TYPE_FIELDS (current_class);
7584             TREE_CHAIN (fields) = nreverse (TREE_CHAIN (fields));
7585             TYPE_SIZE (current_class) = NULL_TREE;
7586           }
7587         /* We don't have a dummy field, we need to layout the class,
7588            after having reversed the fields */
7589         else
7590           {
7591             TYPE_FIELDS (current_class) =
7592               nreverse (TYPE_FIELDS (current_class));
7593             TYPE_SIZE (current_class) = NULL_TREE;
7594           }
7595       }
7596     }
7597   /* There are cases were gclass_list will be empty. */
7598   if (gclass_list)
7599     stop_reordering = TREE_TYPE (TREE_VALUE (gclass_list));
7600 }
7601
7602 /* Layout the methods of all classes loaded in one way or another.
7603    Check methods of source parsed classes. Then reorder the
7604    fields and layout the classes or the type of all source parsed
7605    classes */
7606
7607 void
7608 java_layout_classes (void)
7609 {
7610   tree current;
7611   int save_error_count = java_error_count;
7612
7613   /* Layout the methods of all classes seen so far */
7614   java_layout_seen_class_methods ();
7615   java_parse_abort_on_error ();
7616   all_class_list = NULL_TREE;
7617
7618   /* Then check the methods of all parsed classes */
7619   for (current = gclass_list; current; current = TREE_CHAIN (current))
7620     if (CLASS_FROM_SOURCE_P (TREE_TYPE (TREE_VALUE (current))))
7621       java_check_methods (TREE_VALUE (current));
7622   java_parse_abort_on_error ();
7623
7624   for (current = gclass_list; current; current = TREE_CHAIN (current))
7625     {
7626       current_class = TREE_TYPE (TREE_VALUE (current));
7627       layout_class (current_class);
7628
7629       /* Error reported by the caller */
7630       if (java_error_count)
7631         return;
7632     }
7633
7634   /* We might have reloaded classes durign the process of laying out
7635      classes for code generation. We must layout the methods of those
7636      late additions, as constructor checks might use them */
7637   java_layout_seen_class_methods ();
7638   java_parse_abort_on_error ();
7639 }
7640
7641 /* Expand methods in the current set of classes remembered for
7642    generation.  */
7643
7644 static void
7645 java_complete_expand_classes (void)
7646 {
7647   tree current;
7648
7649   do_not_fold = flag_emit_xref;
7650
7651   for (current = ctxp->class_list; current; current = TREE_CHAIN (current))
7652     if (!INNER_CLASS_DECL_P (current))
7653       java_complete_expand_class (current);
7654 }
7655
7656 /* Expand the methods found in OUTER, starting first by OUTER's inner
7657    classes, if any.  */
7658
7659 static void
7660 java_complete_expand_class (tree outer)
7661 {
7662   tree inner_list;
7663
7664   set_nested_class_simple_name_value (outer, 1); /* Set */
7665
7666   /* We need to go after all inner classes and start expanding them,
7667      starting with most nested ones. We have to do that because nested
7668      classes might add functions to outer classes */
7669
7670   for (inner_list = DECL_INNER_CLASS_LIST (outer);
7671        inner_list; inner_list = TREE_CHAIN (inner_list))
7672     java_complete_expand_class (TREE_PURPOSE (inner_list));
7673
7674   java_complete_expand_methods (outer);
7675   set_nested_class_simple_name_value (outer, 0); /* Reset */
7676 }
7677
7678 /* Expand methods registered in CLASS_DECL. The general idea is that
7679    we expand regular methods first. This allows us get an estimate on
7680    how outer context local alias fields are really used so we can add
7681    to the constructor just enough code to initialize them properly (it
7682    also lets us generate finit$ correctly.) Then we expand the
7683    constructors and then <clinit>.  */
7684
7685 static void
7686 java_complete_expand_methods (tree class_decl)
7687 {
7688   tree clinit, decl, first_decl;
7689
7690   current_class = TREE_TYPE (class_decl);
7691
7692   /* Pre-expand <clinit> to figure whether we really need it or
7693      not. If we do need it, we pre-expand the static fields so they're
7694      ready to be used somewhere else. <clinit> will be fully expanded
7695      after we processed the constructors. */
7696   first_decl = TYPE_METHODS (current_class);
7697   clinit = maybe_generate_pre_expand_clinit (current_class);
7698
7699   /* Then generate finit$ (if we need to) because constructors will
7700    try to use it.*/
7701   if (TYPE_FINIT_STMT_LIST (current_class))
7702     java_complete_expand_method (generate_finit (current_class));
7703
7704   /* Then generate instinit$ (if we need to) because constructors will
7705      try to use it. */
7706   if (TYPE_II_STMT_LIST (current_class))
7707     java_complete_expand_method (generate_instinit (current_class));
7708
7709   /* Now do the constructors */
7710   for (decl = first_decl ; !java_error_count && decl; decl = TREE_CHAIN (decl))
7711     {
7712       int no_body;
7713
7714       if (!DECL_CONSTRUCTOR_P (decl))
7715         continue;
7716
7717       no_body = !DECL_FUNCTION_BODY (decl);
7718       /* Don't generate debug info on line zero when expanding a
7719          generated constructor. */
7720       if (no_body)
7721         restore_line_number_status (1);
7722
7723       java_complete_expand_method (decl);
7724
7725       if (no_body)
7726         restore_line_number_status (0);
7727     }
7728
7729   /* First, do the ordinary methods. */
7730   for (decl = first_decl; decl; decl = TREE_CHAIN (decl))
7731     {
7732       /* Ctors aren't part of this batch. */
7733       if (DECL_CONSTRUCTOR_P (decl) || DECL_CLINIT_P (decl))
7734         continue;
7735
7736       /* Skip abstract or native methods -- but do handle native
7737          methods when generating JNI stubs.  */
7738       if (METHOD_ABSTRACT (decl) || (! flag_jni && METHOD_NATIVE (decl)))
7739         {
7740           DECL_FUNCTION_BODY (decl) = NULL_TREE;
7741           continue;
7742         }
7743
7744       if (METHOD_NATIVE (decl))
7745         {
7746           tree body;
7747           current_function_decl = decl;
7748           body = build_jni_stub (decl);
7749           BLOCK_EXPR_BODY (DECL_FUNCTION_BODY (decl)) = body;
7750         }
7751
7752       java_complete_expand_method (decl);
7753     }
7754
7755   /* If there is indeed a <clinit>, fully expand it now */
7756   if (clinit)
7757     {
7758       /* Prevent the use of `this' inside <clinit> */
7759       ctxp->explicit_constructor_p = 1;
7760       java_complete_expand_method (clinit);
7761       ctxp->explicit_constructor_p = 0;
7762     }
7763
7764   /* We might have generated a class$ that we now want to expand */
7765   if (TYPE_DOT_CLASS (current_class))
7766     java_complete_expand_method (TYPE_DOT_CLASS (current_class));
7767
7768   /* Now verify constructor circularity (stop after the first one we
7769      prove wrong.) */
7770   if (!CLASS_INTERFACE (class_decl))
7771     for (decl = TYPE_METHODS (current_class); decl; decl = TREE_CHAIN (decl))
7772       if (DECL_CONSTRUCTOR_P (decl)
7773           && verify_constructor_circularity (decl, decl))
7774         break;
7775 }
7776
7777 /* Attempt to create <clinit>. Pre-expand static fields so they can be
7778    safely used in some other methods/constructors.  */
7779
7780 static tree
7781 maybe_generate_pre_expand_clinit (tree class_type)
7782 {
7783   tree current, mdecl;
7784
7785   if (!TYPE_CLINIT_STMT_LIST (class_type))
7786     return NULL_TREE;
7787
7788   /* Go through all static fields and pre expand them */
7789   for (current = TYPE_FIELDS (class_type); current;
7790        current = TREE_CHAIN (current))
7791     if (FIELD_STATIC (current))
7792       build_field_ref (NULL_TREE, class_type, DECL_NAME (current));
7793
7794   /* Then build the <clinit> method */
7795   mdecl = create_artificial_method (class_type, ACC_STATIC, void_type_node,
7796                                     clinit_identifier_node, end_params_node);
7797   layout_class_method (class_type, CLASSTYPE_SUPER (class_type),
7798                        mdecl, NULL_TREE);
7799   start_artificial_method_body (mdecl);
7800
7801   /* We process the list of assignment we produced as the result of
7802      the declaration of initialized static field and add them as
7803      statement to the <clinit> method. */
7804   for (current = TYPE_CLINIT_STMT_LIST (class_type); current;
7805        current = TREE_CHAIN (current))
7806     {
7807       tree stmt = current;
7808       /* We build the assignment expression that will initialize the
7809          field to its value. There are strict rules on static
7810          initializers (8.5). FIXME */
7811       if (TREE_CODE (stmt) != BLOCK && stmt != empty_stmt_node)
7812         stmt = build_debugable_stmt (EXPR_WFL_LINECOL (stmt), stmt);
7813       java_method_add_stmt (mdecl, stmt);
7814     }
7815
7816   end_artificial_method_body (mdecl);
7817
7818   /* Now we want to place <clinit> as the last method (because we need
7819      it at least for interface so that it doesn't interfere with the
7820      dispatch table based lookup. */
7821   if (TREE_CHAIN (TYPE_METHODS (class_type)))
7822     {
7823       current = TREE_CHAIN (TYPE_METHODS (class_type));
7824       TYPE_METHODS (class_type) = current;
7825
7826       while (TREE_CHAIN (current))
7827         current = TREE_CHAIN (current);
7828
7829       TREE_CHAIN (current) = mdecl;
7830       TREE_CHAIN (mdecl) = NULL_TREE;
7831     }
7832
7833   return mdecl;
7834 }
7835
7836 /* Analyzes a method body and look for something that isn't a
7837    MODIFY_EXPR with a constant value.  */
7838
7839 static int
7840 analyze_clinit_body (tree this_class, tree bbody)
7841 {
7842   while (bbody)
7843     switch (TREE_CODE (bbody))
7844       {
7845       case BLOCK:
7846         bbody = BLOCK_EXPR_BODY (bbody);
7847         break;
7848
7849       case EXPR_WITH_FILE_LOCATION:
7850         bbody = EXPR_WFL_NODE (bbody);
7851         break;
7852
7853       case COMPOUND_EXPR:
7854         if (analyze_clinit_body (this_class, TREE_OPERAND (bbody, 0)))
7855           return 1;
7856         bbody = TREE_OPERAND (bbody, 1);
7857         break;
7858
7859       case MODIFY_EXPR:
7860         /* If we're generating to class file and we're dealing with an
7861            array initialization, we return 1 to keep <clinit> */
7862         if (TREE_CODE (TREE_OPERAND (bbody, 1)) == NEW_ARRAY_INIT
7863             && flag_emit_class_files)
7864           return 1;
7865
7866         /* There are a few cases where we're required to keep
7867            <clinit>:
7868            - If this is an assignment whose operand is not constant,
7869            - If this is an assignment to a non-initialized field,
7870            - If this field is not a member of the current class.
7871         */
7872         return (! TREE_CONSTANT (TREE_OPERAND (bbody, 1))
7873                 || ! DECL_INITIAL (TREE_OPERAND (bbody, 0))
7874                 || DECL_CONTEXT (TREE_OPERAND (bbody, 0)) != this_class);
7875
7876       default:
7877         return 1;
7878       }
7879   return 0;
7880 }
7881
7882
7883 /* See whether we could get rid of <clinit>. Criteria are: all static
7884    final fields have constant initial values and the body of <clinit>
7885    is empty. Return 1 if <clinit> was discarded, 0 otherwise. */
7886
7887 static int
7888 maybe_yank_clinit (tree mdecl)
7889 {
7890   tree type, current;
7891   tree fbody, bbody;
7892
7893   if (!DECL_CLINIT_P (mdecl))
7894     return 0;
7895
7896   /* If the body isn't empty, then we keep <clinit>. Note that if
7897      we're emitting classfiles, this isn't enough not to rule it
7898      out. */
7899   fbody = DECL_FUNCTION_BODY (mdecl);
7900   bbody = BLOCK_EXPR_BODY (fbody);
7901   if (bbody && bbody != error_mark_node)
7902     bbody = BLOCK_EXPR_BODY (bbody);
7903   else
7904     return 0;
7905   if (bbody && ! flag_emit_class_files && bbody != empty_stmt_node)
7906     return 0;
7907
7908   type = DECL_CONTEXT (mdecl);
7909   current = TYPE_FIELDS (type);
7910
7911   for (current = (current ? TREE_CHAIN (current) : current);
7912        current; current = TREE_CHAIN (current))
7913     {
7914       tree f_init;
7915
7916       /* We're not interested in non-static fields.  */
7917       if (!FIELD_STATIC (current))
7918         continue;
7919
7920       /* Nor in fields without initializers. */
7921       f_init = DECL_INITIAL (current);
7922       if (f_init == NULL_TREE)
7923         continue;
7924
7925       /* Anything that isn't String or a basic type is ruled out -- or
7926          if we know how to deal with it (when doing things natively) we
7927          should generated an empty <clinit> so that SUID are computed
7928          correctly. */
7929       if (! JSTRING_TYPE_P (TREE_TYPE (current))
7930           && ! JNUMERIC_TYPE_P (TREE_TYPE (current)))
7931         return 0;
7932
7933       if (! FIELD_FINAL (current) || ! TREE_CONSTANT (f_init))
7934         return 0;
7935     }
7936
7937   /* Now we analyze the method body and look for something that
7938      isn't a MODIFY_EXPR */
7939   if (bbody != empty_stmt_node && analyze_clinit_body (type, bbody))
7940     return 0;
7941
7942   /* Get rid of <clinit> in the class' list of methods */
7943   if (TYPE_METHODS (type) == mdecl)
7944     TYPE_METHODS (type) = TREE_CHAIN (mdecl);
7945   else
7946     for (current = TYPE_METHODS (type); current;
7947          current = TREE_CHAIN (current))
7948       if (TREE_CHAIN (current) == mdecl)
7949         {
7950           TREE_CHAIN (current) = TREE_CHAIN (mdecl);
7951           break;
7952         }
7953
7954   return 1;
7955 }
7956
7957 /* Install the argument from MDECL. Suitable to completion and
7958    expansion of mdecl's body.  */
7959
7960 void
7961 start_complete_expand_method (tree mdecl)
7962 {
7963   tree tem;
7964
7965   pushlevel (1);                /* Prepare for a parameter push */
7966   tem = BLOCK_EXPR_DECLS (DECL_FUNCTION_BODY (current_function_decl));
7967   DECL_ARGUMENTS (mdecl) = tem;
7968
7969   for (; tem; tem = TREE_CHAIN (tem))
7970     {
7971       /* TREE_CHAIN (tem) will change after pushdecl. */
7972       tree next = TREE_CHAIN (tem);
7973       tree type = TREE_TYPE (tem);
7974       if (PROMOTE_PROTOTYPES
7975           && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node)
7976           && INTEGRAL_TYPE_P (type))
7977         type = integer_type_node;
7978       DECL_ARG_TYPE (tem) = type;
7979       layout_decl (tem, 0);
7980       pushdecl (tem);
7981       /* Re-install the next so that the list is kept and the loop
7982          advances. */
7983       TREE_CHAIN (tem) = next;
7984     }
7985   pushdecl_force_head (DECL_ARGUMENTS (mdecl));
7986   input_line = DECL_SOURCE_LINE (mdecl);
7987   build_result_decl (mdecl);
7988 }
7989
7990
7991 /* Complete and expand a method.  */
7992
7993 static void
7994 java_complete_expand_method (tree mdecl)
7995 {
7996   tree fbody, block_body, exception_copy;
7997
7998   current_function_decl = mdecl;
7999   /* Fix constructors before expanding them */
8000   if (DECL_CONSTRUCTOR_P (mdecl))
8001     fix_constructors (mdecl);
8002
8003   /* Expand functions that have a body */
8004   if (!DECL_FUNCTION_BODY (mdecl))
8005     return;
8006
8007   fbody = DECL_FUNCTION_BODY (mdecl);
8008   block_body = BLOCK_EXPR_BODY (fbody);
8009   exception_copy = NULL_TREE;
8010
8011   current_function_decl = mdecl;
8012
8013   if (! quiet_flag)
8014     fprintf (stderr, " [%s.",
8015              lang_printable_name (DECL_CONTEXT (mdecl), 0));
8016   announce_function (mdecl);
8017   if (! quiet_flag)
8018     fprintf (stderr, "]");
8019
8020   /* Prepare the function for tree completion */
8021   start_complete_expand_method (mdecl);
8022
8023   /* Install the current this */
8024   current_this = (!METHOD_STATIC (mdecl) ?
8025                   BLOCK_EXPR_DECLS (DECL_FUNCTION_BODY (mdecl)) : NULL_TREE);
8026
8027   /* Purge the `throws' list of unchecked exceptions (we save a copy
8028      of the list and re-install it later.) */
8029   exception_copy = copy_list (DECL_FUNCTION_THROWS (mdecl));
8030   purge_unchecked_exceptions (mdecl);
8031
8032   /* Install exceptions thrown with `throws' */
8033   PUSH_EXCEPTIONS (DECL_FUNCTION_THROWS (mdecl));
8034
8035   if (block_body != NULL_TREE)
8036     {
8037       block_body = java_complete_tree (block_body);
8038
8039       /* Before we check initialization, attached all class initialization
8040          variable to the block_body */
8041       htab_traverse (DECL_FUNCTION_INIT_TEST_TABLE (mdecl),
8042                      attach_init_test_initialization_flags, block_body);
8043
8044       if (! flag_emit_xref && ! METHOD_NATIVE (mdecl))
8045         {
8046           check_for_initialization (block_body, mdecl);
8047
8048           /* Go through all the flags marking the initialization of
8049              static variables and see whether they're definitively
8050              assigned, in which case the type is remembered as
8051              definitively initialized in MDECL. */
8052           if (STATIC_CLASS_INIT_OPT_P ())
8053             {
8054               /* Always register the context as properly initialized in
8055                  MDECL. This used with caution helps removing extra
8056                  initialization of self. */
8057               if (METHOD_STATIC (mdecl))
8058                 {
8059                   *(htab_find_slot
8060                     (DECL_FUNCTION_INITIALIZED_CLASS_TABLE (mdecl),
8061                      DECL_CONTEXT (mdecl), INSERT)) = DECL_CONTEXT (mdecl);
8062                 }
8063             }
8064         }
8065       ctxp->explicit_constructor_p = 0;
8066     }
8067
8068   BLOCK_EXPR_BODY (fbody) = block_body;
8069
8070   /* If we saw a return but couldn't evaluate it properly, we'll have
8071      an error_mark_node here. */
8072   if (block_body != error_mark_node
8073       && (block_body == NULL_TREE || CAN_COMPLETE_NORMALLY (block_body))
8074       && TREE_CODE (TREE_TYPE (TREE_TYPE (mdecl))) != VOID_TYPE
8075       && !flag_emit_xref)
8076     missing_return_error (current_function_decl);
8077
8078   /* See if we can get rid of <clinit> if MDECL happens to be <clinit> */
8079   maybe_yank_clinit (mdecl);
8080
8081   /* Pop the current level, with special measures if we found errors. */
8082   if (java_error_count)
8083     pushdecl_force_head (DECL_ARGUMENTS (mdecl));
8084   poplevel (1, 0, 1);
8085
8086   /* Pop the exceptions and sanity check */
8087   POP_EXCEPTIONS();
8088   if (currently_caught_type_list)
8089     abort ();
8090
8091   /* Restore the copy of the list of exceptions if emitting xrefs. */
8092   DECL_FUNCTION_THROWS (mdecl) = exception_copy;
8093 }
8094
8095 /* For with each class for which there's code to generate. */
8096
8097 static void
8098 java_expand_method_bodies (tree class)
8099 {
8100   tree decl;
8101   for (decl = TYPE_METHODS (class); decl; decl = TREE_CHAIN (decl))
8102     {
8103       tree block;
8104       tree body;
8105
8106       if (! DECL_FUNCTION_BODY (decl))
8107         continue;
8108
8109       current_function_decl = decl;
8110
8111       block = BLOCK_EXPR_BODY (DECL_FUNCTION_BODY (decl));
8112
8113       if (TREE_CODE (block) != BLOCK)
8114         abort ();
8115
8116       /* Save the function body for inlining.  */
8117       DECL_SAVED_TREE (decl) = block;
8118
8119       body = BLOCK_EXPR_BODY (block);
8120
8121       if (TREE_TYPE (body) == NULL_TREE)
8122         abort ();
8123
8124       /* It's time to assign the variable flagging static class
8125          initialization based on which classes invoked static methods
8126          are definitely initializing. This should be flagged. */
8127       if (STATIC_CLASS_INIT_OPT_P ())
8128         {
8129           tree list = DECL_FUNCTION_STATIC_METHOD_INVOCATION_COMPOUND (decl);
8130           for (; list != NULL_TREE;  list = TREE_CHAIN (list))
8131             {
8132               /* Executed for each statement calling a static function.
8133                  LIST is a TREE_LIST whose PURPOSE is the called function
8134                  and VALUE is a compound whose second operand can be patched
8135                  with static class initialization flag assignments.  */
8136
8137               tree called_method = TREE_PURPOSE (list);
8138               tree compound = TREE_VALUE (list);
8139               tree assignment_compound_list
8140                 = build_tree_list (called_method, NULL);
8141
8142               /* For each class definitely initialized in
8143                  CALLED_METHOD, fill ASSIGNMENT_COMPOUND with
8144                  assignment to the class initialization flag. */
8145               htab_traverse (DECL_FUNCTION_INITIALIZED_CLASS_TABLE (called_method),
8146                              emit_test_initialization,
8147                              assignment_compound_list);
8148
8149               if (TREE_VALUE (assignment_compound_list))
8150                 TREE_OPERAND (compound, 1)
8151                   = TREE_VALUE (assignment_compound_list);
8152             }
8153         }
8154
8155       /* Prepend class initialization to static methods.  */
8156       if (METHOD_STATIC (decl) && ! METHOD_PRIVATE (decl)
8157           && ! flag_emit_class_files
8158           && ! DECL_CLINIT_P (decl)
8159           && ! CLASS_INTERFACE (TYPE_NAME (class)))
8160         {
8161           tree init = build (CALL_EXPR, void_type_node,
8162                              build_address_of (soft_initclass_node),
8163                              build_tree_list (NULL_TREE,
8164                                               build_class_ref (class)),
8165                              NULL_TREE);
8166           TREE_SIDE_EFFECTS (init) = 1;
8167           body = build (COMPOUND_EXPR, TREE_TYPE (body), init, body);
8168           BLOCK_EXPR_BODY (block) = body;
8169         }
8170
8171       /* Wrap synchronized method bodies in a monitorenter
8172          plus monitorexit cleanup.  */
8173       if (METHOD_SYNCHRONIZED (decl) && ! flag_emit_class_files)
8174         {
8175           tree enter, exit, lock;
8176           if (METHOD_STATIC (decl))
8177             lock = build_class_ref (class);
8178           else
8179             lock = DECL_ARGUMENTS (decl);
8180           BUILD_MONITOR_ENTER (enter, lock);
8181           BUILD_MONITOR_EXIT (exit, lock);
8182
8183           body = build (COMPOUND_EXPR, void_type_node,
8184                         enter,
8185                         build (TRY_FINALLY_EXPR, void_type_node, body, exit));
8186           BLOCK_EXPR_BODY (block) = body;
8187         }
8188
8189       /* Expand the the function body.  */
8190       source_end_java_method ();
8191     }
8192 }
8193
8194 \f
8195
8196 /* This section of the code deals with accessing enclosing context
8197    fields either directly by using the relevant access to this$<n> or
8198    by invoking an access method crafted for that purpose.  */
8199
8200 /* Build the necessary access from an inner class to an outer
8201    class. This routine could be optimized to cache previous result
8202    (decl, current_class and returned access).  When an access method
8203    needs to be generated, it always takes the form of a read. It might
8204    be later turned into a write by calling outer_field_access_fix.  */
8205
8206 static tree
8207 build_outer_field_access (tree id, tree decl)
8208 {
8209   tree access = NULL_TREE;
8210   tree ctx = TREE_TYPE (DECL_CONTEXT (TYPE_NAME (current_class)));
8211   tree decl_ctx = DECL_CONTEXT (decl);
8212
8213   /* If the immediate enclosing context of the current class is the
8214      field decl's class or inherits from it; build the access as
8215      `this$<n>.<field>'. Note that we will break the `private' barrier
8216      if we're not emitting bytecodes. */
8217   if ((ctx == decl_ctx || inherits_from_p (ctx, decl_ctx))
8218       && (!FIELD_PRIVATE (decl) || !flag_emit_class_files ))
8219     {
8220       tree thisn = build_current_thisn (current_class);
8221       access = make_qualified_primary (build_wfl_node (thisn),
8222                                        id, EXPR_WFL_LINECOL (id));
8223     }
8224   /* Otherwise, generate access methods to outer this and access the
8225      field (either using an access method or by direct access.) */
8226   else
8227     {
8228       int lc = EXPR_WFL_LINECOL (id);
8229
8230       /* Now we chain the required number of calls to the access$0 to
8231          get a hold to the enclosing instance we need, and then we
8232          build the field access. */
8233       access = build_access_to_thisn (current_class, decl_ctx, lc);
8234
8235       /* If the field is private and we're generating bytecode, then
8236          we generate an access method */
8237       if (FIELD_PRIVATE (decl) && flag_emit_class_files )
8238         {
8239           tree name = build_outer_field_access_methods (decl);
8240           access = build_outer_field_access_expr (lc, decl_ctx,
8241                                                   name, access, NULL_TREE);
8242         }
8243       /* Otherwise we use `access$(this$<j>). ... access$(this$<i>).<field>'.
8244          Once again we break the `private' access rule from a foreign
8245          class. */
8246       else
8247         access = make_qualified_primary (access, id, lc);
8248     }
8249   return resolve_expression_name (access, NULL);
8250 }
8251
8252 /* Return a nonzero value if NODE describes an outer field inner
8253    access.  */
8254
8255 static int
8256 outer_field_access_p (tree type, tree decl)
8257 {
8258   if (!INNER_CLASS_TYPE_P (type)
8259       || TREE_CODE (decl) != FIELD_DECL
8260       || DECL_CONTEXT (decl) == type)
8261     return 0;
8262
8263   /* If the inner class extends the declaration context of the field
8264      we're trying to access, then this isn't an outer field access */
8265   if (inherits_from_p (type, DECL_CONTEXT (decl)))
8266     return 0;
8267
8268   for (type = TREE_TYPE (DECL_CONTEXT (TYPE_NAME (type))); ;
8269        type = TREE_TYPE (DECL_CONTEXT (TYPE_NAME (type))))
8270     {
8271       if (type == DECL_CONTEXT (decl))
8272         return 1;
8273
8274       if (!DECL_CONTEXT (TYPE_NAME (type)))
8275         {
8276           /* Before we give up, see whether the field is inherited from
8277              the enclosing context we're considering. */
8278           if (inherits_from_p (type, DECL_CONTEXT (decl)))
8279             return 1;
8280           break;
8281         }
8282     }
8283
8284   return 0;
8285 }
8286
8287 /* Return a nonzero value if NODE represents an outer field inner
8288    access that was been already expanded. As a side effect, it returns
8289    the name of the field being accessed and the argument passed to the
8290    access function, suitable for a regeneration of the access method
8291    call if necessary. */
8292
8293 static int
8294 outer_field_expanded_access_p (tree node, tree *name, tree *arg_type,
8295                                tree *arg)
8296 {
8297   int identified = 0;
8298
8299   if (TREE_CODE (node) != CALL_EXPR)
8300     return 0;
8301
8302   /* Well, gcj generates slightly different tree nodes when compiling
8303      to native or bytecodes. It's the case for function calls. */
8304
8305   if (flag_emit_class_files
8306       && TREE_CODE (node) == CALL_EXPR
8307       && OUTER_FIELD_ACCESS_IDENTIFIER_P (DECL_NAME (TREE_OPERAND (node, 0))))
8308     identified = 1;
8309   else if (!flag_emit_class_files)
8310     {
8311       node = TREE_OPERAND (node, 0);
8312
8313       if (node && TREE_OPERAND (node, 0)
8314           && TREE_CODE (TREE_OPERAND (node, 0)) == ADDR_EXPR)
8315         {
8316           node = TREE_OPERAND (node, 0);
8317           if (TREE_OPERAND (node, 0)
8318               && TREE_CODE (TREE_OPERAND (node, 0)) == FUNCTION_DECL
8319               && (OUTER_FIELD_ACCESS_IDENTIFIER_P
8320                   (DECL_NAME (TREE_OPERAND (node, 0)))))
8321             identified = 1;
8322         }
8323     }
8324
8325   if (identified && name && arg_type && arg)
8326     {
8327       tree argument = TREE_OPERAND (node, 1);
8328       *name = DECL_NAME (TREE_OPERAND (node, 0));
8329       *arg_type = TREE_TYPE (TREE_TYPE (TREE_VALUE (argument)));
8330       *arg = TREE_VALUE (argument);
8331     }
8332   return identified;
8333 }
8334
8335 /* Detect in NODE an outer field read access from an inner class and
8336    transform it into a write with RHS as an argument. This function is
8337    called from the java_complete_lhs when an assignment to a LHS can
8338    be identified. */
8339
8340 static tree
8341 outer_field_access_fix (tree wfl, tree node, tree rhs)
8342 {
8343   tree name, arg_type, arg;
8344
8345   if (outer_field_expanded_access_p (node, &name, &arg_type, &arg))
8346     {
8347       node = build_outer_field_access_expr (EXPR_WFL_LINECOL (wfl),
8348                                             arg_type, name, arg, rhs);
8349       return java_complete_tree (node);
8350     }
8351   return NULL_TREE;
8352 }
8353
8354 /* Construct the expression that calls an access method:
8355      <type>.access$<n>(<arg1> [, <arg2>]);
8356
8357    ARG2 can be NULL and will be omitted in that case. It will denote a
8358    read access.  */
8359
8360 static tree
8361 build_outer_field_access_expr (int lc, tree type, tree access_method_name,
8362                                tree arg1, tree arg2)
8363 {
8364   tree args, cn, access;
8365
8366   args = arg1 ? arg1 :
8367     build_wfl_node (build_current_thisn (current_class));
8368   args = build_tree_list (NULL_TREE, args);
8369
8370   if (arg2)
8371     args = tree_cons (NULL_TREE, arg2, args);
8372
8373   access = build_method_invocation (build_wfl_node (access_method_name), args);
8374   cn = build_wfl_node (DECL_NAME (TYPE_NAME (type)));
8375   return make_qualified_primary (cn, access, lc);
8376 }
8377
8378 static tree
8379 build_new_access_id (void)
8380 {
8381   static int access_n_counter = 1;
8382   char buffer [128];
8383
8384   sprintf (buffer, "access$%d", access_n_counter++);
8385   return get_identifier (buffer);
8386 }
8387
8388 /* Create the static access functions for the outer field DECL. We define a
8389    read:
8390      TREE_TYPE (<field>) access$<n> (DECL_CONTEXT (<field>) inst$) {
8391        return inst$.field;
8392      }
8393    and a write access:
8394      TREE_TYPE (<field>) access$<n> (DECL_CONTEXT (<field>) inst$,
8395                                      TREE_TYPE (<field>) value$) {
8396        return inst$.field = value$;
8397      }
8398    We should have a usage flags on the DECL so we can lazily turn the ones
8399    we're using for code generation. FIXME.
8400 */
8401
8402 static tree
8403 build_outer_field_access_methods (tree decl)
8404 {
8405   tree id, args, stmt, mdecl;
8406
8407   if (FIELD_INNER_ACCESS_P (decl))
8408     return FIELD_INNER_ACCESS (decl);
8409
8410   MAYBE_CREATE_VAR_LANG_DECL_SPECIFIC (decl);
8411
8412   /* Create the identifier and a function named after it. */
8413   id = build_new_access_id ();
8414
8415   /* The identifier is marked as bearing the name of a generated write
8416      access function for outer field accessed from inner classes. */
8417   OUTER_FIELD_ACCESS_IDENTIFIER_P (id) = 1;
8418
8419   /* Create the read access */
8420   args = build_tree_list (inst_id, build_pointer_type (DECL_CONTEXT (decl)));
8421   TREE_CHAIN (args) = end_params_node;
8422   stmt = make_qualified_primary (build_wfl_node (inst_id),
8423                                  build_wfl_node (DECL_NAME (decl)), 0);
8424   stmt = build_return (0, stmt);
8425   mdecl = build_outer_field_access_method (DECL_CONTEXT (decl),
8426                                            TREE_TYPE (decl), id, args, stmt);
8427   DECL_FUNCTION_ACCESS_DECL (mdecl) = decl;
8428
8429   /* Create the write access method. No write access for final variable */
8430   if (!FIELD_FINAL (decl))
8431     {
8432       args = build_tree_list (inst_id,
8433                               build_pointer_type (DECL_CONTEXT (decl)));
8434       TREE_CHAIN (args) = build_tree_list (wpv_id, TREE_TYPE (decl));
8435       TREE_CHAIN (TREE_CHAIN (args)) = end_params_node;
8436       stmt = make_qualified_primary (build_wfl_node (inst_id),
8437                                      build_wfl_node (DECL_NAME (decl)), 0);
8438       stmt = build_return (0, build_assignment (ASSIGN_TK, 0, stmt,
8439                                                 build_wfl_node (wpv_id)));
8440       mdecl = build_outer_field_access_method (DECL_CONTEXT (decl),
8441                                                TREE_TYPE (decl), id,
8442                                                args, stmt);
8443     }
8444   DECL_FUNCTION_ACCESS_DECL (mdecl) = decl;
8445
8446   /* Return the access name */
8447   return FIELD_INNER_ACCESS (decl) = id;
8448 }
8449
8450 /* Build an field access method NAME.  */
8451
8452 static tree
8453 build_outer_field_access_method (tree class, tree type, tree name,
8454                                  tree args, tree body)
8455 {
8456   tree saved_current_function_decl, mdecl;
8457
8458   /* Create the method */
8459   mdecl = create_artificial_method (class, ACC_STATIC, type, name, args);
8460   fix_method_argument_names (args, mdecl);
8461   layout_class_method (class, NULL_TREE, mdecl, NULL_TREE);
8462
8463   /* Attach the method body. */
8464   saved_current_function_decl = current_function_decl;
8465   start_artificial_method_body (mdecl);
8466   java_method_add_stmt (mdecl, body);
8467   end_artificial_method_body (mdecl);
8468   current_function_decl = saved_current_function_decl;
8469
8470   return mdecl;
8471 }
8472
8473 \f
8474 /* This section deals with building access function necessary for
8475    certain kinds of method invocation from inner classes.  */
8476
8477 static tree
8478 build_outer_method_access_method (tree decl)
8479 {
8480   tree saved_current_function_decl, mdecl;
8481   tree args = NULL_TREE, call_args = NULL_TREE;
8482   tree carg, id, body, class;
8483   char buffer [80];
8484   int parm_id_count = 0;
8485
8486   /* Test this abort with an access to a private field */
8487   if (!strcmp (IDENTIFIER_POINTER (DECL_NAME (decl)), "access$"))
8488     abort ();
8489
8490   /* Check the cache first */
8491   if (DECL_FUNCTION_INNER_ACCESS (decl))
8492     return DECL_FUNCTION_INNER_ACCESS (decl);
8493
8494   class = DECL_CONTEXT (decl);
8495
8496   /* Obtain an access identifier and mark it */
8497   id = build_new_access_id ();
8498   OUTER_FIELD_ACCESS_IDENTIFIER_P (id) = 1;
8499
8500   carg = TYPE_ARG_TYPES (TREE_TYPE (decl));
8501   /* Create the arguments, as much as the original */
8502   for (; carg && carg != end_params_node;
8503        carg = TREE_CHAIN (carg))
8504     {
8505       sprintf (buffer, "write_parm_value$%d", parm_id_count++);
8506       args = chainon (args, build_tree_list (get_identifier (buffer),
8507                                              TREE_VALUE (carg)));
8508     }
8509   args = chainon (args, end_params_node);
8510
8511   /* Create the method */
8512   mdecl = create_artificial_method (class, ACC_STATIC,
8513                                     TREE_TYPE (TREE_TYPE (decl)), id, args);
8514   layout_class_method (class, NULL_TREE, mdecl, NULL_TREE);
8515   /* There is a potential bug here. We should be able to use
8516      fix_method_argument_names, but then arg names get mixed up and
8517      eventually a constructor will have its this$0 altered and the
8518      outer context won't be assignment properly. The testcase is
8519      stub.java FIXME */
8520   TYPE_ARG_TYPES (TREE_TYPE (mdecl)) = args;
8521
8522   /* Attach the method body. */
8523   saved_current_function_decl = current_function_decl;
8524   start_artificial_method_body (mdecl);
8525
8526   /* The actual method invocation uses the same args. When invoking a
8527      static methods that way, we don't want to skip the first
8528      argument. */
8529   carg = args;
8530   if (!METHOD_STATIC (decl))
8531     carg = TREE_CHAIN (carg);
8532   for (; carg && carg != end_params_node; carg = TREE_CHAIN (carg))
8533     call_args = tree_cons (NULL_TREE, build_wfl_node (TREE_PURPOSE (carg)),
8534                            call_args);
8535
8536   body = build_method_invocation (build_wfl_node (DECL_NAME (decl)),
8537                                   call_args);
8538   if (!METHOD_STATIC (decl))
8539     body = make_qualified_primary (build_wfl_node (TREE_PURPOSE (args)),
8540                                    body, 0);
8541   if (TREE_TYPE (TREE_TYPE (decl)) != void_type_node)
8542     body = build_return (0, body);
8543   java_method_add_stmt (mdecl,body);
8544   end_artificial_method_body (mdecl);
8545   current_function_decl = saved_current_function_decl;
8546
8547   /* Back tag the access function so it know what it accesses */
8548   DECL_FUNCTION_ACCESS_DECL (decl) = mdecl;
8549
8550   /* Tag the current method so it knows it has an access generated */
8551   return DECL_FUNCTION_INNER_ACCESS (decl) = mdecl;
8552 }
8553
8554 \f
8555 /* This section of the code deals with building expressions to access
8556    the enclosing instance of an inner class. The enclosing instance is
8557    kept in a generated field called this$<n>, with <n> being the
8558    inner class nesting level (starting from 0.)  */
8559
8560 /* Build an access to a given this$<n>, always chaining access call to
8561    others. Access methods to this$<n> are build on the fly if
8562    necessary. This CAN'T be used to solely access this$<n-1> from
8563    this$<n> (which alway yield to special cases and optimization, see
8564    for example build_outer_field_access).  */
8565
8566 static tree
8567 build_access_to_thisn (tree from, tree to, int lc)
8568 {
8569   tree access = NULL_TREE;
8570
8571   while (from != to && PURE_INNER_CLASS_TYPE_P (from))
8572     {
8573       if (!access)
8574         {
8575           access = build_current_thisn (from);
8576           access = build_wfl_node (access);
8577         }
8578       else
8579         {
8580           tree access0_wfl, cn;
8581
8582           maybe_build_thisn_access_method (from);
8583           access0_wfl = build_wfl_node (access0_identifier_node);
8584           cn = build_wfl_node (DECL_NAME (TYPE_NAME (from)));
8585           EXPR_WFL_LINECOL (access0_wfl) = lc;
8586           access = build_tree_list (NULL_TREE, access);
8587           access = build_method_invocation (access0_wfl, access);
8588           access = make_qualified_primary (cn, access, lc);
8589         }
8590
8591       /* If FROM isn't an inner class, that's fine, we've done enough.
8592          What we're looking for can be accessed from there.  */
8593       from = DECL_CONTEXT (TYPE_NAME (from));
8594       if (!from)
8595         break;
8596       from = TREE_TYPE (from);
8597     }
8598   return access;
8599 }
8600
8601 /* Build an access function to the this$<n> local to TYPE. NULL_TREE
8602    is returned if nothing needs to be generated. Otherwise, the method
8603    generated and a method decl is returned.
8604
8605    NOTE: These generated methods should be declared in a class file
8606    attribute so that they can't be referred to directly.  */
8607
8608 static tree
8609 maybe_build_thisn_access_method (tree type)
8610 {
8611   tree mdecl, args, stmt, rtype;
8612   tree saved_current_function_decl;
8613
8614   /* If TYPE is a top-level class, no access method is required.
8615      If there already is such an access method, bail out. */
8616   if (CLASS_ACCESS0_GENERATED_P (type) || !PURE_INNER_CLASS_TYPE_P (type))
8617     return NULL_TREE;
8618
8619   /* We generate the method. The method looks like:
8620      static <outer_of_type> access$0 (<type> inst$) { return inst$.this$<n>; }
8621   */
8622   args = build_tree_list (inst_id, build_pointer_type (type));
8623   TREE_CHAIN (args) = end_params_node;
8624   rtype = build_pointer_type (TREE_TYPE (DECL_CONTEXT (TYPE_NAME (type))));
8625   mdecl = create_artificial_method (type, ACC_STATIC, rtype,
8626                                     access0_identifier_node, args);
8627   fix_method_argument_names (args, mdecl);
8628   layout_class_method (type, NULL_TREE, mdecl, NULL_TREE);
8629   stmt = build_current_thisn (type);
8630   stmt = make_qualified_primary (build_wfl_node (inst_id),
8631                                  build_wfl_node (stmt), 0);
8632   stmt = build_return (0, stmt);
8633
8634   saved_current_function_decl = current_function_decl;
8635   start_artificial_method_body (mdecl);
8636   java_method_add_stmt (mdecl, stmt);
8637   end_artificial_method_body (mdecl);
8638   current_function_decl = saved_current_function_decl;
8639
8640   CLASS_ACCESS0_GENERATED_P (type) = 1;
8641
8642   return mdecl;
8643 }
8644
8645 /* Craft an correctly numbered `this$<n>'string. this$0 is used for
8646    the first level of innerclassing. this$1 for the next one, etc...
8647    This function can be invoked with TYPE to NULL, available and then
8648    has to count the parser context.  */
8649
8650 static GTY(()) tree saved_thisn;
8651 static GTY(()) tree saved_type;
8652
8653 static tree
8654 build_current_thisn (tree type)
8655 {
8656   static int saved_i = -1;
8657   static int saved_type_i = 0;
8658   tree decl;
8659   char buffer [24];
8660   int i = 0;
8661
8662   if (type)
8663     {
8664       if (type == saved_type)
8665         i = saved_type_i;
8666       else
8667         {
8668           for (i = -1, decl = DECL_CONTEXT (TYPE_NAME (type));
8669                decl; decl = DECL_CONTEXT (decl), i++)
8670             ;
8671
8672           saved_type = type;
8673           saved_type_i = i;
8674         }
8675     }
8676   else
8677     i = list_length (GET_CPC_LIST ())-2;
8678
8679   if (i == saved_i)
8680     return saved_thisn;
8681
8682   sprintf (buffer, "this$%d", i);
8683   saved_i = i;
8684   saved_thisn = get_identifier (buffer);
8685   return saved_thisn;
8686 }
8687
8688 /* Return the assignment to the hidden enclosing context `this$<n>'
8689    by the second incoming parameter to the innerclass constructor. The
8690    form used is `this.this$<n> = this$<n>;'.  */
8691
8692 static tree
8693 build_thisn_assign (void)
8694 {
8695   if (current_class && PURE_INNER_CLASS_TYPE_P (current_class))
8696     {
8697       tree thisn = build_current_thisn (current_class);
8698       tree lhs = make_qualified_primary (build_wfl_node (this_identifier_node),
8699                                          build_wfl_node (thisn), 0);
8700       tree rhs = build_wfl_node (thisn);
8701       EXPR_WFL_SET_LINECOL (lhs, input_line, 0);
8702       return build_assignment (ASSIGN_TK, EXPR_WFL_LINECOL (lhs), lhs, rhs);
8703     }
8704   return NULL_TREE;
8705 }
8706
8707 \f
8708 /* Building the synthetic `class$' used to implement the `.class' 1.1
8709    extension for non primitive types. This method looks like:
8710
8711     static Class class$(String type) throws NoClassDefFoundError
8712     {
8713       try {return (java.lang.Class.forName (String));}
8714       catch (ClassNotFoundException e) {
8715         throw new NoClassDefFoundError(e.getMessage());}
8716     } */
8717
8718 static GTY(()) tree get_message_wfl;
8719 static GTY(()) tree type_parm_wfl;
8720
8721 static tree
8722 build_dot_class_method (tree class)
8723 {
8724 #define BWF(S) build_wfl_node (get_identifier ((S)))
8725 #define MQN(X,Y) make_qualified_name ((X), (Y), 0)
8726   tree args, tmp, saved_current_function_decl, mdecl, qual_name;
8727   tree stmt, throw_stmt;
8728
8729   if (!get_message_wfl)
8730     {
8731       get_message_wfl = build_wfl_node (get_identifier ("getMessage"));
8732       type_parm_wfl = build_wfl_node (get_identifier ("type$"));
8733     }
8734
8735   /* Build the arguments */
8736   args = build_tree_list (get_identifier ("type$"),
8737                           build_pointer_type (string_type_node));
8738   TREE_CHAIN (args) = end_params_node;
8739
8740   /* Build the qualified name java.lang.Class.forName */
8741   tmp = MQN (MQN (MQN (BWF ("java"),
8742                        BWF ("lang")), BWF ("Class")), BWF ("forName"));
8743
8744   /* Create the "class$" function */
8745   mdecl = create_artificial_method (class, ACC_STATIC,
8746                                     build_pointer_type (class_type_node),
8747                                     classdollar_identifier_node, args);
8748   qual_name = MQN (MQN (BWF ("java"), BWF ("lang")),
8749                    BWF ("NoClassDefFoundError"));
8750   DECL_FUNCTION_THROWS (mdecl) = build_tree_list (NULL_TREE, qual_name);
8751   register_incomplete_type (JDEP_EXCEPTION, qual_name, NULL_TREE, NULL_TREE);
8752   JDEP_GET_PATCH (CLASSD_LAST (ctxp->classd_list)) =
8753     &TREE_VALUE (DECL_FUNCTION_THROWS (mdecl));
8754
8755   /* We start by building the try block. We need to build:
8756        return (java.lang.Class.forName (type)); */
8757   stmt = build_method_invocation (tmp,
8758                                   build_tree_list (NULL_TREE, type_parm_wfl));
8759   stmt = build_return (0, stmt);
8760
8761   /* Now onto the catch block. We start by building the expression
8762      throwing a new exception: throw new NoClassDefFoundError (_.getMessage) */
8763   throw_stmt = make_qualified_name (build_wfl_node (wpv_id),
8764                                     get_message_wfl, 0);
8765   throw_stmt = build_method_invocation (throw_stmt, NULL_TREE);
8766
8767   /* Build new NoClassDefFoundError (_.getMessage) */
8768   throw_stmt = build_new_invocation
8769     (build_wfl_node (get_identifier ("NoClassDefFoundError")),
8770      build_tree_list (build_pointer_type (string_type_node), throw_stmt));
8771
8772   /* Build the throw, (it's too early to use BUILD_THROW) */
8773   throw_stmt = build1 (THROW_EXPR, NULL_TREE, throw_stmt);
8774
8775   /* Encapsulate STMT in a try block. The catch clause executes THROW_STMT */
8776   qual_name = MQN (MQN (BWF ("java"), BWF ("lang")),
8777                    BWF ("ClassNotFoundException"));
8778   stmt = encapsulate_with_try_catch (0, qual_name, stmt, throw_stmt);
8779
8780   fix_method_argument_names (args, mdecl);
8781   layout_class_method (class, NULL_TREE, mdecl, NULL_TREE);
8782   saved_current_function_decl = current_function_decl;
8783   start_artificial_method_body (mdecl);
8784   java_method_add_stmt (mdecl, stmt);
8785   end_artificial_method_body (mdecl);
8786   current_function_decl = saved_current_function_decl;
8787   TYPE_DOT_CLASS (class) = mdecl;
8788
8789   return mdecl;
8790 }
8791
8792 static tree
8793 build_dot_class_method_invocation (tree this_class, tree type)
8794 {
8795   tree dot_class_method = TYPE_DOT_CLASS (this_class);
8796   tree sig_id, s, t;
8797
8798   if (TYPE_ARRAY_P (type))
8799     sig_id = build_java_signature (type);
8800   else
8801     sig_id = DECL_NAME (TYPE_NAME (type));
8802
8803   /* Ensure that the proper name separator is used */
8804   sig_id = unmangle_classname (IDENTIFIER_POINTER (sig_id),
8805                                IDENTIFIER_LENGTH (sig_id));
8806
8807   s = build_string (IDENTIFIER_LENGTH (sig_id),
8808                     IDENTIFIER_POINTER (sig_id));
8809   t = build_method_invocation (build_wfl_node (DECL_NAME (dot_class_method)),
8810                                build_tree_list (NULL_TREE, s));
8811   if (DECL_CONTEXT (dot_class_method) != this_class)
8812     {
8813       tree class_name = DECL_NAME (TYPE_NAME (DECL_CONTEXT (dot_class_method)));
8814       t = make_qualified_primary (build_wfl_node (class_name), t, 0);
8815     }
8816   return t;
8817 }
8818
8819 /* This section of the code deals with constructor.  */
8820
8821 /* Craft a body for default constructor. Patch existing constructor
8822    bodies with call to super() and field initialization statements if
8823    necessary.  */
8824
8825 static void
8826 fix_constructors (tree mdecl)
8827 {
8828   tree iii;                     /* Instance Initializer Invocation */
8829   tree body = DECL_FUNCTION_BODY (mdecl);
8830   tree thisn_assign, compound = NULL_TREE;
8831   tree class_type = DECL_CONTEXT (mdecl);
8832
8833   if (DECL_FIXED_CONSTRUCTOR_P (mdecl))
8834     return;
8835   DECL_FIXED_CONSTRUCTOR_P (mdecl) = 1;
8836
8837   if (!body)
8838     {
8839       /* It is an error for the compiler to generate a default
8840          constructor if the superclass doesn't have a constructor that
8841          takes no argument, or the same args for an anonymous class */
8842       if (verify_constructor_super (mdecl))
8843         {
8844           tree sclass_decl = TYPE_NAME (CLASSTYPE_SUPER (class_type));
8845           tree save = DECL_NAME (mdecl);
8846           const char *n = IDENTIFIER_POINTER (DECL_NAME (sclass_decl));
8847           DECL_NAME (mdecl) = DECL_NAME (sclass_decl);
8848           parse_error_context
8849             (lookup_cl (TYPE_NAME (class_type)),
8850              "No constructor matching `%s' found in class `%s'",
8851              lang_printable_name (mdecl, 0), n);
8852           DECL_NAME (mdecl) = save;
8853         }
8854
8855       /* The constructor body must be crafted by hand. It's the
8856          constructor we defined when we realize we didn't have the
8857          CLASSNAME() constructor */
8858       start_artificial_method_body (mdecl);
8859
8860       /* Insert an assignment to the this$<n> hidden field, if
8861          necessary */
8862       if ((thisn_assign = build_thisn_assign ()))
8863         java_method_add_stmt (mdecl, thisn_assign);
8864
8865       /* We don't generate a super constructor invocation if we're
8866          compiling java.lang.Object. build_super_invocation takes care
8867          of that. */
8868       java_method_add_stmt (mdecl, build_super_invocation (mdecl));
8869
8870       /* FIXME */
8871       if ((iii = build_instinit_invocation (class_type)))
8872         java_method_add_stmt (mdecl, iii);
8873
8874       end_artificial_method_body (mdecl);
8875     }
8876   /* Search for an explicit constructor invocation */
8877   else
8878     {
8879       int found = 0;
8880       int invokes_this = 0;
8881       tree found_call = NULL_TREE;
8882       tree main_block = BLOCK_EXPR_BODY (body);
8883
8884       while (body)
8885         switch (TREE_CODE (body))
8886           {
8887           case CALL_EXPR:
8888             found = CALL_EXPLICIT_CONSTRUCTOR_P (body);
8889             if (CALL_THIS_CONSTRUCTOR_P (body))
8890               invokes_this = 1;
8891             body = NULL_TREE;
8892             break;
8893           case COMPOUND_EXPR:
8894           case EXPR_WITH_FILE_LOCATION:
8895             found_call = body;
8896             body = TREE_OPERAND (body, 0);
8897             break;
8898           case BLOCK:
8899             found_call = body;
8900             body = BLOCK_EXPR_BODY (body);
8901             break;
8902           default:
8903             found = 0;
8904             body = NULL_TREE;
8905           }
8906
8907       /* Generate the assignment to this$<n>, if necessary */
8908       if ((thisn_assign = build_thisn_assign ()))
8909         compound = add_stmt_to_compound (compound, NULL_TREE, thisn_assign);
8910
8911       /* The constructor is missing an invocation of super() */
8912       if (!found)
8913         compound = add_stmt_to_compound (compound, NULL_TREE,
8914                                          build_super_invocation (mdecl));
8915       /* Explicit super() invocation should take place before the
8916          instance initializer blocks. */
8917       else
8918         {
8919           compound = add_stmt_to_compound (compound, NULL_TREE,
8920                                            TREE_OPERAND (found_call, 0));
8921           TREE_OPERAND (found_call, 0) = empty_stmt_node;
8922         }
8923
8924       DECL_INIT_CALLS_THIS (mdecl) = invokes_this;
8925
8926       /* Insert the instance initializer block right after. */
8927       if (!invokes_this && (iii = build_instinit_invocation (class_type)))
8928         compound = add_stmt_to_compound (compound, NULL_TREE, iii);
8929
8930       /* Fix the constructor main block if we're adding extra stmts */
8931       if (compound)
8932         {
8933           compound = add_stmt_to_compound (compound, NULL_TREE,
8934                                            BLOCK_EXPR_BODY (main_block));
8935           BLOCK_EXPR_BODY (main_block) = compound;
8936         }
8937     }
8938 }
8939
8940 /* Browse constructors in the super class, searching for a constructor
8941    that doesn't take any argument. Return 0 if one is found, 1
8942    otherwise.  If the current class is an anonymous inner class, look
8943    for something that has the same signature. */
8944
8945 static int
8946 verify_constructor_super (tree mdecl)
8947 {
8948   tree class = CLASSTYPE_SUPER (current_class);
8949   int super_inner = PURE_INNER_CLASS_TYPE_P (class);
8950   tree sdecl;
8951
8952   if (!class)
8953     return 0;
8954
8955   if (ANONYMOUS_CLASS_P (current_class))
8956     {
8957       tree mdecl_arg_type;
8958       SKIP_THIS_AND_ARTIFICIAL_PARMS (mdecl_arg_type, mdecl);
8959       for (sdecl = TYPE_METHODS (class); sdecl; sdecl = TREE_CHAIN (sdecl))
8960         if (DECL_CONSTRUCTOR_P (sdecl))
8961           {
8962             tree m_arg_type;
8963             tree arg_type = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (sdecl)));
8964             if (super_inner)
8965               arg_type = TREE_CHAIN (arg_type);
8966             for (m_arg_type = mdecl_arg_type;
8967                  (arg_type != end_params_node
8968                   && m_arg_type != end_params_node);
8969                  arg_type = TREE_CHAIN (arg_type),
8970                    m_arg_type = TREE_CHAIN (m_arg_type))
8971               if (!valid_method_invocation_conversion_p
8972                      (TREE_VALUE (arg_type),
8973                       TREE_VALUE (m_arg_type)))
8974                 break;
8975
8976             if (arg_type == end_params_node && m_arg_type == end_params_node)
8977               return 0;
8978           }
8979     }
8980   else
8981     {
8982       for (sdecl = TYPE_METHODS (class); sdecl; sdecl = TREE_CHAIN (sdecl))
8983         {
8984           tree arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (sdecl)));
8985           if (super_inner)
8986             arg = TREE_CHAIN (arg);
8987           if (DECL_CONSTRUCTOR_P (sdecl) && arg == end_params_node)
8988             return 0;
8989         }
8990     }
8991   return 1;
8992 }
8993
8994 /* Generate code for all context remembered for code generation.  */
8995
8996 static GTY(()) tree reversed_class_list;
8997 void
8998 java_expand_classes (void)
8999 {
9000   int save_error_count = 0;
9001   static struct parser_ctxt *cur_ctxp = NULL;
9002
9003   java_parse_abort_on_error ();
9004   if (!(ctxp = ctxp_for_generation))
9005     return;
9006   java_layout_classes ();
9007   java_parse_abort_on_error ();
9008
9009   for (cur_ctxp = ctxp_for_generation; cur_ctxp; cur_ctxp = cur_ctxp->next)
9010     {
9011       ctxp = cur_ctxp;
9012       input_filename = ctxp->filename;
9013       lang_init_source (2);            /* Error msgs have method prototypes */
9014       java_complete_expand_classes (); /* Complete and expand classes */
9015       java_parse_abort_on_error ();
9016     }
9017   input_filename = main_input_filename;
9018
9019
9020   /* Find anonymous classes and expand their constructor. This extra pass is
9021      necessary because the constructor itself is only generated when the
9022      method in which it is defined is expanded. */
9023   for (cur_ctxp = ctxp_for_generation; cur_ctxp; cur_ctxp = cur_ctxp->next)
9024     {
9025       tree current;
9026       ctxp = cur_ctxp;
9027       for (current = ctxp->class_list; current; current = TREE_CHAIN (current))
9028         {
9029           current_class = TREE_TYPE (current);
9030           if (ANONYMOUS_CLASS_P (current_class))
9031             {
9032               tree d;
9033               for (d = TYPE_METHODS (current_class); d; d = TREE_CHAIN (d))
9034                 {
9035                   if (DECL_CONSTRUCTOR_P (d))
9036                     {
9037                       restore_line_number_status (1);
9038                       java_complete_expand_method (d);
9039                       restore_line_number_status (0);
9040                       break;    /* There is only one constructor. */
9041                     }
9042                 }
9043             }
9044         }
9045     }
9046
9047   /* Expanding the constructors of anonymous classes generates access
9048      methods.  Scan all the methods looking for null DECL_RESULTs --
9049      this will be the case if a method hasn't been expanded.  */
9050   for (cur_ctxp = ctxp_for_generation; cur_ctxp; cur_ctxp = cur_ctxp->next)
9051     {
9052       tree current;
9053       ctxp = cur_ctxp;
9054       for (current = ctxp->class_list; current; current = TREE_CHAIN (current))
9055         {
9056           tree d;
9057           current_class = TREE_TYPE (current);
9058           for (d = TYPE_METHODS (current_class); d; d = TREE_CHAIN (d))
9059             {
9060               if (DECL_RESULT (d) == NULL_TREE)
9061                 {
9062                   restore_line_number_status (1);
9063                   java_complete_expand_method (d);
9064                   restore_line_number_status (0);
9065                 }
9066             }
9067         }
9068     }
9069
9070   /* ???  Instead of all this we could iterate around the list of
9071      classes until there were no more un-expanded methods.  It would
9072      take a little longer -- one pass over the whole list of methods
9073      -- but it would be simpler.  Like this:  */
9074 #if 0
9075     {
9076       int something_changed;
9077     
9078       do
9079         {
9080           something_changed = 0;
9081           for (cur_ctxp = ctxp_for_generation; cur_ctxp; cur_ctxp = cur_ctxp->next)
9082             {
9083               tree current;
9084               ctxp = cur_ctxp;
9085               for (current = ctxp->class_list; current; current = TREE_CHAIN (current))
9086                 {
9087                   tree d;
9088                   current_class = TREE_TYPE (current);
9089                   for (d = TYPE_METHODS (current_class); d; d = TREE_CHAIN (d))
9090                     {
9091                       if (DECL_RESULT (d) == NULL_TREE)
9092                         {
9093                           something_changed = 1;
9094                           restore_line_number_status (1);
9095                           java_complete_expand_method (d);
9096                           restore_line_number_status (0);
9097                         }
9098                     }
9099                 }
9100             }
9101         }
9102       while (something_changed);
9103     }
9104 #endif
9105
9106   /* If we've found error at that stage, don't try to generate
9107      anything, unless we're emitting xrefs or checking the syntax only
9108      (but not using -fsyntax-only for the purpose of generating
9109      bytecode. */
9110   if (java_error_count && !flag_emit_xref
9111       && (!flag_syntax_only && !flag_emit_class_files))
9112     return;
9113
9114   /* Now things are stable, go for generation of the class data. */
9115
9116   /* We pessimistically marked all methods and fields external until
9117      we knew what set of classes we were planning to compile.  Now mark
9118      those that will be generated locally as not external.  */
9119   for (cur_ctxp = ctxp_for_generation; cur_ctxp; cur_ctxp = cur_ctxp->next)
9120     {
9121       tree current;
9122       ctxp = cur_ctxp;
9123       for (current = ctxp->class_list; current; current = TREE_CHAIN (current))
9124         java_mark_class_local (TREE_TYPE (current));
9125     }
9126
9127   /* Compile the classes.  */
9128   for (cur_ctxp = ctxp_for_generation; cur_ctxp; cur_ctxp = cur_ctxp->next)
9129     {
9130       tree current;
9131       reversed_class_list = NULL;
9132
9133       ctxp = cur_ctxp;
9134
9135       /* We write out the classes in reverse order.  This ensures that
9136          inner classes are written before their containing classes,
9137          which is important for parallel builds.  Otherwise, the
9138          class file for the outer class may be found, but the class
9139          file for the inner class may not be present.  In that
9140          situation, the compiler cannot fall back to the original
9141          source, having already read the outer class, so we must
9142          prevent that situation.  */
9143       for (current = ctxp->class_list;
9144            current;
9145            current = TREE_CHAIN (current))
9146         reversed_class_list
9147           = tree_cons (NULL_TREE, current, reversed_class_list);
9148
9149       for (current = reversed_class_list;
9150            current;
9151            current = TREE_CHAIN (current))
9152         {
9153           current_class = TREE_TYPE (TREE_VALUE (current));
9154           if (flag_emit_class_files)
9155             write_classfile (current_class);
9156           if (flag_emit_xref)
9157             expand_xref (current_class);
9158           else if (! flag_syntax_only)
9159             java_expand_method_bodies (current_class);
9160         }
9161     }
9162 }
9163
9164 void
9165 java_finish_classes (void)
9166 {
9167   static struct parser_ctxt *cur_ctxp = NULL;
9168   for (cur_ctxp = ctxp_for_generation; cur_ctxp; cur_ctxp = cur_ctxp->next)
9169     {
9170       tree current;
9171       ctxp = cur_ctxp;
9172       for (current = ctxp->class_list; current; current = TREE_CHAIN (current))
9173         {
9174           current_class = TREE_TYPE (current);
9175           finish_class ();
9176         }
9177     }
9178 }
9179
9180 /* Wrap non WFL PRIMARY around a WFL and set EXPR_WFL_QUALIFICATION to
9181    a tree list node containing RIGHT. Fore coming RIGHTs will be
9182    chained to this hook. LOCATION contains the location of the
9183    separating `.' operator.  */
9184
9185 static tree
9186 make_qualified_primary (tree primary, tree right, int location)
9187 {
9188   tree wfl;
9189
9190   if (TREE_CODE (primary) != EXPR_WITH_FILE_LOCATION)
9191     wfl = build_wfl_wrap (primary, location);
9192   else
9193     {
9194       wfl = primary;
9195       /* If wfl wasn't qualified, we build a first anchor */
9196       if (!EXPR_WFL_QUALIFICATION (wfl))
9197         EXPR_WFL_QUALIFICATION (wfl) = build_tree_list (wfl, NULL_TREE);
9198     }
9199
9200   /* And chain them */
9201   EXPR_WFL_LINECOL (right) = location;
9202   chainon (EXPR_WFL_QUALIFICATION (wfl), build_tree_list (right, NULL_TREE));
9203   PRIMARY_P (wfl) =  1;
9204   return wfl;
9205 }
9206
9207 /* Simple merge of two name separated by a `.' */
9208
9209 static tree
9210 merge_qualified_name (tree left, tree right)
9211 {
9212   tree node;
9213   if (!left && !right)
9214     return NULL_TREE;
9215
9216   if (!left)
9217     return right;
9218
9219   if (!right)
9220     return left;
9221
9222   obstack_grow (&temporary_obstack, IDENTIFIER_POINTER (left),
9223                 IDENTIFIER_LENGTH (left));
9224   obstack_1grow (&temporary_obstack, '.');
9225   obstack_grow0 (&temporary_obstack, IDENTIFIER_POINTER (right),
9226                  IDENTIFIER_LENGTH (right));
9227   node =  get_identifier (obstack_base (&temporary_obstack));
9228   obstack_free (&temporary_obstack, obstack_base (&temporary_obstack));
9229   QUALIFIED_P (node) = 1;
9230   return node;
9231 }
9232
9233 /* Merge the two parts of a qualified name into LEFT.  Set the
9234    location information of the resulting node to LOCATION, usually
9235    inherited from the location information of the `.' operator. */
9236
9237 static tree
9238 make_qualified_name (tree left, tree right, int location)
9239 {
9240 #ifdef USE_COMPONENT_REF
9241   tree node = build (COMPONENT_REF, NULL_TREE, left, right);
9242   EXPR_WFL_LINECOL (node) = location;
9243   return node;
9244 #else
9245   tree left_id = EXPR_WFL_NODE (left);
9246   tree right_id = EXPR_WFL_NODE (right);
9247   tree wfl, merge;
9248
9249   merge = merge_qualified_name (left_id, right_id);
9250
9251   /* Left wasn't qualified and is now qualified */
9252   if (!QUALIFIED_P (left_id))
9253     {
9254       tree wfl = build_expr_wfl (left_id, ctxp->filename, 0, 0);
9255       EXPR_WFL_LINECOL (wfl) = EXPR_WFL_LINECOL (left);
9256       EXPR_WFL_QUALIFICATION (left) = build_tree_list (wfl, NULL_TREE);
9257     }
9258
9259   wfl = build_expr_wfl (right_id, ctxp->filename, 0, 0);
9260   EXPR_WFL_LINECOL (wfl) = location;
9261   chainon (EXPR_WFL_QUALIFICATION (left), build_tree_list (wfl, NULL_TREE));
9262
9263   EXPR_WFL_NODE (left) = merge;
9264   return left;
9265 #endif
9266 }
9267
9268 /* Extract the last identifier component of the qualified in WFL. The
9269    last identifier is removed from the linked list */
9270
9271 static tree
9272 cut_identifier_in_qualified (tree wfl)
9273 {
9274   tree q;
9275   tree previous = NULL_TREE;
9276   for (q = EXPR_WFL_QUALIFICATION (wfl); ; previous = q, q = TREE_CHAIN (q))
9277     if (!TREE_CHAIN (q))
9278       {
9279         if (!previous)
9280           /* Operating on a non qualified qualified WFL.  */
9281           abort ();
9282
9283         TREE_CHAIN (previous) = NULL_TREE;
9284         return TREE_PURPOSE (q);
9285       }
9286 }
9287
9288 /* Resolve the expression name NAME. Return its decl.  */
9289
9290 static tree
9291 resolve_expression_name (tree id, tree *orig)
9292 {
9293   tree name = EXPR_WFL_NODE (id);
9294   tree decl;
9295
9296   /* 6.5.5.1: Simple expression names */
9297   if (!PRIMARY_P (id) && !QUALIFIED_P (name))
9298     {
9299       /* 15.13.1: NAME can appear within the scope of a local variable
9300          declaration */
9301       if ((decl = IDENTIFIER_LOCAL_VALUE (name)))
9302         return decl;
9303
9304       /* 15.13.1: NAME can appear within a class declaration */
9305       else
9306         {
9307           decl = lookup_field_wrapper (current_class, name);
9308           if (decl)
9309             {
9310               tree access = NULL_TREE;
9311               int fs = FIELD_STATIC (decl);
9312
9313               /* If we're accessing an outer scope local alias, make
9314                  sure we change the name of the field we're going to
9315                  build access to. */
9316               if (FIELD_LOCAL_ALIAS_USED (decl))
9317                 name = DECL_NAME (decl);
9318
9319               check_deprecation (id, decl);
9320
9321               /* Instance variable (8.3.1.1) can't appear within
9322                  static method, static initializer or initializer for
9323                  a static variable. */
9324               if (!fs && METHOD_STATIC (current_function_decl))
9325                 {
9326                   static_ref_err (id, name, current_class);
9327                   return error_mark_node;
9328                 }
9329               /* Instance variables can't appear as an argument of
9330                  an explicit constructor invocation */
9331               if (!fs && ctxp->explicit_constructor_p
9332                   && !enclosing_context_p (DECL_CONTEXT (decl), current_class))
9333                 {
9334                   parse_error_context
9335                     (id, "Can't reference `%s' before the superclass constructor has been called", IDENTIFIER_POINTER (name));
9336                   return error_mark_node;
9337                 }
9338
9339               /* If we're processing an inner class and we're trying
9340                  to access a field belonging to an outer class, build
9341                  the access to the field */
9342               if (!fs && outer_field_access_p (current_class, decl))
9343                 {
9344                   if (CLASS_STATIC (TYPE_NAME (current_class)))
9345                     {
9346                       static_ref_err (id, DECL_NAME (decl), current_class);
9347                       return error_mark_node;
9348                     }
9349                   access = build_outer_field_access (id, decl);
9350                   if (orig)
9351                     *orig = access;
9352                   return access;
9353                 }
9354
9355               /* Otherwise build what it takes to access the field */
9356               access = build_field_ref ((fs ? NULL_TREE : current_this),
9357                                         DECL_CONTEXT (decl), name);
9358               if (fs)
9359                 access = maybe_build_class_init_for_field (decl, access);
9360               /* We may be asked to save the real field access node */
9361               if (orig)
9362                 *orig = access;
9363               /* Last check: can we access the field? */
9364               if (not_accessible_p (current_class, decl, NULL_TREE, 0))
9365                 {
9366                   not_accessible_field_error (id, decl);
9367                   return error_mark_node;
9368                 }
9369               /* And we return what we got */
9370               return access;
9371             }
9372           /* Fall down to error report on undefined variable */
9373         }
9374     }
9375   /* 6.5.5.2 Qualified Expression Names */
9376   else
9377     {
9378       if (orig)
9379         *orig = NULL_TREE;
9380       qualify_ambiguous_name (id);
9381       /* 15.10.1 Field Access Using a Primary and/or Expression Name */
9382       /* 15.10.2: Accessing Superclass Members using super */
9383       return resolve_field_access (id, orig, NULL);
9384     }
9385
9386   /* We've got an error here */
9387   if (INNER_CLASS_TYPE_P (current_class))
9388     parse_error_context (id,
9389                          "Local variable `%s' can't be accessed from within the inner class `%s' unless it is declared final",
9390                          IDENTIFIER_POINTER (name),
9391                          IDENTIFIER_POINTER (DECL_NAME
9392                                              (TYPE_NAME (current_class))));
9393   else
9394     parse_error_context (id, "Undefined variable `%s'",
9395                          IDENTIFIER_POINTER (name));
9396
9397   return error_mark_node;
9398 }
9399
9400 static void
9401 static_ref_err (tree wfl, tree field_id, tree class_type)
9402 {
9403   parse_error_context
9404     (wfl,
9405      "Can't make a static reference to nonstatic variable `%s' in class `%s'",
9406      IDENTIFIER_POINTER (field_id),
9407      IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (class_type))));
9408 }
9409
9410 /* 15.10.1 Field Access Using a Primary and/or Expression Name.
9411    We return something suitable to generate the field access. We also
9412    return the field decl in FIELD_DECL and its type in FIELD_TYPE.  If
9413    recipient's address can be null. */
9414
9415 static tree
9416 resolve_field_access (tree qual_wfl, tree *field_decl, tree *field_type)
9417 {
9418   int is_static = 0;
9419   tree field_ref;
9420   tree decl, where_found, type_found;
9421
9422   if (resolve_qualified_expression_name (qual_wfl, &decl,
9423                                          &where_found, &type_found))
9424     return error_mark_node;
9425
9426   /* Resolve the LENGTH field of an array here */
9427   if (DECL_P (decl) && DECL_NAME (decl) == length_identifier_node
9428       && type_found && TYPE_ARRAY_P (type_found)
9429       && ! flag_emit_class_files && ! flag_emit_xref)
9430     {
9431       tree length = build_java_array_length_access (where_found);
9432       field_ref = length;
9433
9434       /* In case we're dealing with a static array, we need to
9435          initialize its class before the array length can be fetched.
9436          It's also a good time to create a DECL_RTL for the field if
9437          none already exists, otherwise if the field was declared in a
9438          class found in an external file and hasn't been (and won't
9439          be) accessed for its value, none will be created. */
9440       if (TREE_CODE (where_found) == VAR_DECL && FIELD_STATIC (where_found))
9441         {
9442           build_static_field_ref (where_found);
9443           field_ref = build_class_init (DECL_CONTEXT (where_found), field_ref);
9444         }
9445     }
9446   /* We might have been trying to resolve field.method(). In which
9447      case, the resolution is over and decl is the answer */
9448   else if (JDECL_P (decl) && IDENTIFIER_LOCAL_VALUE (DECL_NAME (decl)) == decl)
9449     field_ref = decl;
9450   else if (JDECL_P (decl))
9451     {
9452       if (!type_found)
9453         type_found = DECL_CONTEXT (decl);
9454       is_static = FIELD_STATIC (decl);
9455       field_ref = build_field_ref ((is_static && !flag_emit_xref?
9456                                     NULL_TREE : where_found),
9457                                    type_found, DECL_NAME (decl));
9458       if (field_ref == error_mark_node)
9459         return error_mark_node;
9460       if (is_static)
9461         field_ref = maybe_build_class_init_for_field (decl, field_ref);
9462
9463       /* If we're looking at a static field, we may need to generate a
9464          class initialization for it.  This can happen when the access
9465          looks like `field.ref', where `field' is a static field in an
9466          interface we implement.  */
9467       if (!flag_emit_class_files
9468           && !flag_emit_xref
9469           && TREE_CODE (where_found) == VAR_DECL
9470           && FIELD_STATIC (where_found))
9471         {
9472           build_static_field_ref (where_found);
9473           field_ref = build_class_init (DECL_CONTEXT (where_found), field_ref);
9474         }
9475     }
9476   else
9477     field_ref = decl;
9478
9479   if (field_decl)
9480     *field_decl = decl;
9481   if (field_type)
9482     *field_type = (QUAL_DECL_TYPE (decl) ?
9483                    QUAL_DECL_TYPE (decl) : TREE_TYPE (decl));
9484   return field_ref;
9485 }
9486
9487 /* If NODE is an access to f static field, strip out the class
9488    initialization part and return the field decl, otherwise, return
9489    NODE. */
9490
9491 static tree
9492 strip_out_static_field_access_decl (tree node)
9493 {
9494   if (TREE_CODE (node) == COMPOUND_EXPR)
9495     {
9496       tree op1 = TREE_OPERAND (node, 1);
9497       if (TREE_CODE (op1) == COMPOUND_EXPR)
9498          {
9499            tree call = TREE_OPERAND (op1, 0);
9500            if (TREE_CODE (call) == CALL_EXPR
9501                && TREE_CODE (TREE_OPERAND (call, 0)) == ADDR_EXPR
9502                && TREE_OPERAND (TREE_OPERAND (call, 0), 0)
9503                == soft_initclass_node)
9504              return TREE_OPERAND (op1, 1);
9505          }
9506       else if (JDECL_P (op1))
9507         return op1;
9508     }
9509   return node;
9510 }
9511
9512 /* 6.5.5.2: Qualified Expression Names */
9513
9514 static int
9515 resolve_qualified_expression_name (tree wfl, tree *found_decl,
9516                                    tree *where_found, tree *type_found)
9517 {
9518   int from_type = 0;            /* Field search initiated from a type */
9519   int from_super = 0, from_cast = 0, from_qualified_this = 0;
9520   int previous_call_static = 0;
9521   int is_static;
9522   tree decl = NULL_TREE, type = NULL_TREE, q;
9523   /* For certain for of inner class instantiation */
9524   tree saved_current, saved_this;
9525 #define RESTORE_THIS_AND_CURRENT_CLASS                          \
9526   { current_class = saved_current; current_this = saved_this;}
9527
9528   *type_found = *where_found = NULL_TREE;
9529
9530   for (q = EXPR_WFL_QUALIFICATION (wfl); q; q = TREE_CHAIN (q))
9531     {
9532       tree qual_wfl = QUAL_WFL (q);
9533       tree ret_decl;            /* for EH checking */
9534       int location;             /* for EH checking */
9535
9536       /* 15.10.1 Field Access Using a Primary */
9537       switch (TREE_CODE (qual_wfl))
9538         {
9539         case CALL_EXPR:
9540         case NEW_CLASS_EXPR:
9541           /* If the access to the function call is a non static field,
9542              build the code to access it. */
9543           if (JDECL_P (decl) && !FIELD_STATIC (decl))
9544             {
9545               decl = maybe_access_field (decl, *where_found,
9546                                          DECL_CONTEXT (decl));
9547               if (decl == error_mark_node)
9548                 return 1;
9549             }
9550
9551           /* And code for the function call */
9552           if (complete_function_arguments (qual_wfl))
9553             return 1;
9554
9555           /* We might have to setup a new current class and a new this
9556              for the search of an inner class, relative to the type of
9557              a expression resolved as `decl'. The current values are
9558              saved and restored shortly after */
9559           saved_current = current_class;
9560           saved_this = current_this;
9561           if (decl
9562               && (TREE_CODE (qual_wfl) == NEW_CLASS_EXPR
9563                   || from_qualified_this))
9564             {
9565               /* If we still have `from_qualified_this', we have the form
9566                  <T>.this.f() and we need to build <T>.this */
9567               if (from_qualified_this)
9568                 {
9569                   decl = build_access_to_thisn (current_class, type, 0);
9570                   decl = java_complete_tree (decl);
9571                   type = TREE_TYPE (TREE_TYPE (decl));
9572                 }
9573               current_class = type;
9574               current_this = decl;
9575               from_qualified_this = 0;
9576             }
9577
9578           if (from_super && TREE_CODE (qual_wfl) == CALL_EXPR)
9579             CALL_USING_SUPER (qual_wfl) = 1;
9580           location = (TREE_CODE (qual_wfl) == CALL_EXPR ?
9581                       EXPR_WFL_LINECOL (TREE_OPERAND (qual_wfl, 0)) : 0);
9582           *where_found = patch_method_invocation (qual_wfl, decl, type,
9583                                                   from_super,
9584                                                   &is_static, &ret_decl);
9585           from_super = 0;
9586           if (*where_found == error_mark_node)
9587             {
9588               RESTORE_THIS_AND_CURRENT_CLASS;
9589               return 1;
9590             }
9591           *type_found = type = QUAL_DECL_TYPE (*where_found);
9592
9593           *where_found = force_evaluation_order (*where_found);
9594
9595           /* If we're creating an inner class instance, check for that
9596              an enclosing instance is in scope */
9597           if (TREE_CODE (qual_wfl) == NEW_CLASS_EXPR
9598               && INNER_ENCLOSING_SCOPE_CHECK (type))
9599             {
9600               parse_error_context
9601                 (qual_wfl, "No enclosing instance for inner class `%s' is in scope%s",
9602                  lang_printable_name (type, 0),
9603                  (!current_this ? "" :
9604                   "; an explicit one must be provided when creating this inner class"));
9605               RESTORE_THIS_AND_CURRENT_CLASS;
9606               return 1;
9607             }
9608
9609           /* In case we had to change then to resolve a inner class
9610              instantiation using a primary qualified by a `new' */
9611           RESTORE_THIS_AND_CURRENT_CLASS;
9612
9613           if (location)
9614             {
9615               tree arguments = NULL_TREE;
9616               if (TREE_CODE (qual_wfl) == CALL_EXPR
9617                   && TREE_OPERAND (qual_wfl, 1) != NULL_TREE)
9618                 arguments = TREE_VALUE (TREE_OPERAND (qual_wfl, 1));
9619               check_thrown_exceptions (location, ret_decl, arguments);
9620             }
9621
9622           /* If the previous call was static and this one is too,
9623              build a compound expression to hold the two (because in
9624              that case, previous function calls aren't transported as
9625              forcoming function's argument. */
9626           if (previous_call_static && is_static)
9627             {
9628               decl = build (COMPOUND_EXPR, TREE_TYPE (*where_found),
9629                             decl, *where_found);
9630               TREE_SIDE_EFFECTS (decl) = 1;
9631             }
9632           else
9633             {
9634               previous_call_static = is_static;
9635               decl = *where_found;
9636             }
9637           from_type = 0;
9638           continue;
9639
9640         case NEW_ARRAY_EXPR:
9641         case NEW_ANONYMOUS_ARRAY_EXPR:
9642           *where_found = decl = java_complete_tree (qual_wfl);
9643           if (decl == error_mark_node)
9644             return 1;
9645           *type_found = type = QUAL_DECL_TYPE (decl);
9646           continue;
9647
9648         case CONVERT_EXPR:
9649           *where_found = decl = java_complete_tree (qual_wfl);
9650           if (decl == error_mark_node)
9651             return 1;
9652           *type_found = type = QUAL_DECL_TYPE (decl);
9653           from_cast = 1;
9654           continue;
9655
9656         case CONDITIONAL_EXPR:
9657         case STRING_CST:
9658         case MODIFY_EXPR:
9659           *where_found = decl = java_complete_tree (qual_wfl);
9660           if (decl == error_mark_node)
9661             return 1;
9662           *type_found = type = QUAL_DECL_TYPE (decl);
9663           continue;
9664
9665         case ARRAY_REF:
9666           /* If the access to the function call is a non static field,
9667              build the code to access it. */
9668           if (JDECL_P (decl) && !FIELD_STATIC (decl))
9669             {
9670               decl = maybe_access_field (decl, *where_found, type);
9671               if (decl == error_mark_node)
9672                 return 1;
9673             }
9674           /* And code for the array reference expression */
9675           decl = java_complete_tree (qual_wfl);
9676           if (decl == error_mark_node)
9677             return 1;
9678           type = QUAL_DECL_TYPE (decl);
9679           continue;
9680
9681         case PLUS_EXPR:
9682           if ((decl = java_complete_tree (qual_wfl)) == error_mark_node)
9683             return 1;
9684           if ((type = patch_string (decl)))
9685             decl = type;
9686           *where_found = QUAL_RESOLUTION (q) = decl;
9687           *type_found = type = TREE_TYPE (decl);
9688           break;
9689
9690         case CLASS_LITERAL:
9691           if ((decl = java_complete_tree (qual_wfl)) == error_mark_node)
9692             return 1;
9693           *where_found = QUAL_RESOLUTION (q) = decl;
9694           *type_found = type = TREE_TYPE (decl);
9695           break;
9696
9697         default:
9698           /* Fix for -Wall Just go to the next statement. Don't
9699              continue */
9700           break;
9701         }
9702
9703       /* If we fall here, we weren't processing a (static) function call. */
9704       previous_call_static = 0;
9705
9706       /* It can be the keyword THIS */
9707       if (TREE_CODE (qual_wfl) == EXPR_WITH_FILE_LOCATION
9708           && EXPR_WFL_NODE (qual_wfl) == this_identifier_node)
9709         {
9710           if (!current_this)
9711             {
9712               parse_error_context
9713                 (wfl, "Keyword `this' used outside allowed context");
9714               return 1;
9715             }
9716           if (ctxp->explicit_constructor_p
9717               && type == current_class)
9718             {
9719               parse_error_context (wfl, "Can't reference `this' before the superclass constructor has been called");
9720               return 1;
9721             }
9722           /* We have to generate code for intermediate access */
9723           if (!from_type || TREE_TYPE (TREE_TYPE (current_this)) == type)
9724             {
9725               *where_found = decl = current_this;
9726               *type_found = type = QUAL_DECL_TYPE (decl);
9727             }
9728           /* We're trying to access the this from somewhere else. Make sure
9729              it's allowed before doing so. */
9730           else
9731             {
9732               if (!enclosing_context_p (type, current_class))
9733                 {
9734                   char *p  = xstrdup (lang_printable_name (type, 0));
9735                   parse_error_context (qual_wfl, "Can't use variable `%s.this': type `%s' isn't an outer type of type `%s'",
9736                                        p, p,
9737                                        lang_printable_name (current_class, 0));
9738                   free (p);
9739                   return 1;
9740                 }
9741               from_qualified_this = 1;
9742               /* If there's nothing else after that, we need to
9743                  produce something now, otherwise, the section of the
9744                  code that needs to produce <T>.this will generate
9745                  what is necessary. */
9746               if (!TREE_CHAIN (q))
9747                 {
9748                   decl = build_access_to_thisn (current_class, type, 0);
9749                   *where_found = decl = java_complete_tree (decl);
9750                   *type_found = type = TREE_TYPE (decl);
9751                 }
9752             }
9753
9754           from_type = 0;
9755           continue;
9756         }
9757
9758       /* 15.10.2 Accessing Superclass Members using SUPER */
9759       if (TREE_CODE (qual_wfl) == EXPR_WITH_FILE_LOCATION
9760           && EXPR_WFL_NODE (qual_wfl) == super_identifier_node)
9761         {
9762           tree node;
9763           /* Check on the restricted use of SUPER */
9764           if (METHOD_STATIC (current_function_decl)
9765               || current_class == object_type_node)
9766             {
9767               parse_error_context
9768                 (wfl, "Keyword `super' used outside allowed context");
9769               return 1;
9770             }
9771           /* Otherwise, treat SUPER as (SUPER_CLASS)THIS */
9772           node = build_cast (EXPR_WFL_LINECOL (qual_wfl),
9773                              CLASSTYPE_SUPER (current_class),
9774                              build_this (EXPR_WFL_LINECOL (qual_wfl)));
9775           *where_found = decl = java_complete_tree (node);
9776           if (decl == error_mark_node)
9777             return 1;
9778           *type_found = type = QUAL_DECL_TYPE (decl);
9779           from_super = from_type = 1;
9780           continue;
9781         }
9782
9783       /* 15.13.1: Can't search for field name in packages, so we
9784          assume a variable/class name was meant. */
9785       if (RESOLVE_PACKAGE_NAME_P (qual_wfl))
9786         {
9787           tree name;
9788           if ((decl = resolve_package (wfl, &q, &name)))
9789             {
9790               tree list;
9791               *where_found = decl;
9792
9793               /* We want to be absolutely sure that the class is laid
9794                  out. We're going to search something inside it. */
9795               *type_found = type = TREE_TYPE (decl);
9796               layout_class (type);
9797               from_type = 1;
9798
9799               /* Fix them all the way down, if any are left. */
9800               if (q)
9801                 {
9802                   list = TREE_CHAIN (q);
9803                   while (list)
9804                     {
9805                       RESOLVE_EXPRESSION_NAME_P (QUAL_WFL (list)) = 1;
9806                       RESOLVE_PACKAGE_NAME_P (QUAL_WFL (list)) = 0;
9807                       list = TREE_CHAIN (list);
9808                     }
9809                 }
9810             }
9811           else
9812             {
9813               if (from_super || from_cast)
9814                 parse_error_context
9815                   ((from_cast ? qual_wfl : wfl),
9816                    "No variable `%s' defined in class `%s'",
9817                    IDENTIFIER_POINTER (EXPR_WFL_NODE (qual_wfl)),
9818                    lang_printable_name (type, 0));
9819               else
9820                 parse_error_context
9821                   (qual_wfl, "Undefined variable or class name: `%s'",
9822                    IDENTIFIER_POINTER (name));
9823               return 1;
9824             }
9825         }
9826
9827       /* We have a type name. It's been already resolved when the
9828          expression was qualified. */
9829       else if (RESOLVE_TYPE_NAME_P (qual_wfl) && QUAL_RESOLUTION (q))
9830         {
9831           decl = QUAL_RESOLUTION (q);
9832
9833           /* Sneak preview. If next we see a `new', we're facing a
9834              qualification with resulted in a type being selected
9835              instead of a field.  Report the error */
9836           if(TREE_CHAIN (q)
9837              && TREE_CODE (TREE_PURPOSE (TREE_CHAIN (q))) == NEW_CLASS_EXPR)
9838             {
9839               parse_error_context (qual_wfl, "Undefined variable `%s'",
9840                                    IDENTIFIER_POINTER (EXPR_WFL_NODE (wfl)));
9841               return 1;
9842             }
9843
9844           if (not_accessible_p (TREE_TYPE (decl), decl, type, 0))
9845             return not_accessible_field_error (qual_wfl, decl);
9846           check_deprecation (qual_wfl, decl);
9847
9848           type = TREE_TYPE (decl);
9849           from_type = 1;
9850         }
9851       /* We resolve an expression name */
9852       else
9853         {
9854           tree field_decl = NULL_TREE;
9855
9856           /* If there exists an early resolution, use it. That occurs
9857              only once and we know that there are more things to
9858              come. Don't do that when processing something after SUPER
9859              (we need more thing to be put in place below */
9860           if (!from_super && QUAL_RESOLUTION (q))
9861             {
9862               decl = QUAL_RESOLUTION (q);
9863               if (!type)
9864                 {
9865                   if (TREE_CODE (decl) == FIELD_DECL && !FIELD_STATIC (decl))
9866                     {
9867                       if (current_this)
9868                         *where_found = current_this;
9869                       else
9870                         {
9871                           static_ref_err (qual_wfl, DECL_NAME (decl),
9872                                           current_class);
9873                           return 1;
9874                         }
9875                       if (outer_field_access_p (current_class, decl))
9876                         decl = build_outer_field_access (qual_wfl, decl);
9877                     }
9878                   else
9879                     {
9880                       *where_found = TREE_TYPE (decl);
9881                       if (TREE_CODE (*where_found) == POINTER_TYPE)
9882                         *where_found = TREE_TYPE (*where_found);
9883                     }
9884                 }
9885             }
9886
9887           /* Report and error if we're using a numerical literal as a
9888              qualifier. It can only be an INTEGER_CST. */
9889           else if (TREE_CODE (qual_wfl) == INTEGER_CST)
9890             {
9891               parse_error_context
9892                 (wfl, "Can't use type `%s' as a qualifier",
9893                  lang_printable_name (TREE_TYPE (qual_wfl), 0));
9894               return 1;
9895             }
9896
9897           /* We have to search for a field, knowing the type of its
9898              container. The flag FROM_TYPE indicates that we resolved
9899              the last member of the expression as a type name, which
9900              means that for the resolution of this field, we'll look
9901              for other errors than if it was resolved as a member of
9902              an other field. */
9903           else
9904             {
9905               int is_static;
9906               tree field_decl_type; /* For layout */
9907
9908               if (!from_type && !JREFERENCE_TYPE_P (type))
9909                 {
9910                   parse_error_context
9911                     (qual_wfl, "Attempt to reference field `%s' in `%s %s'",
9912                      IDENTIFIER_POINTER (EXPR_WFL_NODE (qual_wfl)),
9913                      lang_printable_name (type, 0),
9914                      IDENTIFIER_POINTER (DECL_NAME (decl)));
9915                   return 1;
9916                 }
9917
9918               field_decl = lookup_field_wrapper (type,
9919                                                  EXPR_WFL_NODE (qual_wfl));
9920
9921               /* Maybe what we're trying to access to is an inner
9922                  class, only if decl is a TYPE_DECL. */
9923               if (!field_decl && TREE_CODE (decl) == TYPE_DECL)
9924                 {
9925                   tree ptr, inner_decl;
9926
9927                   BUILD_PTR_FROM_NAME (ptr, EXPR_WFL_NODE (qual_wfl));
9928                   inner_decl = resolve_class (decl, ptr, NULL_TREE, qual_wfl);
9929                   if (inner_decl)
9930                     {
9931                       check_inner_class_access (inner_decl, decl, qual_wfl);
9932                       type = TREE_TYPE (inner_decl);
9933                       decl = inner_decl;
9934                       from_type = 1;
9935                       continue;
9936                     }
9937                 }
9938
9939               if (field_decl == NULL_TREE)
9940                 {
9941                   parse_error_context
9942                     (qual_wfl, "No variable `%s' defined in type `%s'",
9943                      IDENTIFIER_POINTER (EXPR_WFL_NODE (qual_wfl)),
9944                      GET_TYPE_NAME (type));
9945                   return 1;
9946                 }
9947               if (field_decl == error_mark_node)
9948                 return 1;
9949
9950               /* Layout the type of field_decl, since we may need
9951                  it. Don't do primitive types or loaded classes. The
9952                  situation of non primitive arrays may not handled
9953                  properly here. FIXME */
9954               if (TREE_CODE (TREE_TYPE (field_decl)) == POINTER_TYPE)
9955                 field_decl_type = TREE_TYPE (TREE_TYPE (field_decl));
9956               else
9957                 field_decl_type = TREE_TYPE (field_decl);
9958               if (!JPRIMITIVE_TYPE_P (field_decl_type)
9959                   && !CLASS_LOADED_P (field_decl_type)
9960                   && !TYPE_ARRAY_P (field_decl_type))
9961                 resolve_and_layout (field_decl_type, NULL_TREE);
9962
9963               /* Check on accessibility here */
9964               if (not_accessible_p (current_class, field_decl,
9965                                     DECL_CONTEXT (field_decl), from_super))
9966                 return not_accessible_field_error (qual_wfl,field_decl);    
9967               check_deprecation (qual_wfl, field_decl);
9968
9969               /* There are things to check when fields are accessed
9970                  from type. There are no restrictions on a static
9971                  declaration of the field when it is accessed from an
9972                  interface */
9973               is_static = FIELD_STATIC (field_decl);
9974               if (!from_super && from_type
9975                   && !TYPE_INTERFACE_P (type)
9976                   && !is_static
9977                   && (current_function_decl
9978                       && METHOD_STATIC (current_function_decl)))
9979                 {
9980                   static_ref_err (qual_wfl, EXPR_WFL_NODE (qual_wfl), type);
9981                   return 1;
9982                 }
9983               from_cast = from_super = 0;
9984
9985               /* It's an access from a type but it isn't static, we
9986                  make it relative to `this'. */
9987               if (!is_static && from_type)
9988                 decl = current_this;
9989
9990               /* If we need to generate something to get a proper
9991                  handle on what this field is accessed from, do it
9992                  now. */
9993               if (!is_static)
9994                 {
9995                   decl = maybe_access_field (decl, *where_found, *type_found);
9996                   if (decl == error_mark_node)
9997                     return 1;
9998                 }
9999
10000               /* We want to keep the location were found it, and the type
10001                  we found. */
10002               *where_found = decl;
10003               *type_found = type;
10004
10005               /* Generate the correct expression for field access from
10006                  qualified this */
10007               if (from_qualified_this)
10008                 {
10009                   field_decl = build_outer_field_access (qual_wfl, field_decl);
10010                   from_qualified_this = 0;
10011                 }
10012
10013               /* This is the decl found and eventually the next one to
10014                  search from */
10015               decl = field_decl;
10016             }
10017           from_type = 0;
10018           type = QUAL_DECL_TYPE (decl);
10019
10020           /* Sneak preview. If decl is qualified by a `new', report
10021              the error here to be accurate on the peculiar construct */
10022           if (TREE_CHAIN (q)
10023               && TREE_CODE (TREE_PURPOSE (TREE_CHAIN (q))) == NEW_CLASS_EXPR
10024               && !JREFERENCE_TYPE_P (type))
10025             {
10026               parse_error_context (qual_wfl, "Attempt to reference field `new' in a `%s'",
10027                                    lang_printable_name (type, 0));
10028               return 1;
10029             }
10030         }
10031       /* `q' might have changed due to a after package resolution
10032          re-qualification */
10033       if (!q)
10034         break;
10035     }
10036   *found_decl = decl;
10037   return 0;
10038 }
10039
10040 /* 6.6 Qualified name and access control. Returns 1 if MEMBER (a decl)
10041    can't be accessed from REFERENCE (a record type). If MEMBER
10042    features a protected access, we then use WHERE which, if non null,
10043    holds the type of MEMBER's access that is checked against
10044    6.6.2.1. This function should be used when decl is a field or a
10045    method.  */
10046
10047 static int
10048 not_accessible_p (tree reference, tree member, tree where, int from_super)
10049 {
10050   int access_flag = get_access_flags_from_decl (member);
10051
10052   /* Inner classes are processed by check_inner_class_access */
10053   if (INNER_CLASS_TYPE_P (reference))
10054     return 0;
10055
10056   /* Access always granted for members declared public */
10057   if (access_flag & ACC_PUBLIC)
10058     return 0;
10059
10060   /* Check access on protected members */
10061   if (access_flag & ACC_PROTECTED)
10062     {
10063       /* Access granted if it occurs from within the package
10064          containing the class in which the protected member is
10065          declared */
10066       if (class_in_current_package (DECL_CONTEXT (member)))
10067         return 0;
10068
10069       /* If accessed with the form `super.member', then access is granted */
10070       if (from_super)
10071         return 0;
10072
10073       /* If where is active, access was made through a
10074          qualifier. Access is granted if the type of the qualifier is
10075          or is a sublass of the type the access made from (6.6.2.1.)  */
10076       if (where && !inherits_from_p (reference, where))
10077         return 1;
10078
10079       /* Otherwise, access is granted if occurring from the class where
10080          member is declared or a subclass of it. Find the right
10081          context to perform the check */
10082       if (PURE_INNER_CLASS_TYPE_P (reference))
10083         {
10084           while (INNER_CLASS_TYPE_P (reference))
10085             {
10086               if (inherits_from_p (reference, DECL_CONTEXT (member)))
10087                 return 0;
10088               reference = TREE_TYPE (DECL_CONTEXT (TYPE_NAME (reference)));
10089             }
10090         }
10091       if (inherits_from_p (reference, DECL_CONTEXT (member)))
10092         return 0;
10093       return 1;
10094     }
10095
10096   /* Check access on private members. Access is granted only if it
10097      occurs from within the class in which it is declared -- that does
10098      it for innerclasses too. */
10099   if (access_flag & ACC_PRIVATE)
10100     {
10101       if (reference == DECL_CONTEXT (member))
10102         return 0;
10103       if (enclosing_context_p (reference, DECL_CONTEXT (member)))
10104         return 0;
10105       return 1;
10106     }
10107
10108   /* Default access are permitted only when occurring within the
10109      package in which the type (REFERENCE) is declared. In other words,
10110      REFERENCE is defined in the current package */
10111   if (ctxp->package)
10112     return !class_in_current_package (reference);
10113
10114   /* Otherwise, access is granted */
10115   return 0;
10116 }
10117
10118 /* Test deprecated decl access.  */
10119 static void
10120 check_deprecation (tree wfl, tree decl)
10121 {
10122   const char *file;
10123   tree elt;
10124
10125   if (! flag_deprecated)
10126     return;
10127
10128   /* We want to look at the element type of arrays here, so we strip
10129      all surrounding array types.  */
10130   if (TYPE_ARRAY_P (TREE_TYPE (decl)))
10131     {
10132       elt = TREE_TYPE (decl);
10133       while (TYPE_ARRAY_P (elt))
10134         elt = TYPE_ARRAY_ELEMENT (elt);
10135       /* We'll end up with a pointer type, so we use TREE_TYPE to go
10136          to the record.  */
10137       decl = TYPE_NAME (TREE_TYPE (elt));
10138     }
10139   file = DECL_SOURCE_FILE (decl);
10140
10141   /* Complain if the field is deprecated and the file it was defined
10142      in isn't compiled at the same time the file which contains its
10143      use is */
10144   if (DECL_DEPRECATED (decl)
10145       && !IS_A_COMMAND_LINE_FILENAME_P (get_identifier (file)))
10146     {
10147       const char *the;
10148       switch (TREE_CODE (decl))
10149         {
10150         case FUNCTION_DECL:
10151           the = "method";
10152           break;
10153         case FIELD_DECL:
10154         case VAR_DECL:
10155           the = "field";
10156           break;
10157         case TYPE_DECL:
10158           parse_warning_context (wfl, "The class `%s' has been deprecated",
10159                                  IDENTIFIER_POINTER (DECL_NAME (decl)));
10160           return;
10161         default:
10162           abort ();
10163         }
10164       /* Don't issue a message if the context as been deprecated as a
10165          whole. */
10166       if (! CLASS_DEPRECATED (TYPE_NAME (DECL_CONTEXT (decl))))
10167         parse_warning_context
10168           (wfl, "The %s `%s' in class `%s' has been deprecated",
10169            the, lang_printable_name (decl, 0),
10170            IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (DECL_CONTEXT (decl)))));
10171     }
10172 }
10173
10174 /* Returns 1 if class was declared in the current package, 0 otherwise */
10175
10176 static GTY(()) tree cicp_cache;
10177 static int
10178 class_in_current_package (tree class)
10179 {
10180   int qualified_flag;
10181   tree left;
10182
10183   if (cicp_cache == class)
10184     return 1;
10185
10186   qualified_flag = QUALIFIED_P (DECL_NAME (TYPE_NAME (class)));
10187
10188   /* If the current package is empty and the name of CLASS is
10189      qualified, class isn't in the current package.  If there is a
10190      current package and the name of the CLASS is not qualified, class
10191      isn't in the current package */
10192   if ((!ctxp->package && qualified_flag) || (ctxp->package && !qualified_flag))
10193     return 0;
10194
10195   /* If there is not package and the name of CLASS isn't qualified,
10196      they belong to the same unnamed package */
10197   if (!ctxp->package && !qualified_flag)
10198     return 1;
10199
10200   /* Compare the left part of the name of CLASS with the package name */
10201   breakdown_qualified (&left, NULL, DECL_NAME (TYPE_NAME (class)));
10202   if (ctxp->package == left)
10203     {
10204       cicp_cache = class;
10205       return 1;
10206     }
10207   return 0;
10208 }
10209
10210 /* This function may generate code to access DECL from WHERE. This is
10211    done only if certain conditions meet.  */
10212
10213 static tree
10214 maybe_access_field (tree decl, tree where, tree type)
10215 {
10216   if (TREE_CODE (decl) == FIELD_DECL && decl != current_this
10217       && !FIELD_STATIC (decl))
10218     decl = build_field_ref (where ? where : current_this,
10219                             (type ? type : DECL_CONTEXT (decl)),
10220                             DECL_NAME (decl));
10221   return decl;
10222 }
10223
10224 /* Build a method invocation, by patching PATCH. If non NULL
10225    and according to the situation, PRIMARY and WHERE may be
10226    used. IS_STATIC is set to 1 if the invoked function is static. */
10227
10228 static tree
10229 patch_method_invocation (tree patch, tree primary, tree where, int from_super,
10230                          int *is_static, tree *ret_decl)
10231 {
10232   tree wfl = TREE_OPERAND (patch, 0);
10233   tree args = TREE_OPERAND (patch, 1);
10234   tree name = EXPR_WFL_NODE (wfl);
10235   tree list;
10236   int is_static_flag = 0;
10237   int is_super_init = 0;
10238   tree this_arg = NULL_TREE;
10239   int is_array_clone_call = 0;
10240
10241   /* Should be overridden if everything goes well. Otherwise, if
10242      something fails, it should keep this value. It stop the
10243      evaluation of a bogus assignment. See java_complete_tree,
10244      MODIFY_EXPR: for the reasons why we sometimes want to keep on
10245      evaluating an assignment */
10246   TREE_TYPE (patch) = error_mark_node;
10247
10248   /* Since lookup functions are messing with line numbers, save the
10249      context now.  */
10250   java_parser_context_save_global ();
10251
10252   /* 15.11.1: Compile-Time Step 1: Determine Class or Interface to Search */
10253
10254   /* Resolution of qualified name, excluding constructors */
10255   if (QUALIFIED_P (name) && !CALL_CONSTRUCTOR_P (patch))
10256     {
10257       tree identifier, identifier_wfl, type, resolved;
10258       /* Extract the last IDENTIFIER of the qualified
10259          expression. This is a wfl and we will use it's location
10260          data during error report. */
10261       identifier_wfl = cut_identifier_in_qualified (wfl);
10262       identifier = EXPR_WFL_NODE (identifier_wfl);
10263
10264       /* Given the context, IDENTIFIER is syntactically qualified
10265          as a MethodName. We need to qualify what's before */
10266       qualify_ambiguous_name (wfl);
10267       resolved = resolve_field_access (wfl, NULL, NULL);
10268
10269       if (TREE_CODE (resolved) == VAR_DECL && FIELD_STATIC (resolved)
10270          && FIELD_FINAL (resolved)
10271          && !inherits_from_p (DECL_CONTEXT (resolved), current_class)
10272          && !flag_emit_class_files && !flag_emit_xref)
10273        resolved = build_class_init (DECL_CONTEXT (resolved), resolved);
10274
10275       if (resolved == error_mark_node)
10276         PATCH_METHOD_RETURN_ERROR ();
10277
10278       type = GET_SKIP_TYPE (resolved);
10279       resolve_and_layout (type, NULL_TREE);
10280
10281       if (JPRIMITIVE_TYPE_P (type))
10282         {
10283           parse_error_context
10284             (identifier_wfl,
10285              "Can't invoke a method on primitive type `%s'",
10286              IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (type))));
10287           PATCH_METHOD_RETURN_ERROR ();
10288         }
10289
10290       list = lookup_method_invoke (0, identifier_wfl, type, identifier, args);
10291       args = nreverse (args);
10292
10293       /* We're resolving a call from a type */
10294       if (TREE_CODE (resolved) == TYPE_DECL)
10295         {
10296           if (CLASS_INTERFACE (resolved))
10297             {
10298               parse_error_context
10299                 (identifier_wfl,
10300                 "Can't make static reference to method `%s' in interface `%s'",
10301                  IDENTIFIER_POINTER (identifier),
10302                  IDENTIFIER_POINTER (name));
10303               PATCH_METHOD_RETURN_ERROR ();
10304             }
10305           if (list && !METHOD_STATIC (list))
10306             {
10307               char *fct_name = xstrdup (lang_printable_name (list, 0));
10308               parse_error_context
10309                 (identifier_wfl,
10310                  "Can't make static reference to method `%s %s' in class `%s'",
10311                  lang_printable_name (TREE_TYPE (TREE_TYPE (list)), 0),
10312                  fct_name, IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (type))));
10313               free (fct_name);
10314               PATCH_METHOD_RETURN_ERROR ();
10315             }
10316         }
10317       else
10318         this_arg = primary = resolved;
10319
10320       if (TYPE_ARRAY_P (type) && identifier == get_identifier ("clone"))
10321         is_array_clone_call = 1;
10322
10323       /* IDENTIFIER_WFL will be used to report any problem further */
10324       wfl = identifier_wfl;
10325     }
10326   /* Resolution of simple names, names generated after a primary: or
10327      constructors */
10328   else
10329     {
10330       tree class_to_search = NULL_TREE;
10331       int lc;                   /* Looking for Constructor */
10332
10333       /* We search constructor in their target class */
10334       if (CALL_CONSTRUCTOR_P (patch))
10335         {
10336           if (TREE_CODE (patch) == NEW_CLASS_EXPR)
10337             class_to_search = EXPR_WFL_NODE (wfl);
10338           else if (EXPR_WFL_NODE (TREE_OPERAND (patch, 0)) ==
10339                    this_identifier_node)
10340             class_to_search = NULL_TREE;
10341           else if (EXPR_WFL_NODE (TREE_OPERAND (patch, 0)) ==
10342                    super_identifier_node)
10343             {
10344               is_super_init = 1;
10345               if (CLASSTYPE_SUPER (current_class))
10346                 class_to_search =
10347                   DECL_NAME (TYPE_NAME (CLASSTYPE_SUPER (current_class)));
10348               else
10349                 {
10350                   parse_error_context (wfl, "Can't invoke super constructor on java.lang.Object");
10351                   PATCH_METHOD_RETURN_ERROR ();
10352                 }
10353             }
10354
10355           /* Class to search is NULL if we're searching the current one */
10356           if (class_to_search)
10357             {
10358               class_to_search = resolve_and_layout (class_to_search, wfl);
10359
10360               if (!class_to_search)
10361                 {
10362                   parse_error_context
10363                     (wfl, "Class `%s' not found in type declaration",
10364                      IDENTIFIER_POINTER (EXPR_WFL_NODE (wfl)));
10365                   PATCH_METHOD_RETURN_ERROR ();
10366                 }
10367
10368               /* Can't instantiate an abstract class, but we can
10369                  invoke it's constructor. It's use within the `new'
10370                  context is denied here. */
10371               if (CLASS_ABSTRACT (class_to_search)
10372                   && TREE_CODE (patch) == NEW_CLASS_EXPR)
10373                 {
10374                   parse_error_context
10375                     (wfl, "Class `%s' is an abstract class. It can't be instantiated",
10376                      IDENTIFIER_POINTER (EXPR_WFL_NODE (wfl)));
10377                   PATCH_METHOD_RETURN_ERROR ();
10378                 }
10379
10380               class_to_search = TREE_TYPE (class_to_search);
10381             }
10382           else
10383             class_to_search = current_class;
10384           lc = 1;
10385         }
10386       /* This is a regular search in the local class, unless an
10387          alternate class is specified. */
10388       else
10389         {
10390           if (where != NULL_TREE)
10391             class_to_search = where;
10392           else if (QUALIFIED_P (name))
10393             class_to_search = current_class;
10394           else
10395             {
10396               class_to_search = current_class;
10397
10398               for (;;)
10399                 {
10400                   if (has_method (class_to_search, name))
10401                     break;
10402                   if (! INNER_CLASS_TYPE_P (class_to_search))
10403                     {
10404                       parse_error_context (wfl,
10405                                            "No method named `%s' in scope",
10406                                            IDENTIFIER_POINTER (name));
10407                       PATCH_METHOD_RETURN_ERROR ();
10408                     }
10409                   class_to_search
10410                     = TREE_TYPE (DECL_CONTEXT (TYPE_NAME (class_to_search)));
10411                 }
10412             }
10413           lc = 0;
10414         }
10415
10416       /* NAME is a simple identifier or comes from a primary. Search
10417          in the class whose declaration contain the method being
10418          invoked. */
10419       resolve_and_layout (class_to_search, NULL_TREE);
10420
10421       list = lookup_method_invoke (lc, wfl, class_to_search, name, args);
10422       /* Don't continue if no method were found, as the next statement
10423          can't be executed then. */
10424       if (!list)
10425         PATCH_METHOD_RETURN_ERROR ();
10426
10427       if (TYPE_ARRAY_P (class_to_search)
10428           && DECL_NAME (list) == get_identifier ("clone"))
10429         is_array_clone_call = 1;
10430
10431       /* Check for static reference if non static methods */
10432       if (check_for_static_method_reference (wfl, patch, list,
10433                                              class_to_search, primary))
10434         PATCH_METHOD_RETURN_ERROR ();
10435
10436       /* Check for inner classes creation from illegal contexts */
10437       if (lc && (INNER_CLASS_TYPE_P (class_to_search)
10438                  && !CLASS_STATIC (TYPE_NAME (class_to_search)))
10439           && INNER_ENCLOSING_SCOPE_CHECK (class_to_search)
10440           && !DECL_INIT_P (current_function_decl))
10441         {
10442           parse_error_context
10443             (wfl, "No enclosing instance for inner class `%s' is in scope%s",
10444              lang_printable_name (class_to_search, 0),
10445              (!current_this ? "" :
10446               "; an explicit one must be provided when creating this inner class"));
10447           PATCH_METHOD_RETURN_ERROR ();
10448         }
10449
10450       /* Non static methods are called with the current object extra
10451          argument. If patch a `new TYPE()', the argument is the value
10452          returned by the object allocator. If method is resolved as a
10453          primary, use the primary otherwise use the current THIS. */
10454       args = nreverse (args);
10455       if (TREE_CODE (patch) != NEW_CLASS_EXPR)
10456         {
10457           this_arg = primary ? primary : current_this;
10458
10459           /* If we're using an access method, things are different.
10460              There are two family of cases:
10461
10462              1) We're not generating bytecodes:
10463
10464              - LIST is non static. It's invocation is transformed from
10465                x(a1,...,an) into this$<n>.x(a1,....an).
10466              - LIST is static. It's invocation is transformed from
10467                x(a1,...,an) into TYPE_OF(this$<n>).x(a1,....an)
10468
10469              2) We're generating bytecodes:
10470
10471              - LIST is non static. It's invocation is transformed from
10472                x(a1,....,an) into access$<n>(this$<n>,a1,...,an).
10473              - LIST is static. It's invocation is transformed from
10474                x(a1,....,an) into TYPE_OF(this$<n>).x(a1,....an).
10475
10476              Of course, this$<n> can be arbitrarily complex, ranging from
10477              this$0 (the immediate outer context) to
10478              access$0(access$0(...(this$0))).
10479
10480              maybe_use_access_method returns a nonzero value if the
10481              this_arg has to be moved into the (then generated) stub
10482              argument list. In the meantime, the selected function
10483              might have be replaced by a generated stub. */
10484           if (!primary &&
10485               maybe_use_access_method (is_super_init, &list, &this_arg))
10486             {
10487               args = tree_cons (NULL_TREE, this_arg, args);
10488               this_arg = NULL_TREE; /* So it doesn't get chained twice */
10489             }
10490         }
10491     }
10492
10493   /* Merge point of all resolution schemes. If we have nothing, this
10494      is an error, already signaled */
10495   if (!list)
10496     PATCH_METHOD_RETURN_ERROR ();
10497
10498   /* Check accessibility, position the is_static flag, build and
10499      return the call */
10500   if (not_accessible_p (DECL_CONTEXT (current_function_decl), list,
10501                         (primary ? TREE_TYPE (TREE_TYPE (primary)) :
10502                          NULL_TREE), from_super)
10503       /* Calls to clone() on array types are permitted as a special-case. */
10504       && !is_array_clone_call)
10505     {
10506       const char *const fct_name = IDENTIFIER_POINTER (DECL_NAME (list));
10507       const char *const access =
10508         java_accstring_lookup (get_access_flags_from_decl (list));
10509       const char *const klass =
10510         IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (DECL_CONTEXT (list))));
10511       const char *const refklass =
10512         IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (current_class)));
10513       const char *const what = (DECL_CONSTRUCTOR_P (list)
10514                                 ? "constructor" : "method");
10515       /* FIXME: WFL yields the wrong message here but I don't know
10516          what else to use.  */
10517       parse_error_context (wfl,
10518                            "Can't access %s %s `%s.%s' from `%s'",
10519                            access, what, klass, fct_name, refklass);
10520       PATCH_METHOD_RETURN_ERROR ();
10521     }
10522
10523   /* Deprecation check: check whether the method being invoked or the
10524      instance-being-created's type are deprecated.  */
10525   if (TREE_CODE (patch) == NEW_CLASS_EXPR)
10526     check_deprecation (wfl, TYPE_NAME (DECL_CONTEXT (list)));
10527   check_deprecation (wfl, list);
10528
10529   /* If invoking a innerclass constructor, there are hidden parameters
10530      to pass */
10531   if (TREE_CODE (patch) == NEW_CLASS_EXPR
10532       && PURE_INNER_CLASS_TYPE_P (DECL_CONTEXT (list)))
10533     {
10534       /* And make sure we add the accessed local variables to be saved
10535          in field aliases. */
10536       args = build_alias_initializer_parameter_list
10537         (AIPL_FUNCTION_CTOR_INVOCATION, DECL_CONTEXT (list), args, NULL);
10538
10539       /* Secretly pass the current_this/primary as a second argument */
10540       if (primary || current_this)
10541         {
10542           tree extra_arg;
10543           tree this_type = (current_this ?
10544                             TREE_TYPE (TREE_TYPE (current_this)) : NULL_TREE);
10545           /* Method's (list) enclosing context */
10546           tree mec = DECL_CONTEXT (TYPE_NAME (DECL_CONTEXT (list)));
10547           /* If we have a primary, use it. */
10548           if (primary)
10549             extra_arg = primary;
10550           /* The current `this' is an inner class but isn't a direct
10551              enclosing context for the inner class we're trying to
10552              create. Build an access to the proper enclosing context
10553              and use it. */
10554           else if (current_this && PURE_INNER_CLASS_TYPE_P (this_type)
10555                    && this_type != TREE_TYPE (mec))
10556             {
10557
10558               extra_arg = build_access_to_thisn (current_class,
10559                                                  TREE_TYPE (mec), 0);
10560               extra_arg = java_complete_tree (extra_arg);
10561             }
10562           /* Otherwise, just use the current `this' as an enclosing
10563              context. */
10564           else
10565             extra_arg = current_this;
10566           args = tree_cons (NULL_TREE, extra_arg, args);
10567         }
10568       else
10569         args = tree_cons (NULL_TREE, integer_zero_node, args);
10570     }
10571
10572   /* This handles the situation where a constructor invocation needs
10573      to have an enclosing context passed as a second parameter (the
10574      constructor is one of an inner class). */
10575   if ((is_super_init ||
10576        (TREE_CODE (patch) == CALL_EXPR && name == this_identifier_node))
10577       && PURE_INNER_CLASS_TYPE_P (DECL_CONTEXT (list)))
10578     {
10579       tree dest = TYPE_NAME (DECL_CONTEXT (list));
10580       tree extra_arg =
10581         build_access_to_thisn (current_class, DECL_CONTEXT (dest), 0);
10582       extra_arg = java_complete_tree (extra_arg);
10583       args = tree_cons (NULL_TREE, extra_arg, args);
10584     }
10585
10586   is_static_flag = METHOD_STATIC (list);
10587   if (! is_static_flag && this_arg != NULL_TREE)
10588     args = tree_cons (NULL_TREE, this_arg, args);
10589
10590   /* In the context of an explicit constructor invocation, we can't
10591      invoke any method relying on `this'. Exceptions are: we're
10592      invoking a static function, primary exists and is not the current
10593      this, we're creating a new object. */
10594   if (ctxp->explicit_constructor_p
10595       && !is_static_flag
10596       && (!primary || primary == current_this)
10597       && (TREE_CODE (patch) != NEW_CLASS_EXPR))
10598     {
10599       parse_error_context (wfl, "Can't reference `this' before the superclass constructor has been called");
10600       PATCH_METHOD_RETURN_ERROR ();
10601     }
10602   java_parser_context_restore_global ();
10603   if (is_static)
10604     *is_static = is_static_flag;
10605   /* Sometimes, we want the decl of the selected method. Such as for
10606      EH checking */
10607   if (ret_decl)
10608     *ret_decl = list;
10609   patch = patch_invoke (patch, list, args);
10610
10611   /* Now is a good time to insert the call to finit$ */
10612   if (is_super_init && CLASS_HAS_FINIT_P (current_class))
10613     {
10614       tree finit_parms, finit_call;
10615
10616       /* Prepare to pass hidden parameters to finit$, if any. */
10617       finit_parms = build_alias_initializer_parameter_list
10618         (AIPL_FUNCTION_FINIT_INVOCATION, current_class, NULL_TREE, NULL);
10619
10620       finit_call =
10621         build_method_invocation (build_wfl_node (finit_identifier_node),
10622                                  finit_parms);
10623
10624       /* Generate the code used to initialize fields declared with an
10625          initialization statement and build a compound statement along
10626          with the super constructor invocation. */
10627       CAN_COMPLETE_NORMALLY (patch) = 1;
10628       patch = build (COMPOUND_EXPR, void_type_node, patch,
10629                      java_complete_tree (finit_call));
10630     }
10631   return patch;
10632 }
10633
10634 /* Check that we're not trying to do a static reference to a method in
10635    non static method. Return 1 if it's the case, 0 otherwise. */
10636
10637 static int
10638 check_for_static_method_reference (tree wfl, tree node, tree method,
10639                                    tree where, tree primary)
10640 {
10641   if (METHOD_STATIC (current_function_decl)
10642       && !METHOD_STATIC (method) && !primary && !CALL_CONSTRUCTOR_P (node))
10643     {
10644       char *fct_name = xstrdup (lang_printable_name (method, 0));
10645       parse_error_context
10646         (wfl, "Can't make static reference to method `%s %s' in class `%s'",
10647          lang_printable_name (TREE_TYPE (TREE_TYPE (method)), 0), fct_name,
10648          IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (where))));
10649       free (fct_name);
10650       return 1;
10651     }
10652   return 0;
10653 }
10654
10655 /* Fix the invocation of *MDECL if necessary in the case of a
10656    invocation from an inner class. *THIS_ARG might be modified
10657    appropriately and an alternative access to *MDECL might be
10658    returned.  */
10659
10660 static int
10661 maybe_use_access_method (int is_super_init, tree *mdecl, tree *this_arg)
10662 {
10663   tree ctx;
10664   tree md = *mdecl, ta = *this_arg;
10665   int to_return = 0;
10666   int non_static_context = !METHOD_STATIC (md);
10667
10668   if (is_super_init
10669       || DECL_CONTEXT (md) == current_class
10670       || !PURE_INNER_CLASS_TYPE_P (current_class)
10671       || DECL_FINIT_P (md)
10672       || DECL_INSTINIT_P (md))
10673     return 0;
10674
10675   /* If we're calling a method found in an enclosing class, generate
10676      what it takes to retrieve the right this. Don't do that if we're
10677      invoking a static method. Note that if MD's type is unrelated to
10678      CURRENT_CLASS, then the current this can be used. */
10679
10680   if (non_static_context && DECL_CONTEXT (md) != object_type_node)
10681     {
10682       ctx = TREE_TYPE (DECL_CONTEXT (TYPE_NAME (current_class)));
10683       if (inherits_from_p (ctx, DECL_CONTEXT (md)))
10684         {
10685           ta = build_current_thisn (current_class);
10686           ta = build_wfl_node (ta);
10687         }
10688       else
10689         {
10690           tree type = ctx;
10691           while (type)
10692             {
10693               maybe_build_thisn_access_method (type);
10694               if (inherits_from_p (type, DECL_CONTEXT (md)))
10695                 {
10696                   ta = build_access_to_thisn (ctx, type, 0);
10697                   break;
10698                 }
10699               type = (DECL_CONTEXT (TYPE_NAME (type)) ?
10700                       TREE_TYPE (DECL_CONTEXT (TYPE_NAME (type))) : NULL_TREE);
10701             }
10702         }
10703       ta = java_complete_tree (ta);
10704     }
10705
10706   /* We might have to use an access method to get to MD. We can
10707      break the method access rule as far as we're not generating
10708      bytecode */
10709   if (METHOD_PRIVATE (md) && flag_emit_class_files)
10710     {
10711       md = build_outer_method_access_method (md);
10712       to_return = 1;
10713     }
10714
10715   *mdecl = md;
10716   *this_arg = ta;
10717
10718   /* Returning a nonzero value indicates we were doing a non static
10719      method invocation that is now a static invocation. It will have
10720      callee displace `this' to insert it in the regular argument
10721      list. */
10722   return (non_static_context && to_return);
10723 }
10724
10725 /* Patch an invoke expression METHOD and ARGS, based on its invocation
10726    mode.  */
10727
10728 static tree
10729 patch_invoke (tree patch, tree method, tree args)
10730 {
10731   tree dtable, func;
10732   tree original_call, t, ta;
10733   tree check = NULL_TREE;
10734
10735   /* Last step for args: convert build-in types. If we're dealing with
10736      a new TYPE() type call, the first argument to the constructor
10737      isn't found in the incoming argument list, but delivered by
10738      `new' */
10739   t = TYPE_ARG_TYPES (TREE_TYPE (method));
10740   if (TREE_CODE (patch) == NEW_CLASS_EXPR)
10741     t = TREE_CHAIN (t);
10742   for (ta = args; t != end_params_node && ta;
10743        t = TREE_CHAIN (t), ta = TREE_CHAIN (ta))
10744     if (JPRIMITIVE_TYPE_P (TREE_TYPE (TREE_VALUE (ta))) &&
10745         TREE_TYPE (TREE_VALUE (ta)) != TREE_VALUE (t))
10746       TREE_VALUE (ta) = convert (TREE_VALUE (t), TREE_VALUE (ta));
10747
10748   /* Resolve unresolved returned type issues */
10749   t = TREE_TYPE (TREE_TYPE (method));
10750   if (TREE_CODE (t) == POINTER_TYPE && !CLASS_LOADED_P (TREE_TYPE (t)))
10751     resolve_and_layout (TREE_TYPE (t), NULL);
10752
10753   if (flag_emit_class_files || flag_emit_xref)
10754     func = method;
10755   else
10756     {
10757       switch (invocation_mode (method, CALL_USING_SUPER (patch)))
10758         {
10759         case INVOKE_VIRTUAL:
10760           dtable = invoke_build_dtable (0, args);
10761           func = build_invokevirtual (dtable, method);
10762           break;
10763
10764         case INVOKE_NONVIRTUAL:
10765           /* If the object for the method call is null, we throw an
10766              exception.  We don't do this if the object is the current
10767              method's `this'.  In other cases we just rely on an
10768              optimization pass to eliminate redundant checks.  */
10769           if (TREE_VALUE (args) != current_this)
10770             {
10771               /* We use a save_expr here to make sure we only evaluate
10772                  the new `self' expression once.  */
10773               tree save_arg = save_expr (TREE_VALUE (args));
10774               TREE_VALUE (args) = save_arg;
10775               check = java_check_reference (save_arg, 1);
10776             }
10777           /* Fall through.  */
10778
10779         case INVOKE_SUPER:
10780         case INVOKE_STATIC:
10781           {
10782             tree signature = build_java_signature (TREE_TYPE (method));
10783             func = build_known_method_ref (method, TREE_TYPE (method),
10784                                            DECL_CONTEXT (method),
10785                                            signature, args);
10786           }
10787           break;
10788
10789         case INVOKE_INTERFACE:
10790           dtable = invoke_build_dtable (1, args);
10791           func = build_invokeinterface (dtable, method);
10792           break;
10793
10794         default:
10795           abort ();
10796         }
10797
10798       /* Ensure self_type is initialized, (invokestatic). FIXME */
10799       func = build1 (NOP_EXPR, build_pointer_type (TREE_TYPE (method)), func);
10800     }
10801
10802   TREE_TYPE (patch) = TREE_TYPE (TREE_TYPE (method));
10803   TREE_OPERAND (patch, 0) = func;
10804   TREE_OPERAND (patch, 1) = args;
10805   patch = check_for_builtin (method, patch);
10806   original_call = patch;
10807
10808   /* We're processing a `new TYPE ()' form. New is called and its
10809      returned value is the first argument to the constructor. We build
10810      a COMPOUND_EXPR and use saved expression so that the overall NEW
10811      expression value is a pointer to a newly created and initialized
10812      class. */
10813   if (TREE_CODE (original_call) == NEW_CLASS_EXPR)
10814     {
10815       tree class = DECL_CONTEXT (method);
10816       tree c1, saved_new, size, new;
10817       tree alloc_node;
10818
10819       if (flag_emit_class_files || flag_emit_xref)
10820         {
10821           TREE_TYPE (patch) = build_pointer_type (class);
10822           return patch;
10823         }
10824       if (!TYPE_SIZE (class))
10825         safe_layout_class (class);
10826       size = size_in_bytes (class);
10827       alloc_node =
10828         (class_has_finalize_method (class) ? alloc_object_node
10829                                            : alloc_no_finalizer_node);
10830       new = build (CALL_EXPR, promote_type (class),
10831                    build_address_of (alloc_node),
10832                    tree_cons (NULL_TREE, build_class_ref (class),
10833                               build_tree_list (NULL_TREE,
10834                                                size_in_bytes (class))),
10835                    NULL_TREE);
10836       saved_new = save_expr (new);
10837       c1 = build_tree_list (NULL_TREE, saved_new);
10838       TREE_CHAIN (c1) = TREE_OPERAND (original_call, 1);
10839       TREE_OPERAND (original_call, 1) = c1;
10840       TREE_SET_CODE (original_call, CALL_EXPR);
10841       patch = build (COMPOUND_EXPR, TREE_TYPE (new), patch, saved_new);
10842     }
10843
10844   /* If CHECK is set, then we are building a check to see if the object
10845      is NULL.  */
10846   if (check != NULL_TREE)
10847     {
10848       /* We have to call force_evaluation_order now because creating a
10849          COMPOUND_EXPR wraps the arg list in a way that makes it
10850          unrecognizable by force_evaluation_order later.  Yuk.  */
10851       patch = build (COMPOUND_EXPR, TREE_TYPE (patch), check, 
10852                      force_evaluation_order (patch));
10853       TREE_SIDE_EFFECTS (patch) = 1;
10854     }
10855
10856   /* In order to be able to modify PATCH later, we SAVE_EXPR it and
10857      put it as the first expression of a COMPOUND_EXPR. The second
10858      expression being an empty statement to be later patched if
10859      necessary. We remember a TREE_LIST (the PURPOSE is the method,
10860      the VALUE is the compound) in a hashtable and return a
10861      COMPOUND_EXPR built so that the result of the evaluation of the
10862      original PATCH node is returned. */
10863   if (STATIC_CLASS_INIT_OPT_P ()
10864       && current_function_decl && METHOD_STATIC (method))
10865     {
10866       tree list;
10867       tree fndecl = current_function_decl;
10868       /* We have to call force_evaluation_order now because creating a
10869          COMPOUND_EXPR wraps the arg list in a way that makes it
10870          unrecognizable by force_evaluation_order later.  Yuk.  */
10871       tree save = save_expr (force_evaluation_order (patch));
10872       tree type = TREE_TYPE (patch);
10873
10874       patch = build (COMPOUND_EXPR, type, save, empty_stmt_node);
10875       list = tree_cons (method, patch,
10876                         DECL_FUNCTION_STATIC_METHOD_INVOCATION_COMPOUND (fndecl));
10877
10878       DECL_FUNCTION_STATIC_METHOD_INVOCATION_COMPOUND (fndecl) = list;
10879
10880       patch = build (COMPOUND_EXPR, type, patch, save);
10881     }
10882
10883   return patch;
10884 }
10885
10886 static int
10887 invocation_mode (tree method, int super)
10888 {
10889   int access = get_access_flags_from_decl (method);
10890
10891   if (super)
10892     return INVOKE_SUPER;
10893
10894   if (access & ACC_STATIC)
10895     return INVOKE_STATIC;
10896
10897   /* We have to look for a constructor before we handle nonvirtual
10898      calls; otherwise the constructor will look nonvirtual.  */
10899   if (DECL_CONSTRUCTOR_P (method))
10900     return INVOKE_STATIC;
10901
10902   if (access & ACC_FINAL || access & ACC_PRIVATE)
10903     return INVOKE_NONVIRTUAL;
10904
10905   if (CLASS_FINAL (TYPE_NAME (DECL_CONTEXT (method))))
10906     return INVOKE_NONVIRTUAL;
10907
10908   if (CLASS_INTERFACE (TYPE_NAME (DECL_CONTEXT (method))))
10909     return INVOKE_INTERFACE;
10910
10911   return INVOKE_VIRTUAL;
10912 }
10913
10914 /* Retrieve a refined list of matching methods. It covers the step
10915    15.11.2 (Compile-Time Step 2) */
10916
10917 static tree
10918 lookup_method_invoke (int lc, tree cl, tree class, tree name, tree arg_list)
10919 {
10920   tree atl = end_params_node;           /* Arg Type List */
10921   tree method, signature, list, node;
10922   const char *candidates;               /* Used for error report */
10923   char *dup;
10924
10925   /* Fix the arguments */
10926   for (node = arg_list; node; node = TREE_CHAIN (node))
10927     {
10928       tree current_arg = TREE_TYPE (TREE_VALUE (node));
10929       /* Non primitive type may have to be resolved */
10930       if (!JPRIMITIVE_TYPE_P (current_arg))
10931         resolve_and_layout (current_arg, NULL_TREE);
10932       /* And promoted */
10933       if (TREE_CODE (current_arg) == RECORD_TYPE)
10934         current_arg = promote_type (current_arg);
10935       atl = tree_cons (NULL_TREE, current_arg, atl);
10936     }
10937
10938   /* Presto. If we're dealing with an anonymous class and a
10939      constructor call, generate the right constructor now, since we
10940      know the arguments' types. */
10941
10942   if (lc && ANONYMOUS_CLASS_P (class))
10943     {
10944       tree saved_current_class;
10945       tree mdecl = craft_constructor (TYPE_NAME (class), atl);
10946       saved_current_class = current_class;
10947       current_class = class;
10948       fix_constructors (mdecl);
10949       current_class = saved_current_class;
10950     }
10951
10952   /* Find all candidates and then refine the list, searching for the
10953      most specific method. */
10954   list = find_applicable_accessible_methods_list (lc, class, name, atl);
10955   list = find_most_specific_methods_list (list);
10956   if (list && !TREE_CHAIN (list))
10957     return TREE_VALUE (list);
10958
10959   /* Issue an error. List candidates if any. Candidates are listed
10960      only if accessible (non accessible methods may end-up here for
10961      the sake of a better error report). */
10962   candidates = NULL;
10963   if (list)
10964     {
10965       tree current;
10966       obstack_grow (&temporary_obstack, ". Candidates are:\n", 18);
10967       for (current = list; current; current = TREE_CHAIN (current))
10968         {
10969           tree cm = TREE_VALUE (current);
10970           char string [4096];
10971           if (!cm || not_accessible_p (class, cm, NULL_TREE, 0))
10972             continue;
10973           sprintf
10974             (string, "  `%s' in `%s'%s",
10975              get_printable_method_name (cm),
10976              IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (DECL_CONTEXT (cm)))),
10977              (TREE_CHAIN (current) ? "\n" : ""));
10978           obstack_grow (&temporary_obstack, string, strlen (string));
10979         }
10980       obstack_1grow (&temporary_obstack, '\0');
10981       candidates = obstack_finish (&temporary_obstack);
10982     }
10983   /* Issue the error message */
10984   method = make_node (FUNCTION_TYPE);
10985   TYPE_ARG_TYPES (method) = atl;
10986   signature = build_java_argument_signature (method);
10987   dup = xstrdup (lang_printable_name (class, 0));
10988   parse_error_context (cl, "Can't find %s `%s(%s)' in type `%s'%s",
10989                        (lc ? "constructor" : "method"),
10990                        (lc ? dup : IDENTIFIER_POINTER (name)),
10991                        IDENTIFIER_POINTER (signature), dup,
10992                        (candidates ? candidates : ""));
10993   free (dup);
10994   return NULL_TREE;
10995 }
10996
10997 /* 15.11.2.1: Find Methods that are Applicable and Accessible. LC is 1
10998    when we're looking for a constructor. */
10999
11000 static tree
11001 find_applicable_accessible_methods_list (int lc, tree class, tree name,
11002                                          tree arglist)
11003 {
11004   static htab_t searched_classes;
11005   static int search_not_done = 0;
11006   tree list = NULL_TREE, all_list = NULL_TREE;
11007
11008   /* Check the hash table to determine if this class has been searched
11009      already. */
11010   if (searched_classes)
11011     {
11012       if (htab_find (searched_classes, class) != NULL)
11013         return NULL;
11014     }
11015   else
11016     {
11017       searched_classes = htab_create (10, htab_hash_pointer,
11018                                       htab_eq_pointer, NULL);
11019     }
11020
11021   search_not_done++;
11022   *htab_find_slot (searched_classes, class, INSERT) = class;
11023
11024   if (!CLASS_LOADED_P (class) && !CLASS_FROM_SOURCE_P (class))
11025     {
11026       load_class (class, 1);
11027       safe_layout_class (class);
11028     }
11029
11030   /* Search interfaces */
11031   if (TREE_CODE (TYPE_NAME (class)) == TYPE_DECL
11032       && CLASS_INTERFACE (TYPE_NAME (class)))
11033     {
11034       int i, n;
11035       tree basetype_vec = TYPE_BINFO_BASETYPES (class);
11036       search_applicable_methods_list (lc, TYPE_METHODS (class),
11037                                       name, arglist, &list, &all_list);
11038       n = TREE_VEC_LENGTH (basetype_vec);
11039       for (i = 1; i < n; i++)
11040         {
11041           tree t = BINFO_TYPE (TREE_VEC_ELT (basetype_vec, i));
11042           tree rlist;
11043
11044           rlist = find_applicable_accessible_methods_list (lc,  t, name,
11045                                                            arglist);
11046           list = chainon (rlist, list);
11047         }
11048     }
11049   /* Search classes */
11050   else
11051     {
11052       search_applicable_methods_list (lc, TYPE_METHODS (class),
11053                                       name, arglist, &list, &all_list);
11054
11055       /* When looking finit$, class$ or instinit$, we turn LC to 1 so
11056          that we only search in class. Note that we should have found
11057          something at this point. */
11058       if (ID_FINIT_P (name) || ID_CLASSDOLLAR_P (name) || ID_INSTINIT_P (name))
11059         {
11060           lc = 1;
11061           if (!list)
11062             abort ();
11063         }
11064
11065       /* We must search all interfaces of this class */
11066       if (!lc)
11067       {
11068         tree basetype_vec = TYPE_BINFO_BASETYPES (class);
11069         int n = TREE_VEC_LENGTH (basetype_vec), i;
11070         for (i = 1; i < n; i++)
11071           {
11072             tree t = BINFO_TYPE (TREE_VEC_ELT (basetype_vec, i));
11073             if (t != object_type_node)
11074               {
11075                 tree rlist
11076                   = find_applicable_accessible_methods_list (lc, t,
11077                                                              name, arglist);
11078                 list = chainon (rlist, list);
11079               }
11080           }
11081       }
11082
11083       /* Search superclass */
11084       if (!lc && CLASSTYPE_SUPER (class) != NULL_TREE)
11085         {
11086           tree rlist;
11087           class = CLASSTYPE_SUPER (class);
11088           rlist = find_applicable_accessible_methods_list (lc, class,
11089                                                            name, arglist);
11090           list = chainon (rlist, list);
11091         }
11092     }
11093
11094   search_not_done--;
11095
11096   /* We're done. Reset the searched classes list and finally search
11097      java.lang.Object if it wasn't searched already. */
11098   if (!search_not_done)
11099     {
11100       if (!lc
11101           && TYPE_METHODS (object_type_node)
11102           && htab_find (searched_classes, object_type_node) == NULL)
11103         {
11104           search_applicable_methods_list (lc,
11105                                           TYPE_METHODS (object_type_node),
11106                                           name, arglist, &list, &all_list);
11107         }
11108       htab_delete (searched_classes);
11109       searched_classes = NULL;
11110     }
11111
11112   /* Either return the list obtained or all selected (but
11113      inaccessible) methods for better error report. */
11114   return (!list ? all_list : list);
11115 }
11116
11117 /* Effectively search for the appropriate method in method */
11118
11119 static void
11120 search_applicable_methods_list (int lc, tree method, tree name, tree arglist,
11121                                 tree *list, tree *all_list)
11122 {
11123   for (; method; method = TREE_CHAIN (method))
11124     {
11125       /* When dealing with constructor, stop here, otherwise search
11126          other classes */
11127       if (lc && !DECL_CONSTRUCTOR_P (method))
11128         continue;
11129       else if (!lc && (DECL_CONSTRUCTOR_P (method)
11130                        || (DECL_NAME (method) != name)))
11131         continue;
11132
11133       if (argument_types_convertible (method, arglist))
11134         {
11135           /* Retain accessible methods only */
11136           if (!not_accessible_p (DECL_CONTEXT (current_function_decl),
11137                                  method, NULL_TREE, 0))
11138             *list = tree_cons (NULL_TREE, method, *list);
11139           else
11140             /* Also retain all selected method here */
11141             *all_list = tree_cons (NULL_TREE, method, *list);
11142         }
11143     }
11144 }
11145
11146 /* 15.11.2.2 Choose the Most Specific Method */
11147
11148 static tree
11149 find_most_specific_methods_list (tree list)
11150 {
11151   int max = 0;
11152   int abstract, candidates;
11153   tree current, new_list = NULL_TREE;
11154   for (current = list; current; current = TREE_CHAIN (current))
11155     {
11156       tree method;
11157       DECL_SPECIFIC_COUNT (TREE_VALUE (current)) = 0;
11158
11159       for (method = list; method; method = TREE_CHAIN (method))
11160         {
11161           tree method_v, current_v;
11162           /* Don't test a method against itself */
11163           if (method == current)
11164             continue;
11165
11166           method_v = TREE_VALUE (method);
11167           current_v = TREE_VALUE (current);
11168
11169           /* Compare arguments and location where methods where declared */
11170           if (argument_types_convertible (method_v, current_v))
11171             {
11172               if (valid_method_invocation_conversion_p
11173                   (DECL_CONTEXT (method_v), DECL_CONTEXT (current_v))
11174                   || (INNER_CLASS_TYPE_P (DECL_CONTEXT (current_v))
11175                       && enclosing_context_p (DECL_CONTEXT (method_v),
11176                                               DECL_CONTEXT (current_v))))
11177                 {
11178                   int v = (DECL_SPECIFIC_COUNT (current_v) +=
11179                     (INNER_CLASS_TYPE_P (DECL_CONTEXT (current_v)) ? 2 : 1));
11180                   max = (v > max ? v : max);
11181                 }
11182             }
11183         }
11184     }
11185
11186   /* Review the list and select the maximally specific methods */
11187   for (current = list, abstract = -1, candidates = -1;
11188        current; current = TREE_CHAIN (current))
11189     if (DECL_SPECIFIC_COUNT (TREE_VALUE (current)) == max)
11190       {
11191         new_list = tree_cons (NULL_TREE, TREE_VALUE (current), new_list);
11192         abstract += (METHOD_ABSTRACT (TREE_VALUE (current)) ? 1 : 0);
11193         candidates++;
11194       }
11195
11196   /* If we have several and they're all abstract, just pick the
11197      closest one. */
11198   if (candidates > 0 && candidates == abstract)
11199     {
11200       /* FIXME: merge the throws clauses.  There is no convenient way
11201          to do this in gcj right now, since ideally we'd like to
11202          introduce a new METHOD_DECL here, but that is really not
11203          possible.  */
11204       new_list = nreverse (new_list);
11205       TREE_CHAIN (new_list) = NULL_TREE;
11206       return new_list;
11207     }
11208
11209   /* We have several (we couldn't find a most specific), all but one
11210      are abstract, we pick the only non abstract one. */
11211   if (candidates > 0 && (candidates == abstract+1))
11212     {
11213       for (current = new_list; current; current = TREE_CHAIN (current))
11214         if (!METHOD_ABSTRACT (TREE_VALUE (current)))
11215           {
11216             TREE_CHAIN (current) = NULL_TREE;
11217             new_list = current;
11218           }
11219     }
11220
11221   /* If we can't find one, lower expectations and try to gather multiple
11222      maximally specific methods */
11223   while (!new_list && max)
11224     {
11225       while (--max > 0)
11226         {
11227           if (DECL_SPECIFIC_COUNT (TREE_VALUE (current)) == max)
11228             new_list = tree_cons (NULL_TREE, TREE_VALUE (current), new_list);
11229         }
11230     }
11231
11232   return new_list;
11233 }
11234
11235 /* Make sure that the type of each M2_OR_ARGLIST arguments can be
11236    converted by method invocation conversion (5.3) to the type of the
11237    corresponding parameter of M1. Implementation expects M2_OR_ARGLIST
11238    to change less often than M1. */
11239
11240 static GTY(()) tree m2_arg_value;
11241 static GTY(()) tree m2_arg_cache;
11242
11243 static int
11244 argument_types_convertible (tree m1, tree m2_or_arglist)
11245 {
11246   register tree m1_arg, m2_arg;
11247
11248   SKIP_THIS_AND_ARTIFICIAL_PARMS (m1_arg, m1)
11249
11250   if (m2_arg_value == m2_or_arglist)
11251     m2_arg = m2_arg_cache;
11252   else
11253     {
11254       /* M2_OR_ARGLIST can be a function DECL or a raw list of
11255          argument types */
11256       if (m2_or_arglist && TREE_CODE (m2_or_arglist) == FUNCTION_DECL)
11257         {
11258           m2_arg = TYPE_ARG_TYPES (TREE_TYPE (m2_or_arglist));
11259           if (!METHOD_STATIC (m2_or_arglist))
11260             m2_arg = TREE_CHAIN (m2_arg);
11261         }
11262       else
11263         m2_arg = m2_or_arglist;
11264
11265       m2_arg_value = m2_or_arglist;
11266       m2_arg_cache = m2_arg;
11267     }
11268
11269   while (m1_arg != end_params_node && m2_arg != end_params_node)
11270     {
11271       resolve_and_layout (TREE_VALUE (m1_arg), NULL_TREE);
11272       if (!valid_method_invocation_conversion_p (TREE_VALUE (m1_arg),
11273                                                  TREE_VALUE (m2_arg)))
11274         break;
11275       m1_arg = TREE_CHAIN (m1_arg);
11276       m2_arg = TREE_CHAIN (m2_arg);
11277     }
11278   return m1_arg == end_params_node && m2_arg == end_params_node;
11279 }
11280
11281 /* Qualification routines */
11282
11283 static void
11284 qualify_ambiguous_name (tree id)
11285 {
11286   tree qual, qual_wfl, name = NULL_TREE, decl, ptr_type = NULL_TREE,
11287     saved_current_class;
11288   int again, super_found = 0, this_found = 0, new_array_found = 0;
11289   int code;
11290
11291   /* We first qualify the first element, then derive qualification of
11292      others based on the first one. If the first element is qualified
11293      by a resolution (field or type), this resolution is stored in the
11294      QUAL_RESOLUTION of the qual element being examined. We need to
11295      save the current_class since the use of SUPER might change the
11296      its value. */
11297   saved_current_class = current_class;
11298   qual = EXPR_WFL_QUALIFICATION (id);
11299   do {
11300
11301     /* Simple qualified expression feature a qual_wfl that is a
11302        WFL. Expression derived from a primary feature more complicated
11303        things like a CALL_EXPR. Expression from primary need to be
11304        worked out to extract the part on which the qualification will
11305        take place. */
11306     qual_wfl = QUAL_WFL (qual);
11307     switch (TREE_CODE (qual_wfl))
11308       {
11309       case CALL_EXPR:
11310         qual_wfl = TREE_OPERAND (qual_wfl, 0);
11311         if (TREE_CODE (qual_wfl) != EXPR_WITH_FILE_LOCATION
11312             || (EXPR_WFL_QUALIFICATION (qual_wfl)
11313                 && TREE_CODE (EXPR_WFL_QUALIFICATION (qual_wfl)) == TREE_LIST))
11314           {
11315             qual = EXPR_WFL_QUALIFICATION (qual_wfl);
11316             qual_wfl = QUAL_WFL (qual);
11317           }
11318         break;
11319       case NEW_ARRAY_EXPR:
11320       case NEW_ANONYMOUS_ARRAY_EXPR:
11321         qual = TREE_CHAIN (qual);
11322         again = new_array_found = 1;
11323         continue;
11324       case CONVERT_EXPR:
11325         break;
11326       case NEW_CLASS_EXPR:
11327         qual_wfl = TREE_OPERAND (qual_wfl, 0);
11328         break;
11329       case ARRAY_REF:
11330         while (TREE_CODE (qual_wfl) == ARRAY_REF)
11331           qual_wfl = TREE_OPERAND (qual_wfl, 0);
11332         break;
11333       case STRING_CST:
11334         qual = TREE_CHAIN (qual);
11335         qual_wfl = QUAL_WFL (qual);
11336         break;
11337       case CLASS_LITERAL:
11338         qual = TREE_CHAIN (qual);
11339         qual_wfl = QUAL_WFL (qual);
11340       break;
11341       default:
11342         /* Fix for -Wall. Just break doing nothing */
11343         break;
11344       }
11345
11346     ptr_type = current_class;
11347     again = 0;
11348     code = TREE_CODE (qual_wfl);
11349
11350     /* Pos evaluation: non WFL leading expression nodes */
11351     if (code == CONVERT_EXPR
11352         && TREE_CODE (TREE_TYPE (qual_wfl)) == EXPR_WITH_FILE_LOCATION)
11353       name = EXPR_WFL_NODE (TREE_TYPE (qual_wfl));
11354
11355     else if (code == INTEGER_CST)
11356       name = qual_wfl;
11357
11358     else if (code == CONVERT_EXPR &&
11359              TREE_CODE (TREE_OPERAND (qual_wfl, 0)) == EXPR_WITH_FILE_LOCATION)
11360       name = TREE_OPERAND (qual_wfl, 0);
11361
11362     else if (code == CONVERT_EXPR
11363              && TREE_CODE (TREE_OPERAND (qual_wfl, 0)) == CALL_EXPR
11364              && (TREE_CODE (TREE_OPERAND (TREE_OPERAND (qual_wfl, 0), 0))
11365                  == EXPR_WITH_FILE_LOCATION))
11366       name = TREE_OPERAND (TREE_OPERAND (qual_wfl, 0), 0);
11367
11368     else if ((code == ARRAY_REF || code == CALL_EXPR || code == MODIFY_EXPR) &&
11369              TREE_CODE (TREE_OPERAND (qual_wfl, 0)) == EXPR_WITH_FILE_LOCATION)
11370       name = EXPR_WFL_NODE (TREE_OPERAND (qual_wfl, 0));
11371
11372     else if (code == TREE_LIST)
11373       name = EXPR_WFL_NODE (TREE_PURPOSE (qual_wfl));
11374
11375     else if (code == STRING_CST || code == CONDITIONAL_EXPR
11376              || code == PLUS_EXPR)
11377       {
11378         qual = TREE_CHAIN (qual);
11379         qual_wfl = QUAL_WFL (qual);
11380         again = 1;
11381       }
11382     else
11383       {
11384         name = EXPR_WFL_NODE (qual_wfl);
11385         if (!name)
11386           {
11387             qual = EXPR_WFL_QUALIFICATION (qual_wfl);
11388             again = 1;
11389           }
11390       }
11391
11392     /* If we have a THIS (from a primary), we set the context accordingly */
11393     if (name == this_identifier_node)
11394       {
11395         /* This isn't really elegant. One more added irregularity
11396            before I start using COMPONENT_REF (hopefully very soon.)  */
11397         if (TREE_CODE (TREE_PURPOSE (qual)) == ARRAY_REF
11398             && TREE_CODE (TREE_OPERAND (TREE_PURPOSE (qual), 0)) ==
11399                EXPR_WITH_FILE_LOCATION
11400             && EXPR_WFL_NODE (TREE_OPERAND (TREE_PURPOSE (qual), 0)) ==
11401                this_identifier_node)
11402             {
11403               qual = TREE_OPERAND (TREE_PURPOSE (qual), 0);
11404               qual = EXPR_WFL_QUALIFICATION (qual);
11405             }
11406         qual = TREE_CHAIN (qual);
11407         qual_wfl = QUAL_WFL (qual);
11408         if (TREE_CODE (qual_wfl) == CALL_EXPR)
11409           again = 1;
11410         else if (TREE_CODE (qual_wfl) == EXPR_WITH_FILE_LOCATION)
11411           name = EXPR_WFL_NODE (qual_wfl);
11412         else if (TREE_CODE (qual_wfl) == NEW_CLASS_EXPR)
11413           name = TREE_OPERAND (qual_wfl, 0);
11414         this_found = 1;
11415       }
11416     /* If we have a SUPER, we set the context accordingly */
11417     if (name == super_identifier_node)
11418       {
11419         current_class = CLASSTYPE_SUPER (ptr_type);
11420         /* Check that there is such a thing as a super class. If not,
11421            return.  The error will be caught later on, during the
11422            resolution */
11423         if (!current_class)
11424           {
11425             current_class = saved_current_class;
11426             return;
11427           }
11428         qual = TREE_CHAIN (qual);
11429         /* Do one more iteration to set things up */
11430         super_found = again = 1;
11431       }
11432   } while (again);
11433
11434   /* If name appears within the scope of a local variable declaration
11435      or parameter declaration, then it is an expression name. We don't
11436      carry this test out if we're in the context of the use of SUPER
11437      or THIS */
11438   if (!this_found && !super_found
11439       && TREE_CODE (name) != STRING_CST && TREE_CODE (name) != INTEGER_CST
11440       && (decl = IDENTIFIER_LOCAL_VALUE (name)))
11441     {
11442       RESOLVE_EXPRESSION_NAME_P (qual_wfl) = 1;
11443       QUAL_RESOLUTION (qual) = decl;
11444     }
11445
11446   /* If within the class/interface NAME was found to be used there
11447      exists a (possibly inherited) field named NAME, then this is an
11448      expression name. If we saw a NEW_ARRAY_EXPR before and want to
11449      address length, it is OK. */
11450   else if ((decl = lookup_field_wrapper (ptr_type, name))
11451            || name == length_identifier_node)
11452     {
11453       RESOLVE_EXPRESSION_NAME_P (qual_wfl) = 1;
11454       QUAL_RESOLUTION (qual) = (new_array_found ? NULL_TREE : decl);
11455     }
11456
11457   /* We reclassify NAME as yielding to a type name resolution if:
11458      - NAME is a class/interface declared within the compilation
11459        unit containing NAME,
11460      - NAME is imported via a single-type-import declaration,
11461      - NAME is declared in an another compilation unit of the package
11462        of the compilation unit containing NAME,
11463      - NAME is declared by exactly on type-import-on-demand declaration
11464      of the compilation unit containing NAME.
11465      - NAME is actually a STRING_CST.
11466      This can't happen if the expression was qualified by `this.' */
11467   else if (! this_found &&
11468            (TREE_CODE (name) == STRING_CST ||
11469             TREE_CODE (name) == INTEGER_CST ||
11470             (decl = resolve_and_layout (name, NULL_TREE))))
11471     {
11472       RESOLVE_TYPE_NAME_P (qual_wfl) = 1;
11473       QUAL_RESOLUTION (qual) = decl;
11474     }
11475
11476   /* Method call, array references and cast are expression name */
11477   else if (TREE_CODE (QUAL_WFL (qual)) == CALL_EXPR
11478            || TREE_CODE (QUAL_WFL (qual)) == ARRAY_REF
11479            || TREE_CODE (QUAL_WFL (qual)) == CONVERT_EXPR
11480            || TREE_CODE (QUAL_WFL (qual)) == MODIFY_EXPR)
11481     RESOLVE_EXPRESSION_NAME_P (qual_wfl) = 1;
11482
11483   /* Check here that NAME isn't declared by more than one
11484      type-import-on-demand declaration of the compilation unit
11485      containing NAME. FIXME */
11486
11487   /* Otherwise, NAME is reclassified as a package name */
11488   else
11489     RESOLVE_PACKAGE_NAME_P (qual_wfl) = 1;
11490
11491   /* Propagate the qualification across other components of the
11492      qualified name */
11493   for (qual = TREE_CHAIN (qual); qual;
11494        qual_wfl = QUAL_WFL (qual), qual = TREE_CHAIN (qual))
11495     {
11496       if (RESOLVE_PACKAGE_NAME_P (qual_wfl))
11497         RESOLVE_PACKAGE_NAME_P (QUAL_WFL (qual)) = 1;
11498       else
11499         RESOLVE_EXPRESSION_NAME_P (QUAL_WFL (qual)) = 1;
11500     }
11501
11502   /* Store the global qualification for the ambiguous part of ID back
11503      into ID fields */
11504   if (RESOLVE_EXPRESSION_NAME_P (qual_wfl))
11505     RESOLVE_EXPRESSION_NAME_P (id) = 1;
11506   else if (RESOLVE_TYPE_NAME_P (qual_wfl))
11507     RESOLVE_TYPE_NAME_P (id) = 1;
11508   else if (RESOLVE_PACKAGE_NAME_P (qual_wfl))
11509     RESOLVE_PACKAGE_NAME_P (id) = 1;
11510
11511   /* Restore the current class */
11512   current_class = saved_current_class;
11513 }
11514
11515 static int
11516 breakdown_qualified (tree *left, tree *right, tree source)
11517 {
11518   char *p, *base;
11519   int l = IDENTIFIER_LENGTH (source);
11520
11521   base = alloca (l + 1);
11522   memcpy (base, IDENTIFIER_POINTER (source), l + 1);
11523
11524   /* Breakdown NAME into REMAINDER . IDENTIFIER.  */
11525   p = base + l - 1;
11526   while (*p != '.' && p != base)
11527     p--;
11528
11529   /* We didn't find a '.'. Return an error.  */
11530   if (p == base)
11531     return 1;
11532
11533   *p = '\0';
11534   if (right)
11535     *right = get_identifier (p+1);
11536   *left = get_identifier (base);
11537
11538   return 0;
11539 }
11540
11541 /* Return TRUE if two classes are from the same package. */
11542
11543 static int
11544 in_same_package (tree name1, tree name2)
11545 {
11546   tree tmp;
11547   tree pkg1;
11548   tree pkg2;
11549
11550   if (TREE_CODE (name1) == TYPE_DECL)
11551     name1 = DECL_NAME (name1);
11552   if (TREE_CODE (name2) == TYPE_DECL)
11553     name2 = DECL_NAME (name2);
11554
11555   if (QUALIFIED_P (name1) != QUALIFIED_P (name2))
11556     /* One in empty package. */
11557     return 0;
11558
11559   if (QUALIFIED_P (name1) == 0 && QUALIFIED_P (name2) == 0)
11560     /* Both in empty package. */
11561     return 1;
11562
11563   breakdown_qualified (&pkg1, &tmp, name1);
11564   breakdown_qualified (&pkg2, &tmp, name2);
11565
11566   return (pkg1 == pkg2);
11567 }
11568
11569 /* Patch tree nodes in a function body. When a BLOCK is found, push
11570    local variable decls if present.
11571    Same as java_complete_lhs, but does resolve static finals to values. */
11572
11573 static tree
11574 java_complete_tree (tree node)
11575 {
11576   node = java_complete_lhs (node);
11577   if (JDECL_P (node) && CLASS_FINAL_VARIABLE_P (node)
11578       && DECL_INITIAL (node) != NULL_TREE
11579       && !flag_emit_xref)
11580     {
11581       tree value = fold_constant_for_init (node, node);
11582       if (value != NULL_TREE)
11583         return value;
11584     }
11585   return node;
11586 }
11587
11588 static tree
11589 java_stabilize_reference (tree node)
11590 {
11591   if (TREE_CODE (node) == COMPOUND_EXPR)
11592     {
11593       tree op0 = TREE_OPERAND (node, 0);
11594       tree op1 = TREE_OPERAND (node, 1);
11595       TREE_OPERAND (node, 0) = save_expr (op0);
11596       TREE_OPERAND (node, 1) = java_stabilize_reference (op1);
11597       return node;
11598     }
11599   return stabilize_reference (node);
11600 }
11601
11602 /* Patch tree nodes in a function body. When a BLOCK is found, push
11603    local variable decls if present.
11604    Same as java_complete_tree, but does not resolve static finals to values. */
11605
11606 static tree
11607 java_complete_lhs (tree node)
11608 {
11609   tree nn, cn, wfl_op1, wfl_op2, wfl_op3;
11610   int flag;
11611
11612   /* CONVERT_EXPR always has its type set, even though it needs to be
11613      worked out. */
11614   if (TREE_TYPE (node) && TREE_CODE (node) != CONVERT_EXPR)
11615     return node;
11616
11617   /* The switch block implements cases processing container nodes
11618      first.  Contained nodes are always written back. Leaves come
11619      next and return a value. */
11620   switch (TREE_CODE (node))
11621     {
11622     case BLOCK:
11623
11624       /* 1- Block section.
11625          Set the local values on decl names so we can identify them
11626          faster when they're referenced. At that stage, identifiers
11627          are legal so we don't check for declaration errors. */
11628       for (cn = BLOCK_EXPR_DECLS (node); cn; cn = TREE_CHAIN (cn))
11629         {
11630           DECL_CONTEXT (cn) = current_function_decl;
11631           IDENTIFIER_LOCAL_VALUE (DECL_NAME (cn)) = cn;
11632         }
11633       if (BLOCK_EXPR_BODY (node) == NULL_TREE)
11634           CAN_COMPLETE_NORMALLY (node) = 1;
11635       else
11636         {
11637           tree stmt = BLOCK_EXPR_BODY (node);
11638           tree *ptr;
11639           int error_seen = 0;
11640           if (TREE_CODE (stmt) == COMPOUND_EXPR)
11641             {
11642               /* Re-order from (((A; B); C); ...; Z) to
11643                  (A; (B; (C ; (...; Z)))).
11644                  This makes it easier to scan the statements left-to-right
11645                  without using recursion (which might overflow the stack
11646                  if the block has many statements. */
11647               for (;;)
11648                 {
11649                   tree left = TREE_OPERAND (stmt, 0);
11650                   if (TREE_CODE (left) != COMPOUND_EXPR)
11651                     break;
11652                   TREE_OPERAND (stmt, 0) = TREE_OPERAND (left, 1);
11653                   TREE_OPERAND (left, 1) = stmt;
11654                   stmt = left;
11655                 }
11656               BLOCK_EXPR_BODY (node) = stmt;
11657             }
11658
11659           /* Now do the actual complete, without deep recursion for
11660              long blocks. */
11661           ptr = &BLOCK_EXPR_BODY (node);
11662           while (TREE_CODE (*ptr) == COMPOUND_EXPR
11663                  && TREE_OPERAND (*ptr, 1) != empty_stmt_node)
11664             {
11665               tree cur = java_complete_tree (TREE_OPERAND (*ptr, 0));
11666               tree *next = &TREE_OPERAND (*ptr, 1);
11667               TREE_OPERAND (*ptr, 0) = cur;
11668               if (cur == empty_stmt_node)
11669                 {
11670                   /* Optimization;  makes it easier to detect empty bodies.
11671                      Most useful for <clinit> with all-constant initializer. */
11672                   *ptr = *next;
11673                   continue;
11674                 }
11675               if (TREE_CODE (cur) == ERROR_MARK)
11676                 error_seen++;
11677               else if (! CAN_COMPLETE_NORMALLY (cur))
11678                 {
11679                   wfl_op2 = *next;
11680                   for (;;)
11681                     {
11682                       if (TREE_CODE (wfl_op2) == BLOCK)
11683                         wfl_op2 = BLOCK_EXPR_BODY (wfl_op2);
11684                       else if (TREE_CODE (wfl_op2) == COMPOUND_EXPR)
11685                         wfl_op2 = TREE_OPERAND (wfl_op2, 0);
11686                       else
11687                         break;
11688                     }
11689                   if (TREE_CODE (wfl_op2) != CASE_EXPR
11690                       && TREE_CODE (wfl_op2) != DEFAULT_EXPR)
11691                     unreachable_stmt_error (*ptr);
11692                 }
11693               if (TREE_TYPE (*ptr) == NULL_TREE)
11694                 TREE_TYPE (*ptr) = void_type_node;
11695               ptr = next;
11696             }
11697           *ptr = java_complete_tree (*ptr);
11698
11699           if (TREE_CODE (*ptr) == ERROR_MARK || error_seen > 0)
11700             return error_mark_node;
11701           CAN_COMPLETE_NORMALLY (node) = CAN_COMPLETE_NORMALLY (*ptr);
11702         }
11703       /* Turn local bindings to null */
11704       for (cn = BLOCK_EXPR_DECLS (node); cn; cn = TREE_CHAIN (cn))
11705         IDENTIFIER_LOCAL_VALUE (DECL_NAME (cn)) = NULL_TREE;
11706
11707       TREE_TYPE (node) = void_type_node;
11708       break;
11709
11710       /* 2- They are expressions but ultimately deal with statements */
11711
11712     case THROW_EXPR:
11713       wfl_op1 = TREE_OPERAND (node, 0);
11714       COMPLETE_CHECK_OP_0 (node);
11715       /* 14.19 A throw statement cannot complete normally. */
11716       CAN_COMPLETE_NORMALLY (node) = 0;
11717       return patch_throw_statement (node, wfl_op1);
11718
11719     case SYNCHRONIZED_EXPR:
11720       wfl_op1 = TREE_OPERAND (node, 0);
11721       return patch_synchronized_statement (node, wfl_op1);
11722
11723     case TRY_EXPR:
11724       return patch_try_statement (node);
11725
11726     case TRY_FINALLY_EXPR:
11727       COMPLETE_CHECK_OP_0 (node);
11728       COMPLETE_CHECK_OP_1 (node);
11729       /* Reduce try/finally nodes with an empty try block.  */
11730       if (TREE_OPERAND (node, 0) == empty_stmt_node
11731           || BLOCK_EMPTY_P (TREE_OPERAND (node, 0)))
11732         return TREE_OPERAND (node, 1);
11733       /* Likewise for an empty finally block.  */
11734       if (TREE_OPERAND (node, 1) == empty_stmt_node
11735           || BLOCK_EMPTY_P (TREE_OPERAND (node, 1)))
11736         return TREE_OPERAND (node, 0);
11737       CAN_COMPLETE_NORMALLY (node)
11738         = (CAN_COMPLETE_NORMALLY (TREE_OPERAND (node, 0))
11739            && CAN_COMPLETE_NORMALLY (TREE_OPERAND (node, 1)));
11740       TREE_TYPE (node) = TREE_TYPE (TREE_OPERAND (node, 0));
11741       return node;
11742
11743     case LABELED_BLOCK_EXPR:
11744       PUSH_LABELED_BLOCK (node);
11745       if (LABELED_BLOCK_BODY (node))
11746         COMPLETE_CHECK_OP_1 (node);
11747       TREE_TYPE (node) = void_type_node;
11748       POP_LABELED_BLOCK ();
11749
11750       if (LABELED_BLOCK_BODY (node) == empty_stmt_node)
11751         {
11752           LABELED_BLOCK_BODY (node) = NULL_TREE;
11753           CAN_COMPLETE_NORMALLY (node) = 1;
11754         }
11755       else if (CAN_COMPLETE_NORMALLY (LABELED_BLOCK_BODY (node)))
11756         CAN_COMPLETE_NORMALLY (node) = 1;
11757       return node;
11758
11759     case EXIT_BLOCK_EXPR:
11760       /* We don't complete operand 1, because it's the return value of
11761          the EXIT_BLOCK_EXPR which doesn't exist it Java */
11762       return patch_bc_statement (node);
11763
11764     case CASE_EXPR:
11765       cn = java_complete_tree (TREE_OPERAND (node, 0));
11766       if (cn == error_mark_node)
11767         return cn;
11768
11769       /* First, the case expression must be constant. Values of final
11770          fields are accepted. */
11771       cn = fold (cn);
11772       if ((TREE_CODE (cn) == COMPOUND_EXPR || TREE_CODE (cn) == COMPONENT_REF)
11773           && JDECL_P (TREE_OPERAND (cn, 1))
11774           && FIELD_FINAL (TREE_OPERAND (cn, 1))
11775           && DECL_INITIAL (TREE_OPERAND (cn, 1)))
11776         {
11777           cn = fold_constant_for_init (DECL_INITIAL (TREE_OPERAND (cn, 1)),
11778                                        TREE_OPERAND (cn, 1));
11779         }
11780       /* Accept final locals too. */
11781       else if (TREE_CODE (cn) == VAR_DECL && DECL_FINAL (cn))
11782         cn = fold_constant_for_init (DECL_INITIAL (cn), cn);
11783
11784       if (!TREE_CONSTANT (cn) && !flag_emit_xref)
11785         {
11786           EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
11787           parse_error_context (node, "Constant expression required");
11788           return error_mark_node;
11789         }
11790
11791       nn = ctxp->current_loop;
11792
11793       /* It must be assignable to the type of the switch expression. */
11794       if (!try_builtin_assignconv (NULL_TREE,
11795                                    TREE_TYPE (TREE_OPERAND (nn, 0)), cn))
11796         {
11797           EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
11798           parse_error_context
11799             (wfl_operator,
11800              "Incompatible type for case. Can't convert `%s' to `int'",
11801              lang_printable_name (TREE_TYPE (cn), 0));
11802           return error_mark_node;
11803         }
11804
11805       cn = fold (convert (int_type_node, cn));
11806       TREE_CONSTANT_OVERFLOW (cn) = 0;
11807       CAN_COMPLETE_NORMALLY (cn) = 1;
11808
11809       /* Save the label on a list so that we can later check for
11810          duplicates.  */
11811       case_label_list = tree_cons (node, cn, case_label_list);
11812
11813       /* Multiple instance of a case label bearing the same value is
11814          checked later. The case expression is all right so far. */
11815       if (TREE_CODE (cn) == VAR_DECL)
11816         cn = DECL_INITIAL (cn);
11817       TREE_OPERAND (node, 0) = cn;
11818       TREE_TYPE (node) = void_type_node;
11819       CAN_COMPLETE_NORMALLY (node) = 1;
11820       TREE_SIDE_EFFECTS (node) = 1;
11821       break;
11822
11823     case DEFAULT_EXPR:
11824       nn = ctxp->current_loop;
11825       /* Only one default label is allowed per switch statement */
11826       if (SWITCH_HAS_DEFAULT (nn))
11827         {
11828           EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
11829           parse_error_context (wfl_operator,
11830                                "Duplicate case label: `default'");
11831           return error_mark_node;
11832         }
11833       else
11834         SWITCH_HAS_DEFAULT (nn) = 1;
11835       TREE_TYPE (node) = void_type_node;
11836       TREE_SIDE_EFFECTS (node) = 1;
11837       CAN_COMPLETE_NORMALLY (node) = 1;
11838       break;
11839
11840     case SWITCH_EXPR:
11841     case LOOP_EXPR:
11842       PUSH_LOOP (node);
11843       /* Check whether the loop was enclosed in a labeled
11844          statement. If not, create one, insert the loop in it and
11845          return the node */
11846       nn = patch_loop_statement (node);
11847
11848       /* Anyways, walk the body of the loop */
11849       if (TREE_CODE (node) == LOOP_EXPR)
11850         TREE_OPERAND (node, 0) = java_complete_tree (TREE_OPERAND (node, 0));
11851       /* Switch statement: walk the switch expression and the cases */
11852       else
11853         node = patch_switch_statement (node);
11854
11855       if (node == error_mark_node || TREE_OPERAND (node, 0) == error_mark_node)
11856         nn = error_mark_node;
11857       else
11858         {
11859           TREE_TYPE (nn) = TREE_TYPE (node) = void_type_node;
11860           /* If we returned something different, that's because we
11861              inserted a label. Pop the label too. */
11862           if (nn != node)
11863             {
11864               if (CAN_COMPLETE_NORMALLY (node))
11865                 CAN_COMPLETE_NORMALLY (nn) = 1;
11866               POP_LABELED_BLOCK ();
11867             }
11868         }
11869       POP_LOOP ();
11870       return nn;
11871
11872     case EXIT_EXPR:
11873       TREE_OPERAND (node, 0) = java_complete_tree (TREE_OPERAND (node, 0));
11874       return patch_exit_expr (node);
11875
11876     case COND_EXPR:
11877       /* Condition */
11878       TREE_OPERAND (node, 0) = java_complete_tree (TREE_OPERAND (node, 0));
11879       if (TREE_OPERAND (node, 0) == error_mark_node)
11880         return error_mark_node;
11881       /* then-else branches */
11882       TREE_OPERAND (node, 1) = java_complete_tree (TREE_OPERAND (node, 1));
11883       if (TREE_OPERAND (node, 1) == error_mark_node)
11884         return error_mark_node;
11885       TREE_OPERAND (node, 2) = java_complete_tree (TREE_OPERAND (node, 2));
11886       if (TREE_OPERAND (node, 2) == error_mark_node)
11887         return error_mark_node;
11888       return patch_if_else_statement (node);
11889       break;
11890
11891     case CONDITIONAL_EXPR:
11892       /* Condition */
11893       wfl_op1 = TREE_OPERAND (node, 0);
11894       COMPLETE_CHECK_OP_0 (node);
11895       wfl_op2 = TREE_OPERAND (node, 1);
11896       COMPLETE_CHECK_OP_1 (node);
11897       wfl_op3 = TREE_OPERAND (node, 2);
11898       COMPLETE_CHECK_OP_2 (node);
11899       return patch_conditional_expr (node, wfl_op1, wfl_op2);
11900
11901       /* 3- Expression section */
11902     case COMPOUND_EXPR:
11903       wfl_op2 = TREE_OPERAND (node, 1);
11904       TREE_OPERAND (node, 0) = nn =
11905         java_complete_tree (TREE_OPERAND (node, 0));
11906       if (wfl_op2 == empty_stmt_node)
11907         CAN_COMPLETE_NORMALLY (node) = CAN_COMPLETE_NORMALLY (nn);
11908       else
11909         {
11910           if (! CAN_COMPLETE_NORMALLY (nn) && TREE_CODE (nn) != ERROR_MARK)
11911             {
11912               /* An unreachable condition in a do-while statement
11913                  is *not* (technically) an unreachable statement. */
11914               nn = wfl_op2;
11915               if (TREE_CODE (nn) == EXPR_WITH_FILE_LOCATION)
11916                 nn = EXPR_WFL_NODE (nn);
11917               /* NN can be NULL_TREE exactly when UPDATE is, in
11918                  finish_for_loop.  */
11919               if (nn != NULL_TREE && TREE_CODE (nn) != EXIT_EXPR)
11920                 {
11921                   SET_WFL_OPERATOR (wfl_operator, node, wfl_op2);
11922                   if (SUPPRESS_UNREACHABLE_ERROR (nn))
11923                     {
11924                       /* Perhaps this warning should have an
11925                          associated flag.  The code being compiled is
11926                          pedantically correct, but useless.  */
11927                       parse_warning_context (wfl_operator,
11928                                              "Unreachable statement");
11929                     }
11930                   else
11931                     parse_error_context (wfl_operator,
11932                                          "Unreachable statement");
11933                 }
11934             }
11935           TREE_OPERAND (node, 1) = java_complete_tree (TREE_OPERAND (node, 1));
11936           if (TREE_OPERAND (node, 1) == error_mark_node)
11937             return error_mark_node;
11938           /* Even though we might allow the case where the first
11939              operand doesn't return normally, we still should compute
11940              CAN_COMPLETE_NORMALLY correctly.  */
11941           CAN_COMPLETE_NORMALLY (node)
11942             = (CAN_COMPLETE_NORMALLY (TREE_OPERAND (node, 0))
11943                && CAN_COMPLETE_NORMALLY (TREE_OPERAND (node, 1)));
11944         }
11945       TREE_TYPE (node) = TREE_TYPE (TREE_OPERAND (node, 1));
11946       break;
11947
11948     case RETURN_EXPR:
11949       /* CAN_COMPLETE_NORMALLY (node) = 0; */
11950       return patch_return (node);
11951
11952     case EXPR_WITH_FILE_LOCATION:
11953       if (!EXPR_WFL_NODE (node) /* Or a PRIMARY flag ? */
11954           || TREE_CODE (EXPR_WFL_NODE (node)) == IDENTIFIER_NODE)
11955         {
11956           tree wfl = node;
11957           node = resolve_expression_name (node, NULL);
11958           if (node == error_mark_node)
11959             return node;
11960           /* Keep line number information somewhere were it doesn't
11961              disrupt the completion process. */
11962           if (flag_emit_xref && TREE_CODE (node) != CALL_EXPR)
11963             {
11964               EXPR_WFL_NODE (wfl) = TREE_OPERAND (node, 1);
11965               TREE_OPERAND (node, 1) = wfl;
11966             }
11967           CAN_COMPLETE_NORMALLY (node) = 1;
11968         }
11969       else
11970         {
11971           tree body;
11972           int save_lineno = input_line;
11973           input_line = EXPR_WFL_LINENO (node);
11974           body = java_complete_tree (EXPR_WFL_NODE (node));
11975           input_line = save_lineno;
11976           EXPR_WFL_NODE (node) = body;
11977           TREE_SIDE_EFFECTS (node) = TREE_SIDE_EFFECTS (body);
11978           CAN_COMPLETE_NORMALLY (node) = CAN_COMPLETE_NORMALLY (body);
11979           if (body == empty_stmt_node || TREE_CONSTANT (body))
11980             {
11981               /* Makes it easier to constant fold, detect empty bodies. */
11982               return body;
11983             }
11984           if (body == error_mark_node)
11985             {
11986               /* Its important for the evaluation of assignment that
11987                  this mark on the TREE_TYPE is propagated. */
11988               TREE_TYPE (node) = error_mark_node;
11989               return error_mark_node;
11990             }
11991           else
11992             TREE_TYPE (node) = TREE_TYPE (EXPR_WFL_NODE (node));
11993
11994         }
11995       break;
11996
11997     case NEW_ARRAY_EXPR:
11998       /* Patch all the dimensions */
11999       flag = 0;
12000       for (cn = TREE_OPERAND (node, 1); cn; cn = TREE_CHAIN (cn))
12001         {
12002           int location = EXPR_WFL_LINECOL (TREE_VALUE (cn));
12003           tree dim = convert (int_type_node,
12004                               java_complete_tree (TREE_VALUE (cn)));
12005           if (dim == error_mark_node)
12006             {
12007               flag = 1;
12008               continue;
12009             }
12010           else
12011             {
12012               TREE_VALUE (cn) = dim;
12013               /* Setup the location of the current dimension, for
12014                  later error report. */
12015               TREE_PURPOSE (cn) =
12016                 build_expr_wfl (NULL_TREE, input_filename, 0, 0);
12017               EXPR_WFL_LINECOL (TREE_PURPOSE (cn)) = location;
12018             }
12019         }
12020       /* They complete the array creation expression, if no errors
12021          were found. */
12022       CAN_COMPLETE_NORMALLY (node) = 1;
12023       return (flag ? error_mark_node
12024               : force_evaluation_order (patch_newarray (node)));
12025
12026     case NEW_ANONYMOUS_ARRAY_EXPR:
12027       /* Create the array type if necessary. */
12028       if (ANONYMOUS_ARRAY_DIMS_SIG (node))
12029         {
12030           tree type = ANONYMOUS_ARRAY_BASE_TYPE (node);
12031           if (!(type = resolve_type_during_patch (type)))
12032             return error_mark_node;
12033           type = build_array_from_name (type, NULL_TREE,
12034                                         ANONYMOUS_ARRAY_DIMS_SIG (node), NULL);
12035           ANONYMOUS_ARRAY_BASE_TYPE (node) = build_pointer_type (type);
12036         }
12037       node = patch_new_array_init (ANONYMOUS_ARRAY_BASE_TYPE (node),
12038                                    ANONYMOUS_ARRAY_INITIALIZER (node));
12039       if (node == error_mark_node)
12040         return error_mark_node;
12041       CAN_COMPLETE_NORMALLY (node) = 1;
12042       return node;
12043
12044     case NEW_CLASS_EXPR:
12045     case CALL_EXPR:
12046       /* Complete function's argument(s) first */
12047       if (complete_function_arguments (node))
12048         return error_mark_node;
12049       else
12050         {
12051           tree decl, wfl = TREE_OPERAND (node, 0);
12052           int in_this = CALL_THIS_CONSTRUCTOR_P (node);
12053           int from_super = (EXPR_WFL_NODE (TREE_OPERAND (node, 0)) ==
12054                            super_identifier_node);
12055           tree arguments;
12056           int location = EXPR_WFL_LINECOL (node);
12057
12058           node = patch_method_invocation (node, NULL_TREE, NULL_TREE,
12059                                           from_super, 0, &decl);
12060           if (node == error_mark_node)
12061             return error_mark_node;
12062
12063           if (TREE_CODE (node) == CALL_EXPR
12064               && TREE_OPERAND (node, 1) != NULL_TREE)
12065             arguments = TREE_VALUE (TREE_OPERAND (node, 1));
12066           else
12067             arguments = NULL_TREE;
12068           check_thrown_exceptions (location, decl, arguments);
12069           /* If we call this(...), register signature and positions */
12070           if (in_this)
12071             DECL_CONSTRUCTOR_CALLS (current_function_decl) =
12072               tree_cons (wfl, decl,
12073                          DECL_CONSTRUCTOR_CALLS (current_function_decl));
12074           CAN_COMPLETE_NORMALLY (node) = 1;
12075           return force_evaluation_order (node);
12076         }
12077
12078     case MODIFY_EXPR:
12079       /* Save potential wfls */
12080       wfl_op1 = TREE_OPERAND (node, 0);
12081       TREE_OPERAND (node, 0) = nn = java_complete_lhs (wfl_op1);
12082
12083       if (MODIFY_EXPR_FROM_INITIALIZATION_P (node)
12084           && TREE_CODE (nn) == VAR_DECL && TREE_STATIC (nn)
12085           && DECL_INITIAL (nn) != NULL_TREE)
12086         {
12087           tree value;
12088
12089           value = fold_constant_for_init (nn, nn);
12090
12091           /* When we have a primitype type, or a string and we're not
12092              emitting a class file, we actually don't want to generate
12093              anything for the assignment. */
12094           if (value != NULL_TREE && 
12095               (JPRIMITIVE_TYPE_P (TREE_TYPE (value)) || 
12096                (TREE_TYPE (value) == string_ptr_type_node &&
12097                 ! flag_emit_class_files)))
12098             {
12099               /* Prepare node for patch_assignment */
12100               TREE_OPERAND (node, 1) = value;
12101               /* Call patch assignment to verify the assignment */
12102               if (patch_assignment (node, wfl_op1) == error_mark_node)
12103                 return error_mark_node;
12104               /* Set DECL_INITIAL properly (a conversion might have
12105                  been decided by patch_assignment) and return the
12106                  empty statement. */
12107               else
12108                 {
12109                   tree patched = patch_string (TREE_OPERAND (node, 1));
12110                   if (patched)
12111                     DECL_INITIAL (nn) = patched;
12112                   else
12113                     DECL_INITIAL (nn) = TREE_OPERAND (node, 1);
12114                   DECL_FIELD_FINAL_IUD (nn) = 1;
12115                   return empty_stmt_node;
12116                 }
12117             }
12118           if (! flag_emit_class_files)
12119             DECL_INITIAL (nn) = NULL_TREE;
12120         }
12121       wfl_op2 = TREE_OPERAND (node, 1);
12122
12123       if (TREE_OPERAND (node, 0) == error_mark_node)
12124         return error_mark_node;
12125
12126       flag = COMPOUND_ASSIGN_P (wfl_op2);
12127       if (flag)
12128         {
12129           /* This might break when accessing outer field from inner
12130              class. TESTME, FIXME */
12131           tree lvalue = java_stabilize_reference (TREE_OPERAND (node, 0));
12132
12133           /* Hand stabilize the lhs on both places */
12134           TREE_OPERAND (node, 0) = lvalue;
12135           TREE_OPERAND (TREE_OPERAND (node, 1), 0) =
12136             (flag_emit_class_files ? lvalue : save_expr (lvalue));
12137
12138           /* 15.25.2.a: Left hand is not an array access. FIXME */
12139           /* Now complete the RHS. We write it back later on. */
12140           nn = java_complete_tree (TREE_OPERAND (node, 1));
12141
12142           if ((cn = patch_string (nn)))
12143             nn = cn;
12144
12145           /* The last part of the rewrite for E1 op= E2 is to have
12146              E1 = (T)(E1 op E2), with T being the type of E1. */
12147           nn = java_complete_tree (build_cast (EXPR_WFL_LINECOL (wfl_op2),
12148                                                TREE_TYPE (lvalue), nn));
12149
12150           /* If the assignment is compound and has reference type,
12151              then ensure the LHS has type String and nothing else.  */
12152           if (JREFERENCE_TYPE_P (TREE_TYPE (lvalue))
12153               && ! JSTRING_TYPE_P (TREE_TYPE (lvalue)))
12154             parse_error_context (wfl_op2,
12155                                  "Incompatible type for `+='. Can't convert `%s' to `java.lang.String'",
12156                                  lang_printable_name (TREE_TYPE (lvalue), 0));
12157
12158           /* 15.25.2.b: Left hand is an array access. FIXME */
12159         }
12160
12161       /* If we're about to patch a NEW_ARRAY_INIT, we call a special
12162          function to complete this RHS. Note that a NEW_ARRAY_INIT
12163          might have been already fully expanded if created as a result
12164          of processing an anonymous array initializer. We avoid doing
12165          the operation twice by testing whether the node already bears
12166          a type. */
12167       else if (TREE_CODE (wfl_op2) == NEW_ARRAY_INIT && !TREE_TYPE (wfl_op2))
12168         nn = patch_new_array_init (TREE_TYPE (TREE_OPERAND (node, 0)),
12169                                    TREE_OPERAND (node, 1));
12170       /* Otherwise we simply complete the RHS */
12171       else
12172         nn = java_complete_tree (TREE_OPERAND (node, 1));
12173
12174       if (nn == error_mark_node)
12175         return error_mark_node;
12176
12177       /* Write back the RHS as we evaluated it. */
12178       TREE_OPERAND (node, 1) = nn;
12179
12180       /* In case we're handling = with a String as a RHS, we need to
12181          produce a String out of the RHS (it might still be a
12182          STRING_CST or a StringBuffer at this stage */
12183       if ((nn = patch_string (TREE_OPERAND (node, 1))))
12184         TREE_OPERAND (node, 1) = nn;
12185
12186       if ((nn = outer_field_access_fix (wfl_op1, TREE_OPERAND (node, 0),
12187                                         TREE_OPERAND (node, 1))))
12188         {
12189           /* We return error_mark_node if outer_field_access_fix
12190              detects we write into a final. */
12191           if (nn == error_mark_node)
12192             return error_mark_node;
12193           node = nn;
12194         }
12195       else
12196         {
12197           node = patch_assignment (node, wfl_op1);
12198           if (node == error_mark_node)
12199             return error_mark_node;
12200           /* Reorganize the tree if necessary. */
12201           if (flag && (!JREFERENCE_TYPE_P (TREE_TYPE (node))
12202                        || JSTRING_P (TREE_TYPE (node))))
12203             node = java_refold (node);
12204         }
12205
12206       /* Seek to set DECL_INITIAL to a proper value, since it might have
12207          undergone a conversion in patch_assignment. We do that only when
12208          it's necessary to have DECL_INITIAL properly set. */
12209       nn = TREE_OPERAND (node, 0);
12210       if (TREE_CODE (nn) == VAR_DECL
12211           && DECL_INITIAL (nn) && CONSTANT_VALUE_P (DECL_INITIAL (nn))
12212           && FIELD_STATIC (nn) && FIELD_FINAL (nn)
12213           && (JPRIMITIVE_TYPE_P (TREE_TYPE (nn))
12214               || TREE_TYPE (nn) == string_ptr_type_node))
12215         DECL_INITIAL (nn) = TREE_OPERAND (node, 1);
12216
12217       CAN_COMPLETE_NORMALLY (node) = 1;
12218       return node;
12219
12220     case MULT_EXPR:
12221     case PLUS_EXPR:
12222     case MINUS_EXPR:
12223     case LSHIFT_EXPR:
12224     case RSHIFT_EXPR:
12225     case URSHIFT_EXPR:
12226     case BIT_AND_EXPR:
12227     case BIT_XOR_EXPR:
12228     case BIT_IOR_EXPR:
12229     case TRUNC_MOD_EXPR:
12230     case TRUNC_DIV_EXPR:
12231     case RDIV_EXPR:
12232     case TRUTH_ANDIF_EXPR:
12233     case TRUTH_ORIF_EXPR:
12234     case EQ_EXPR:
12235     case NE_EXPR:
12236     case GT_EXPR:
12237     case GE_EXPR:
12238     case LT_EXPR:
12239     case LE_EXPR:
12240       /* Operands 0 and 1 are WFL in certain cases only. patch_binop
12241          knows how to handle those cases. */
12242       wfl_op1 = TREE_OPERAND (node, 0);
12243       wfl_op2 = TREE_OPERAND (node, 1);
12244
12245       CAN_COMPLETE_NORMALLY (node) = 1;
12246       /* Don't complete string nodes if dealing with the PLUS operand. */
12247       if (TREE_CODE (node) != PLUS_EXPR || !JSTRING_P (wfl_op1))
12248         {
12249           nn = java_complete_tree (wfl_op1);
12250           if (nn == error_mark_node)
12251             return error_mark_node;
12252
12253           TREE_OPERAND (node, 0) = nn;
12254         }
12255       if (TREE_CODE (node) != PLUS_EXPR || !JSTRING_P (wfl_op2))
12256         {
12257           nn = java_complete_tree (wfl_op2);
12258           if (nn == error_mark_node)
12259             return error_mark_node;
12260
12261           TREE_OPERAND (node, 1) = nn;
12262         }
12263       return patch_binop (node, wfl_op1, wfl_op2);
12264
12265     case INSTANCEOF_EXPR:
12266       wfl_op1 = TREE_OPERAND (node, 0);
12267       COMPLETE_CHECK_OP_0 (node);
12268       if (flag_emit_xref)
12269         {
12270           TREE_TYPE (node) = boolean_type_node;
12271           return node;
12272         }
12273       return patch_binop (node, wfl_op1, TREE_OPERAND (node, 1));
12274
12275     case UNARY_PLUS_EXPR:
12276     case NEGATE_EXPR:
12277     case TRUTH_NOT_EXPR:
12278     case BIT_NOT_EXPR:
12279     case PREDECREMENT_EXPR:
12280     case PREINCREMENT_EXPR:
12281     case POSTDECREMENT_EXPR:
12282     case POSTINCREMENT_EXPR:
12283     case CONVERT_EXPR:
12284       /* There are cases were wfl_op1 is a WFL. patch_unaryop knows
12285          how to handle those cases. */
12286       wfl_op1 = TREE_OPERAND (node, 0);
12287       CAN_COMPLETE_NORMALLY (node) = 1;
12288       TREE_OPERAND (node, 0) = java_complete_tree (wfl_op1);
12289       if (TREE_OPERAND (node, 0) == error_mark_node)
12290         return error_mark_node;
12291       node = patch_unaryop (node, wfl_op1);
12292       CAN_COMPLETE_NORMALLY (node) = 1;
12293       break;
12294
12295     case ARRAY_REF:
12296       /* There are cases were wfl_op1 is a WFL. patch_array_ref knows
12297          how to handle those cases. */
12298       wfl_op1 = TREE_OPERAND (node, 0);
12299       TREE_OPERAND (node, 0) = java_complete_tree (wfl_op1);
12300       if (TREE_OPERAND (node, 0) == error_mark_node)
12301         return error_mark_node;
12302       if (!flag_emit_class_files && !flag_emit_xref)
12303         TREE_OPERAND (node, 0) = save_expr (TREE_OPERAND (node, 0));
12304       /* The same applies to wfl_op2 */
12305       wfl_op2 = TREE_OPERAND (node, 1);
12306       TREE_OPERAND (node, 1) = java_complete_tree (wfl_op2);
12307       if (TREE_OPERAND (node, 1) == error_mark_node)
12308         return error_mark_node;
12309       if (!flag_emit_class_files && !flag_emit_xref)
12310         TREE_OPERAND (node, 1) = save_expr (TREE_OPERAND (node, 1));
12311       return patch_array_ref (node);
12312
12313     case RECORD_TYPE:
12314       return node;;
12315
12316     case COMPONENT_REF:
12317       /* The first step in the re-write of qualified name handling.  FIXME.
12318          So far, this is only to support PRIMTYPE.class -> PRIMCLASS.TYPE. */
12319       TREE_OPERAND (node, 0) = java_complete_tree (TREE_OPERAND (node, 0));
12320       if (TREE_CODE (TREE_OPERAND (node, 0)) == RECORD_TYPE)
12321         {
12322           tree name = TREE_OPERAND (node, 1);
12323           tree field = lookup_field_wrapper (TREE_OPERAND (node, 0), name);
12324           if (field == NULL_TREE)
12325             {
12326               error ("missing static field `%s'", IDENTIFIER_POINTER (name));
12327               return error_mark_node;
12328             }
12329           if (! FIELD_STATIC (field))
12330             {
12331               error ("not a static field `%s'", IDENTIFIER_POINTER (name));
12332               return error_mark_node;
12333             }
12334           return field;
12335         }
12336       else
12337         abort ();
12338       break;
12339
12340     case THIS_EXPR:
12341       /* Can't use THIS in a static environment */
12342       if (!current_this)
12343         {
12344           EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
12345           parse_error_context (wfl_operator,
12346                                "Keyword `this' used outside allowed context");
12347           TREE_TYPE (node) = error_mark_node;
12348           return error_mark_node;
12349         }
12350       if (ctxp->explicit_constructor_p)
12351         {
12352           EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
12353           parse_error_context
12354             (wfl_operator, "Can't reference `this' or `super' before the superclass constructor has been called");
12355           TREE_TYPE (node) = error_mark_node;
12356           return error_mark_node;
12357         }
12358       return current_this;
12359
12360     case CLASS_LITERAL:
12361       CAN_COMPLETE_NORMALLY (node) = 1;
12362       node = patch_incomplete_class_ref (node);
12363       if (node == error_mark_node)
12364         return error_mark_node;
12365       break;
12366
12367     default:
12368       CAN_COMPLETE_NORMALLY (node) = 1;
12369       /* Ok: may be we have a STRING_CST or a crafted `StringBuffer'
12370          and it's time to turn it into the appropriate String object */
12371       if ((nn = patch_string (node)))
12372         node = nn;
12373       else
12374         internal_error ("No case for %s", tree_code_name [TREE_CODE (node)]);
12375     }
12376   return node;
12377 }
12378
12379 /* Complete function call's argument. Return a nonzero value is an
12380    error was found.  */
12381
12382 static int
12383 complete_function_arguments (tree node)
12384 {
12385   int flag = 0;
12386   tree cn;
12387
12388   ctxp->explicit_constructor_p += (CALL_EXPLICIT_CONSTRUCTOR_P (node) ? 1 : 0);
12389   for (cn = TREE_OPERAND (node, 1); cn; cn = TREE_CHAIN (cn))
12390     {
12391       tree wfl = TREE_VALUE (cn), parm, temp;
12392       parm = java_complete_tree (wfl);
12393
12394       if (parm == error_mark_node)
12395         {
12396           flag = 1;
12397           continue;
12398         }
12399       /* If have a string literal that we haven't transformed yet or a
12400          crafted string buffer, as a result of use of the the String
12401          `+' operator. Build `parm.toString()' and expand it. */
12402       if ((temp = patch_string (parm)))
12403         parm = temp;
12404
12405       TREE_VALUE (cn) = parm;
12406     }
12407   ctxp->explicit_constructor_p -= (CALL_EXPLICIT_CONSTRUCTOR_P (node) ? 1 : 0);
12408   return flag;
12409 }
12410
12411 /* Sometimes (for loops and variable initialized during their
12412    declaration), we want to wrap a statement around a WFL and turn it
12413    debugable.  */
12414
12415 static tree
12416 build_debugable_stmt (int location, tree stmt)
12417 {
12418   if (TREE_CODE (stmt) != EXPR_WITH_FILE_LOCATION)
12419     {
12420       stmt = build_expr_wfl (stmt, input_filename, 0, 0);
12421       EXPR_WFL_LINECOL (stmt) = location;
12422     }
12423   JAVA_MAYBE_GENERATE_DEBUG_INFO (stmt);
12424   return stmt;
12425 }
12426
12427 static tree
12428 build_expr_block (tree body, tree decls)
12429
12430 {
12431   tree node = make_node (BLOCK);
12432   BLOCK_EXPR_DECLS (node) = decls;
12433   BLOCK_EXPR_BODY (node) = body;
12434   if (body)
12435     TREE_TYPE (node) = TREE_TYPE (body);
12436   TREE_SIDE_EFFECTS (node) = 1;
12437   return node;
12438 }
12439
12440 /* Create a new function block and link it appropriately to current
12441    function block chain */
12442
12443 static tree
12444 enter_block (void)
12445 {
12446   tree b = build_expr_block (NULL_TREE, NULL_TREE);
12447
12448   /* Link block B supercontext to the previous block. The current
12449      function DECL is used as supercontext when enter_a_block is called
12450      for the first time for a given function. The current function body
12451      (DECL_FUNCTION_BODY) is set to be block B.  */
12452
12453   tree fndecl = current_function_decl;
12454
12455   if (!fndecl) {
12456     BLOCK_SUPERCONTEXT (b) = current_static_block;
12457     current_static_block = b;
12458   }
12459
12460   else if (!DECL_FUNCTION_BODY (fndecl))
12461     {
12462       BLOCK_SUPERCONTEXT (b) = fndecl;
12463       DECL_FUNCTION_BODY (fndecl) = b;
12464     }
12465   else
12466     {
12467       BLOCK_SUPERCONTEXT (b) = DECL_FUNCTION_BODY (fndecl);
12468       DECL_FUNCTION_BODY (fndecl) = b;
12469     }
12470   return b;
12471 }
12472
12473 /* Exit a block by changing the current function body
12474    (DECL_FUNCTION_BODY) to the current block super context, only if
12475    the block being exited isn't the method's top level one.  */
12476
12477 static tree
12478 exit_block (void)
12479 {
12480   tree b;
12481   if (current_function_decl)
12482     {
12483       b = DECL_FUNCTION_BODY (current_function_decl);
12484       if (BLOCK_SUPERCONTEXT (b) != current_function_decl)
12485         DECL_FUNCTION_BODY (current_function_decl) = BLOCK_SUPERCONTEXT (b);
12486     }
12487   else
12488     {
12489       b = current_static_block;
12490
12491       if (BLOCK_SUPERCONTEXT (b))
12492         current_static_block = BLOCK_SUPERCONTEXT (b);
12493     }
12494   return b;
12495 }
12496
12497 /* Lookup for NAME in the nested function's blocks, all the way up to
12498    the current toplevel one. It complies with Java's local variable
12499    scoping rules.  */
12500
12501 static tree
12502 lookup_name_in_blocks (tree name)
12503 {
12504   tree b = GET_CURRENT_BLOCK (current_function_decl);
12505
12506   while (b != current_function_decl)
12507     {
12508       tree current;
12509
12510       /* Paranoid sanity check. To be removed */
12511       if (TREE_CODE (b) != BLOCK)
12512         abort ();
12513
12514       for (current = BLOCK_EXPR_DECLS (b); current;
12515            current = TREE_CHAIN (current))
12516         if (DECL_NAME (current) == name)
12517           return current;
12518       b = BLOCK_SUPERCONTEXT (b);
12519     }
12520   return NULL_TREE;
12521 }
12522
12523 static void
12524 maybe_absorb_scoping_blocks (void)
12525 {
12526   while (BLOCK_IS_IMPLICIT (GET_CURRENT_BLOCK (current_function_decl)))
12527     {
12528       tree b = exit_block ();
12529       java_method_add_stmt (current_function_decl, b);
12530       SOURCE_FRONTEND_DEBUG (("Absorbing scoping block at line %d", input_line));
12531     }
12532 }
12533
12534 \f
12535 /* This section of the source is reserved to build_* functions that
12536    are building incomplete tree nodes and the patch_* functions that
12537    are completing them.  */
12538
12539 /* Wrap a non WFL node around a WFL.  */
12540
12541 static tree
12542 build_wfl_wrap (tree node, int location)
12543 {
12544   tree wfl, node_to_insert = node;
12545
12546   /* We want to process THIS . xxx symbolically, to keep it consistent
12547      with the way we're processing SUPER. A THIS from a primary as a
12548      different form than a SUPER. Turn THIS into something symbolic */
12549   if (TREE_CODE (node) == THIS_EXPR)
12550     node_to_insert = wfl = build_wfl_node (this_identifier_node);
12551   else
12552     wfl = build_expr_wfl (NULL_TREE, ctxp->filename, 0, 0);
12553
12554   EXPR_WFL_LINECOL (wfl) = location;
12555   EXPR_WFL_QUALIFICATION (wfl) = build_tree_list (node_to_insert, NULL_TREE);
12556   return wfl;
12557 }
12558
12559 /* Build a super() constructor invocation. Returns empty_stmt_node if
12560    we're currently dealing with the class java.lang.Object. */
12561
12562 static tree
12563 build_super_invocation (tree mdecl)
12564 {
12565   if (DECL_CONTEXT (mdecl) == object_type_node)
12566     return empty_stmt_node;
12567   else
12568     {
12569       tree super_wfl = build_wfl_node (super_identifier_node);
12570       tree a = NULL_TREE, t;
12571       /* If we're dealing with an anonymous class, pass the arguments
12572          of the crafted constructor along. */
12573       if (ANONYMOUS_CLASS_P (DECL_CONTEXT (mdecl)))
12574         {
12575           SKIP_THIS_AND_ARTIFICIAL_PARMS (t, mdecl);
12576           for (; t != end_params_node; t = TREE_CHAIN (t))
12577             a = tree_cons (NULL_TREE, build_wfl_node (TREE_PURPOSE (t)), a);
12578         }
12579       return build_method_invocation (super_wfl, a);
12580     }
12581 }
12582
12583 /* Build a SUPER/THIS qualified method invocation.  */
12584
12585 static tree
12586 build_this_super_qualified_invocation (int use_this, tree name, tree args,
12587                                        int lloc, int rloc)
12588 {
12589   tree invok;
12590   tree wfl =
12591     build_wfl_node (use_this ? this_identifier_node : super_identifier_node);
12592   EXPR_WFL_LINECOL (wfl) = lloc;
12593   invok = build_method_invocation (name, args);
12594   return make_qualified_primary (wfl, invok, rloc);
12595 }
12596
12597 /* Build an incomplete CALL_EXPR node. */
12598
12599 static tree
12600 build_method_invocation (tree name, tree args)
12601 {
12602   tree call = build (CALL_EXPR, NULL_TREE, name, args, NULL_TREE);
12603   TREE_SIDE_EFFECTS (call) = 1;
12604   EXPR_WFL_LINECOL (call) = EXPR_WFL_LINECOL (name);
12605   return call;
12606 }
12607
12608 /* Build an incomplete new xxx(...) node. */
12609
12610 static tree
12611 build_new_invocation (tree name, tree args)
12612 {
12613   tree call = build (NEW_CLASS_EXPR, NULL_TREE, name, args, NULL_TREE);
12614   TREE_SIDE_EFFECTS (call) = 1;
12615   EXPR_WFL_LINECOL (call) = EXPR_WFL_LINECOL (name);
12616   return call;
12617 }
12618
12619 /* Build an incomplete assignment expression. */
12620
12621 static tree
12622 build_assignment (int op, int op_location, tree lhs, tree rhs)
12623 {
12624   tree assignment;
12625   /* Build the corresponding binop if we deal with a Compound
12626      Assignment operator. Mark the binop sub-tree as part of a
12627      Compound Assignment expression */
12628   if (op != ASSIGN_TK)
12629     {
12630       rhs = build_binop (BINOP_LOOKUP (op), op_location, lhs, rhs);
12631       COMPOUND_ASSIGN_P (rhs) = 1;
12632     }
12633   assignment = build (MODIFY_EXPR, NULL_TREE, lhs, rhs);
12634   TREE_SIDE_EFFECTS (assignment) = 1;
12635   EXPR_WFL_LINECOL (assignment) = op_location;
12636   return assignment;
12637 }
12638
12639 /* Print an INTEGER_CST node as decimal in a static buffer, and return
12640    the buffer.  This is used only for string conversion.  */
12641 static char *
12642 string_convert_int_cst (tree node)
12643 {
12644   /* Long.MIN_VALUE is -9223372036854775808, 20 characters.  */
12645   static char buffer[21];
12646
12647   unsigned HOST_WIDE_INT lo = TREE_INT_CST_LOW (node);
12648   unsigned HOST_WIDE_INT hi = TREE_INT_CST_HIGH (node);
12649   char *p = buffer + sizeof (buffer);
12650   int neg = 0;
12651
12652   unsigned HOST_WIDE_INT hibit = (((unsigned HOST_WIDE_INT) 1)
12653                                   << (HOST_BITS_PER_WIDE_INT - 1));
12654
12655   *--p = '\0';
12656
12657   /* If negative, note the fact and negate the value.  */
12658   if ((hi & hibit))
12659     {
12660       lo = ~lo;
12661       hi = ~hi;
12662       if (++lo == 0)
12663         ++hi;
12664       neg = 1;
12665     }
12666
12667   /* Divide by 10 until there are no bits left.  */
12668   do
12669     {
12670       unsigned HOST_WIDE_INT acc = 0;
12671       unsigned HOST_WIDE_INT outhi = 0, outlo = 0;
12672       unsigned int i;
12673
12674       /* Use long division to compute the result and the remainder.  */
12675       for (i = 0; i < 2 * HOST_BITS_PER_WIDE_INT; ++i)
12676         {
12677           /* Shift a bit into accumulator.  */
12678           acc <<= 1;
12679           if ((hi & hibit))
12680             acc |= 1;
12681
12682           /* Shift the value.  */
12683           hi <<= 1;
12684           if ((lo & hibit))
12685             hi |= 1;
12686           lo <<= 1;
12687
12688           /* Shift the correct bit into the result.  */
12689           outhi <<= 1;
12690           if ((outlo & hibit))
12691             outhi |= 1;
12692           outlo <<= 1;
12693           if (acc >= 10)
12694             {
12695               acc -= 10;
12696               outlo |= 1;
12697             }
12698         }
12699
12700       /* '0' == 060 in Java, but might not be here (think EBCDIC).  */
12701       *--p = '\060' + acc;
12702
12703       hi = outhi;
12704       lo = outlo;
12705     }
12706   while (hi || lo);
12707
12708   if (neg)
12709     *--p = '\055'; /* '-' == 055 in Java, but might not be here.  */
12710
12711   return p;
12712 }
12713
12714 /* Print an INTEGER_CST node in a static buffer, and return the
12715    buffer.  This is used only for error handling.  */
12716 char *
12717 print_int_node (tree node)
12718 {
12719   static char buffer [80];
12720   if (TREE_CONSTANT_OVERFLOW (node))
12721     sprintf (buffer, "<overflow>");
12722
12723   if (TREE_INT_CST_HIGH (node) == 0)
12724     sprintf (buffer, HOST_WIDE_INT_PRINT_UNSIGNED,
12725              TREE_INT_CST_LOW (node));
12726   else if (TREE_INT_CST_HIGH (node) == -1
12727            && TREE_INT_CST_LOW (node) != 0)
12728     sprintf (buffer, "-" HOST_WIDE_INT_PRINT_UNSIGNED,
12729              -TREE_INT_CST_LOW (node));
12730   else
12731     sprintf (buffer, HOST_WIDE_INT_PRINT_DOUBLE_HEX,
12732              TREE_INT_CST_HIGH (node), TREE_INT_CST_LOW (node));
12733
12734   return buffer;
12735 }
12736
12737 \f
12738 /* Return 1 if an assignment to a FINAL is attempted in a non suitable
12739    context.  */
12740
12741 /* 15.25 Assignment operators. */
12742
12743 static tree
12744 patch_assignment (tree node, tree wfl_op1)
12745 {
12746   tree rhs = TREE_OPERAND (node, 1);
12747   tree lvalue = TREE_OPERAND (node, 0), llvalue;
12748   tree lhs_type = NULL_TREE, rhs_type, new_rhs = NULL_TREE;
12749   int error_found = 0;
12750   int lvalue_from_array = 0;
12751   int is_return = 0;
12752
12753   EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
12754
12755   /* Lhs can be a named variable */
12756   if (JDECL_P (lvalue))
12757     {
12758       lhs_type = TREE_TYPE (lvalue);
12759     }
12760   /* Or Lhs can be an array access. */
12761   else if (TREE_CODE (lvalue) == ARRAY_REF)
12762     {
12763       lhs_type = TREE_TYPE (lvalue);
12764       lvalue_from_array = 1;
12765     }
12766   /* Or a field access */
12767   else if (TREE_CODE (lvalue) == COMPONENT_REF)
12768     lhs_type = TREE_TYPE (lvalue);
12769   /* Or a function return slot */
12770   else if (TREE_CODE (lvalue) == RESULT_DECL)
12771     {
12772       /* If the return type is an integral type, then we create the
12773          RESULT_DECL with a promoted type, but we need to do these
12774          checks against the unpromoted type to ensure type safety.  So
12775          here we look at the real type, not the type of the decl we
12776          are modifying.  */
12777       lhs_type = TREE_TYPE (TREE_TYPE (current_function_decl));
12778       is_return = 1;
12779     }
12780   /* Otherwise, we might want to try to write into an optimized static
12781      final, this is an of a different nature, reported further on. */
12782   else if (TREE_CODE (wfl_op1) == EXPR_WITH_FILE_LOCATION
12783            && resolve_expression_name (wfl_op1, &llvalue))
12784     {
12785       lhs_type = TREE_TYPE (lvalue);
12786     }
12787   else
12788     {
12789       parse_error_context (wfl_op1, "Invalid left hand side of assignment");
12790       error_found = 1;
12791     }
12792
12793   rhs_type = TREE_TYPE (rhs);
12794
12795   /* 5.1 Try the assignment conversion for builtin type. */
12796   new_rhs = try_builtin_assignconv (wfl_op1, lhs_type, rhs);
12797
12798   /* 5.2 If it failed, try a reference conversion */
12799   if (!new_rhs && (new_rhs = try_reference_assignconv (lhs_type, rhs)))
12800     lhs_type = promote_type (rhs_type);
12801
12802   /* 15.25.2 If we have a compound assignment, convert RHS into the
12803      type of the LHS */
12804   else if (COMPOUND_ASSIGN_P (TREE_OPERAND (node, 1)))
12805     new_rhs = convert (lhs_type, rhs);
12806
12807   /* Explicit cast required. This is an error */
12808   if (!new_rhs)
12809     {
12810       char *t1 = xstrdup (lang_printable_name (TREE_TYPE (rhs), 0));
12811       char *t2 = xstrdup (lang_printable_name (lhs_type, 0));
12812       tree wfl;
12813       char operation [32];      /* Max size known */
12814
12815       /* If the assignment is part of a declaration, we use the WFL of
12816          the declared variable to point out the error and call it a
12817          declaration problem. If the assignment is a genuine =
12818          operator, we call is a operator `=' problem, otherwise we
12819          call it an assignment problem. In both of these last cases,
12820          we use the WFL of the operator to indicate the error. */
12821
12822       if (MODIFY_EXPR_FROM_INITIALIZATION_P (node))
12823         {
12824           wfl = wfl_op1;
12825           strcpy (operation, "declaration");
12826         }
12827       else
12828         {
12829           wfl = wfl_operator;
12830           if (COMPOUND_ASSIGN_P (TREE_OPERAND (node, 1)))
12831             strcpy (operation, "assignment");
12832           else if (is_return)
12833             strcpy (operation, "`return'");
12834           else
12835             strcpy (operation, "`='");
12836         }
12837
12838       if (!valid_cast_to_p (rhs_type, lhs_type))
12839         parse_error_context
12840           (wfl, "Incompatible type for %s. Can't convert `%s' to `%s'",
12841            operation, t1, t2);
12842       else
12843         parse_error_context (wfl, "Incompatible type for %s. Explicit cast needed to convert `%s' to `%s'",
12844                              operation, t1, t2);
12845       free (t1); free (t2);
12846       error_found = 1;
12847     }
12848
12849   if (error_found)
12850     return error_mark_node;
12851
12852   /* If we're processing a `return' statement, promote the actual type
12853      to the promoted type.  */
12854   if (is_return)
12855     new_rhs = convert (TREE_TYPE (lvalue), new_rhs);
12856
12857   /* 10.10: Array Store Exception runtime check */
12858   if (!flag_emit_class_files
12859       && !flag_emit_xref
12860       && lvalue_from_array
12861       && JREFERENCE_TYPE_P (TYPE_ARRAY_ELEMENT (lhs_type)))
12862     {
12863       tree array, store_check, base, index_expr;
12864
12865       /* Save RHS so that it doesn't get re-evaluated by the store check. */
12866       new_rhs = save_expr (new_rhs);
12867
12868       /* Get the INDIRECT_REF. */
12869       array = TREE_OPERAND (TREE_OPERAND (lvalue, 0), 0);
12870       /* Get the array pointer expr. */
12871       array = TREE_OPERAND (array, 0);
12872       store_check = build_java_arraystore_check (array, new_rhs);
12873
12874       index_expr = TREE_OPERAND (lvalue, 1);
12875
12876       if (TREE_CODE (index_expr) == COMPOUND_EXPR)
12877         {
12878           /* A COMPOUND_EXPR here is a bounds check. The bounds check must
12879              happen before the store check, so prepare to insert the store
12880              check within the second operand of the existing COMPOUND_EXPR. */
12881           base = index_expr;
12882         }
12883       else
12884         base = lvalue;
12885
12886       index_expr = TREE_OPERAND (base, 1);
12887       TREE_OPERAND (base, 1) = build (COMPOUND_EXPR, TREE_TYPE (index_expr),
12888                                       store_check, index_expr);
12889     }
12890
12891   /* Final locals can be used as case values in switch
12892      statement. Prepare them for this eventuality. */
12893   if (TREE_CODE (lvalue) == VAR_DECL
12894       && DECL_FINAL (lvalue)
12895       && TREE_CONSTANT (new_rhs)
12896       && IDENTIFIER_LOCAL_VALUE (DECL_NAME (lvalue))
12897       && JINTEGRAL_TYPE_P (TREE_TYPE (lvalue))
12898       )
12899     {
12900       TREE_CONSTANT (lvalue) = 1;
12901       DECL_INITIAL (lvalue) = new_rhs;
12902     }
12903
12904   /* Copy the rhs if it's a reference.  */
12905   if (! flag_check_references && ! flag_emit_class_files && optimize > 0)
12906     {
12907       switch (TREE_CODE (new_rhs))
12908         {
12909         case ARRAY_REF:
12910         case INDIRECT_REF:
12911         case COMPONENT_REF:
12912           /* Transform a = foo.bar 
12913              into a = { int tmp; tmp = foo.bar; tmp; ).              
12914              We need to ensure that if a read from memory fails
12915              because of a NullPointerException, a destination variable
12916              will remain unchanged.  An explicit temporary does what
12917              we need.  
12918
12919              If flag_check_references is set, this is unnecessary
12920              because we'll check each reference before doing any
12921              reads.  If optimize is not set the result will never be
12922              written to a stack slot that contains the LHS.  */
12923           {
12924             tree tmp = build_decl (VAR_DECL, get_identifier ("<tmp>"), 
12925                                    TREE_TYPE (new_rhs));
12926             tree block = make_node (BLOCK);
12927             tree assignment 
12928               = build (MODIFY_EXPR, TREE_TYPE (new_rhs), tmp, fold (new_rhs));
12929             DECL_CONTEXT (tmp) = current_function_decl;
12930             TREE_TYPE (block) = TREE_TYPE (new_rhs);
12931             BLOCK_VARS (block) = tmp;
12932             BLOCK_EXPR_BODY (block) 
12933               = build (COMPOUND_EXPR, TREE_TYPE (new_rhs), assignment, tmp);
12934             TREE_SIDE_EFFECTS (block) = 1;
12935             new_rhs = block;
12936           }
12937           break;
12938         default:
12939           break;
12940         }
12941     }
12942
12943   TREE_OPERAND (node, 0) = lvalue;
12944   TREE_OPERAND (node, 1) = new_rhs;
12945   TREE_TYPE (node) = lhs_type;
12946   return node;
12947 }
12948
12949 /* Check that type SOURCE can be cast into type DEST. If the cast
12950    can't occur at all, return NULL; otherwise, return a possibly
12951    modified rhs.  */
12952
12953 static tree
12954 try_reference_assignconv (tree lhs_type, tree rhs)
12955 {
12956   tree new_rhs = NULL_TREE;
12957   tree rhs_type = TREE_TYPE (rhs);
12958
12959   if (!JPRIMITIVE_TYPE_P (rhs_type) && JREFERENCE_TYPE_P (lhs_type))
12960     {
12961       /* `null' may be assigned to any reference type */
12962       if (rhs == null_pointer_node)
12963         new_rhs = null_pointer_node;
12964       /* Try the reference assignment conversion */
12965       else if (valid_ref_assignconv_cast_p (rhs_type, lhs_type, 0))
12966         new_rhs = rhs;
12967       /* This is a magic assignment that we process differently */
12968       else if (TREE_CODE (rhs) == JAVA_EXC_OBJ_EXPR)
12969         new_rhs = rhs;
12970     }
12971   return new_rhs;
12972 }
12973
12974 /* Check that RHS can be converted into LHS_TYPE by the assignment
12975    conversion (5.2), for the cases of RHS being a builtin type. Return
12976    NULL_TREE if the conversion fails or if because RHS isn't of a
12977    builtin type. Return a converted RHS if the conversion is possible.  */
12978
12979 static tree
12980 try_builtin_assignconv (tree wfl_op1, tree lhs_type, tree rhs)
12981 {
12982   tree new_rhs = NULL_TREE;
12983   tree rhs_type = TREE_TYPE (rhs);
12984
12985   /* Handle boolean specially.  */
12986   if (TREE_CODE (rhs_type) == BOOLEAN_TYPE
12987       || TREE_CODE (lhs_type) == BOOLEAN_TYPE)
12988     {
12989       if (TREE_CODE (rhs_type) == BOOLEAN_TYPE
12990           && TREE_CODE (lhs_type) == BOOLEAN_TYPE)
12991         new_rhs = rhs;
12992     }
12993
12994   /* 5.1.1 Try Identity Conversion,
12995      5.1.2 Try Widening Primitive Conversion */
12996   else if (valid_builtin_assignconv_identity_widening_p (lhs_type, rhs_type))
12997     new_rhs = convert (lhs_type, rhs);
12998
12999   /* Try a narrowing primitive conversion (5.1.3):
13000        - expression is a constant expression of type byte, short, char,
13001          or int, AND
13002        - variable is byte, short or char AND
13003        - The value of the expression is representable in the type of the
13004          variable */
13005   else if ((rhs_type == byte_type_node || rhs_type == short_type_node
13006             || rhs_type == char_type_node || rhs_type == int_type_node)
13007             && TREE_CONSTANT (rhs)
13008            && (lhs_type == byte_type_node || lhs_type == char_type_node
13009                || lhs_type == short_type_node))
13010     {
13011       if (int_fits_type_p (rhs, lhs_type))
13012         new_rhs = convert (lhs_type, rhs);
13013       else if (wfl_op1)         /* Might be called with a NULL */
13014         parse_warning_context
13015           (wfl_op1, "Constant expression `%s' too wide for narrowing primitive conversion to `%s'",
13016            print_int_node (rhs), lang_printable_name (lhs_type, 0));
13017       /* Reported a warning that will turn into an error further
13018          down, so we don't return */
13019     }
13020
13021   return new_rhs;
13022 }
13023
13024 /* Return 1 if RHS_TYPE can be converted to LHS_TYPE by identity
13025    conversion (5.1.1) or widening primitive conversion (5.1.2).  Return
13026    0 is the conversion test fails.  This implements parts the method
13027    invocation conversion (5.3).  */
13028
13029 static int
13030 valid_builtin_assignconv_identity_widening_p (tree lhs_type, tree rhs_type)
13031 {
13032   /* 5.1.1: This is the identity conversion part. */
13033   if (lhs_type == rhs_type)
13034     return 1;
13035
13036   /* Reject non primitive types and boolean conversions.  */
13037   if (!JNUMERIC_TYPE_P (lhs_type) || !JNUMERIC_TYPE_P (rhs_type))
13038     return 0;
13039
13040   /* 5.1.2: widening primitive conversion. byte, even if it's smaller
13041      than a char can't be converted into a char. Short can't too, but
13042      the < test below takes care of that */
13043   if (lhs_type == char_type_node && rhs_type == byte_type_node)
13044     return 0;
13045
13046   /* Accept all promoted type here. Note, we can't use <= in the test
13047      below, because we still need to bounce out assignments of short
13048      to char and the likes */
13049   if (lhs_type == int_type_node
13050       && (rhs_type == promoted_byte_type_node
13051           || rhs_type == promoted_short_type_node
13052           || rhs_type == promoted_char_type_node
13053           || rhs_type == promoted_boolean_type_node))
13054     return 1;
13055
13056   /* From here, an integral is widened if its precision is smaller
13057      than the precision of the LHS or if the LHS is a floating point
13058      type, or the RHS is a float and the RHS a double. */
13059   if ((JINTEGRAL_TYPE_P (rhs_type) && JINTEGRAL_TYPE_P (lhs_type)
13060        && (TYPE_PRECISION (rhs_type) < TYPE_PRECISION (lhs_type)))
13061       || (JINTEGRAL_TYPE_P (rhs_type) && JFLOAT_TYPE_P (lhs_type))
13062       || (rhs_type == float_type_node && lhs_type == double_type_node))
13063     return 1;
13064
13065   return 0;
13066 }
13067
13068 /* Check that something of SOURCE type can be assigned or cast to
13069    something of DEST type at runtime. Return 1 if the operation is
13070    valid, 0 otherwise. If CAST is set to 1, we're treating the case
13071    were SOURCE is cast into DEST, which borrows a lot of the
13072    assignment check. */
13073
13074 static int
13075 valid_ref_assignconv_cast_p (tree source, tree dest, int cast)
13076 {
13077   /* SOURCE or DEST might be null if not from a declared entity. */
13078   if (!source || !dest)
13079     return 0;
13080   if (JNULLP_TYPE_P (source))
13081     return 1;
13082   if (TREE_CODE (source) == POINTER_TYPE)
13083     source = TREE_TYPE (source);
13084   if (TREE_CODE (dest) == POINTER_TYPE)
13085     dest = TREE_TYPE (dest);
13086
13087   /* If source and dest are being compiled from bytecode, they may need to
13088      be loaded. */
13089   if (CLASS_P (source) && !CLASS_LOADED_P (source))
13090     {
13091       load_class (source, 1);
13092       safe_layout_class (source);
13093     }
13094   if (CLASS_P (dest) && !CLASS_LOADED_P (dest))
13095     {
13096       load_class (dest, 1);
13097       safe_layout_class (dest);
13098     }
13099
13100   /* Case where SOURCE is a class type */
13101   if (TYPE_CLASS_P (source))
13102     {
13103       if (TYPE_CLASS_P (dest))
13104         return  (source == dest
13105                  || inherits_from_p (source, dest)
13106                  || (cast && inherits_from_p (dest, source)));
13107       if (TYPE_INTERFACE_P (dest))
13108         {
13109           /* If doing a cast and SOURCE is final, the operation is
13110              always correct a compile time (because even if SOURCE
13111              does not implement DEST, a subclass of SOURCE might). */
13112           if (cast && !CLASS_FINAL (TYPE_NAME (source)))
13113             return 1;
13114           /* Otherwise, SOURCE must implement DEST */
13115           return interface_of_p (dest, source);
13116         }
13117       /* DEST is an array, cast permitted if SOURCE is of Object type */
13118       return (cast && source == object_type_node ? 1 : 0);
13119     }
13120   if (TYPE_INTERFACE_P (source))
13121     {
13122       if (TYPE_CLASS_P (dest))
13123         {
13124           /* If not casting, DEST must be the Object type */
13125           if (!cast)
13126             return dest == object_type_node;
13127           /* We're doing a cast. The cast is always valid is class
13128              DEST is not final, otherwise, DEST must implement SOURCE */
13129           else if (!CLASS_FINAL (TYPE_NAME (dest)))
13130             return 1;
13131           else
13132             return interface_of_p (source, dest);
13133         }
13134       if (TYPE_INTERFACE_P (dest))
13135         {
13136           /* If doing a cast, then if SOURCE and DEST contain method
13137              with the same signature but different return type, then
13138              this is a (compile time) error */
13139           if (cast)
13140             {
13141               tree method_source, method_dest;
13142               tree source_type;
13143               tree source_sig;
13144               tree source_name;
13145               for (method_source = TYPE_METHODS (source); method_source;
13146                    method_source = TREE_CHAIN (method_source))
13147                 {
13148                   source_sig =
13149                     build_java_argument_signature (TREE_TYPE (method_source));
13150                   source_type = TREE_TYPE (TREE_TYPE (method_source));
13151                   source_name = DECL_NAME (method_source);
13152                   for (method_dest = TYPE_METHODS (dest);
13153                        method_dest; method_dest = TREE_CHAIN (method_dest))
13154                     if (source_sig ==
13155                         build_java_argument_signature (TREE_TYPE (method_dest))
13156                         && source_name == DECL_NAME (method_dest)
13157                         && source_type != TREE_TYPE (TREE_TYPE (method_dest)))
13158                       return 0;
13159                 }
13160               return 1;
13161             }
13162           else
13163             return source == dest || interface_of_p (dest, source);
13164         }
13165       else
13166         {
13167           /* Array */
13168           return (cast
13169                   && (DECL_NAME (TYPE_NAME (source))
13170                       == java_lang_cloneable_identifier_node
13171                       || (DECL_NAME (TYPE_NAME (source))
13172                           == java_io_serializable_identifier_node)));
13173         }
13174     }
13175   if (TYPE_ARRAY_P (source))
13176     {
13177       if (TYPE_CLASS_P (dest))
13178         return dest == object_type_node;
13179       /* Can't cast an array to an interface unless the interface is
13180          java.lang.Cloneable or java.io.Serializable.  */
13181       if (TYPE_INTERFACE_P (dest))
13182         return (DECL_NAME (TYPE_NAME (dest))
13183                 == java_lang_cloneable_identifier_node
13184                 || (DECL_NAME (TYPE_NAME (dest))
13185                     == java_io_serializable_identifier_node));
13186       else                      /* Arrays */
13187         {
13188           tree source_element_type = TYPE_ARRAY_ELEMENT (source);
13189           tree dest_element_type = TYPE_ARRAY_ELEMENT (dest);
13190
13191           /* In case of severe errors, they turn out null */
13192           if (!dest_element_type || !source_element_type)
13193             return 0;
13194           if (source_element_type == dest_element_type)
13195             return 1;
13196           return valid_ref_assignconv_cast_p (source_element_type,
13197                                               dest_element_type, cast);
13198         }
13199       return 0;
13200     }
13201   return 0;
13202 }
13203
13204 static int
13205 valid_cast_to_p (tree source, tree dest)
13206 {
13207   if (TREE_CODE (source) == POINTER_TYPE)
13208     source = TREE_TYPE (source);
13209   if (TREE_CODE (dest) == POINTER_TYPE)
13210     dest = TREE_TYPE (dest);
13211
13212   if (TREE_CODE (source) == RECORD_TYPE && TREE_CODE (dest) == RECORD_TYPE)
13213     return valid_ref_assignconv_cast_p (source, dest, 1);
13214
13215   else if (JNUMERIC_TYPE_P (source) && JNUMERIC_TYPE_P (dest))
13216     return 1;
13217
13218   else if (TREE_CODE (source) == BOOLEAN_TYPE
13219            && TREE_CODE (dest) == BOOLEAN_TYPE)
13220     return 1;
13221
13222   return 0;
13223 }
13224
13225 static tree
13226 do_unary_numeric_promotion (tree arg)
13227 {
13228   tree type = TREE_TYPE (arg);
13229   if ((TREE_CODE (type) == INTEGER_TYPE && TYPE_PRECISION (type) < 32)
13230       || TREE_CODE (type) == CHAR_TYPE)
13231     arg = convert (int_type_node, arg);
13232   return arg;
13233 }
13234
13235 /* Return a nonzero value if SOURCE can be converted into DEST using
13236    the method invocation conversion rule (5.3).  */
13237 static int
13238 valid_method_invocation_conversion_p (tree dest, tree source)
13239 {
13240   return ((JPRIMITIVE_TYPE_P (source) && JPRIMITIVE_TYPE_P (dest)
13241            && valid_builtin_assignconv_identity_widening_p (dest, source))
13242           || ((JREFERENCE_TYPE_P (source) || JNULLP_TYPE_P (source))
13243               && (JREFERENCE_TYPE_P (dest) || JNULLP_TYPE_P (dest))
13244               && valid_ref_assignconv_cast_p (source, dest, 0)));
13245 }
13246
13247 /* Build an incomplete binop expression. */
13248
13249 static tree
13250 build_binop (enum tree_code op, int op_location, tree op1, tree op2)
13251 {
13252   tree binop = build (op, NULL_TREE, op1, op2);
13253   TREE_SIDE_EFFECTS (binop) = 1;
13254   /* Store the location of the operator, for better error report. The
13255      string of the operator will be rebuild based on the OP value. */
13256   EXPR_WFL_LINECOL (binop) = op_location;
13257   return binop;
13258 }
13259
13260 /* Build the string of the operator retained by NODE. If NODE is part
13261    of a compound expression, add an '=' at the end of the string. This
13262    function is called when an error needs to be reported on an
13263    operator. The string is returned as a pointer to a static character
13264    buffer. */
13265
13266 static char *
13267 operator_string (tree node)
13268 {
13269 #define BUILD_OPERATOR_STRING(S)                                        \
13270   {                                                                     \
13271     sprintf (buffer, "%s%s", S, (COMPOUND_ASSIGN_P (node) ? "=" : "")); \
13272     return buffer;                                                      \
13273   }
13274
13275   static char buffer [10];
13276   switch (TREE_CODE (node))
13277     {
13278     case MULT_EXPR: BUILD_OPERATOR_STRING ("*");
13279     case RDIV_EXPR: BUILD_OPERATOR_STRING ("/");
13280     case TRUNC_MOD_EXPR: BUILD_OPERATOR_STRING ("%");
13281     case PLUS_EXPR: BUILD_OPERATOR_STRING ("+");
13282     case MINUS_EXPR: BUILD_OPERATOR_STRING ("-");
13283     case LSHIFT_EXPR: BUILD_OPERATOR_STRING ("<<");
13284     case RSHIFT_EXPR: BUILD_OPERATOR_STRING (">>");
13285     case URSHIFT_EXPR: BUILD_OPERATOR_STRING (">>>");
13286     case BIT_AND_EXPR: BUILD_OPERATOR_STRING ("&");
13287     case BIT_XOR_EXPR: BUILD_OPERATOR_STRING ("^");
13288     case BIT_IOR_EXPR: BUILD_OPERATOR_STRING ("|");
13289     case TRUTH_ANDIF_EXPR: BUILD_OPERATOR_STRING ("&&");
13290     case TRUTH_ORIF_EXPR: BUILD_OPERATOR_STRING ("||");
13291     case EQ_EXPR: BUILD_OPERATOR_STRING ("==");
13292     case NE_EXPR: BUILD_OPERATOR_STRING ("!=");
13293     case GT_EXPR: BUILD_OPERATOR_STRING (">");
13294     case GE_EXPR: BUILD_OPERATOR_STRING (">=");
13295     case LT_EXPR: BUILD_OPERATOR_STRING ("<");
13296     case LE_EXPR: BUILD_OPERATOR_STRING ("<=");
13297     case UNARY_PLUS_EXPR: BUILD_OPERATOR_STRING ("+");
13298     case NEGATE_EXPR: BUILD_OPERATOR_STRING ("-");
13299     case TRUTH_NOT_EXPR: BUILD_OPERATOR_STRING ("!");
13300     case BIT_NOT_EXPR: BUILD_OPERATOR_STRING ("~");
13301     case PREINCREMENT_EXPR:     /* Fall through */
13302     case POSTINCREMENT_EXPR: BUILD_OPERATOR_STRING ("++");
13303     case PREDECREMENT_EXPR:     /* Fall through */
13304     case POSTDECREMENT_EXPR: BUILD_OPERATOR_STRING ("--");
13305     default:
13306       internal_error ("unregistered operator %s",
13307                       tree_code_name [TREE_CODE (node)]);
13308     }
13309   return NULL;
13310 #undef BUILD_OPERATOR_STRING
13311 }
13312
13313 /* Return 1 if VAR_ACCESS1 is equivalent to VAR_ACCESS2.  */
13314
13315 static int
13316 java_decl_equiv (tree var_acc1, tree var_acc2)
13317 {
13318   if (JDECL_P (var_acc1))
13319     return (var_acc1 == var_acc2);
13320
13321   return (TREE_CODE (var_acc1) == COMPONENT_REF
13322           && TREE_CODE (var_acc2) == COMPONENT_REF
13323           && TREE_OPERAND (TREE_OPERAND (var_acc1, 0), 0)
13324              == TREE_OPERAND (TREE_OPERAND (var_acc2, 0), 0)
13325           && TREE_OPERAND (var_acc1, 1) == TREE_OPERAND (var_acc2, 1));
13326 }
13327
13328 /* Return a nonzero value if CODE is one of the operators that can be
13329    used in conjunction with the `=' operator in a compound assignment.  */
13330
13331 static int
13332 binop_compound_p (enum tree_code code)
13333 {
13334   int i;
13335   for (i = 0; i < BINOP_COMPOUND_CANDIDATES; i++)
13336     if (binop_lookup [i] == code)
13337       break;
13338
13339   return i < BINOP_COMPOUND_CANDIDATES;
13340 }
13341
13342 /* Reorganize after a fold to get SAVE_EXPR to generate what we want.  */
13343
13344 static tree
13345 java_refold (tree t)
13346 {
13347   tree c, b, ns, decl;
13348
13349   if (TREE_CODE (t) != MODIFY_EXPR)
13350     return t;
13351
13352   c = TREE_OPERAND (t, 1);
13353   if (! (c && TREE_CODE (c) == COMPOUND_EXPR
13354          && TREE_CODE (TREE_OPERAND (c, 0)) == MODIFY_EXPR
13355          && binop_compound_p (TREE_CODE (TREE_OPERAND (c, 1)))))
13356     return t;
13357
13358   /* Now the left branch of the binary operator. */
13359   b = TREE_OPERAND (TREE_OPERAND (c, 1), 0);
13360   if (! (b && TREE_CODE (b) == NOP_EXPR
13361          && TREE_CODE (TREE_OPERAND (b, 0)) == SAVE_EXPR))
13362     return t;
13363
13364   ns = TREE_OPERAND (TREE_OPERAND (b, 0), 0);
13365   if (! (ns && TREE_CODE (ns) == NOP_EXPR
13366          && TREE_CODE (TREE_OPERAND (ns, 0)) == SAVE_EXPR))
13367     return t;
13368
13369   decl = TREE_OPERAND (TREE_OPERAND (ns, 0), 0);
13370   if ((JDECL_P (decl) || TREE_CODE (decl) == COMPONENT_REF)
13371       /* It's got to be the an equivalent decl */
13372       && java_decl_equiv (decl, TREE_OPERAND (TREE_OPERAND (c, 0), 0)))
13373     {
13374       /* Shorten the NOP_EXPR/SAVE_EXPR path. */
13375       TREE_OPERAND (TREE_OPERAND (c, 1), 0) = TREE_OPERAND (ns, 0);
13376       /* Substitute the COMPOUND_EXPR by the BINOP_EXPR */
13377       TREE_OPERAND (t, 1) = TREE_OPERAND (c, 1);
13378       /* Change the right part of the BINOP_EXPR */
13379       TREE_OPERAND (TREE_OPERAND (t, 1), 1) = TREE_OPERAND (c, 0);
13380     }
13381
13382   return t;
13383 }
13384
13385 /* Binary operators (15.16 up to 15.18). We return error_mark_node on
13386    errors but we modify NODE so that it contains the type computed
13387    according to the expression, when it's fixed. Otherwise, we write
13388    error_mark_node as the type. It allows us to further the analysis
13389    of remaining nodes and detects more errors in certain cases.  */
13390
13391 static tree
13392 patch_binop (tree node, tree wfl_op1, tree wfl_op2)
13393 {
13394   tree op1 = TREE_OPERAND (node, 0);
13395   tree op2 = TREE_OPERAND (node, 1);
13396   tree op1_type = TREE_TYPE (op1);
13397   tree op2_type = TREE_TYPE (op2);
13398   tree prom_type = NULL_TREE, cn;
13399   enum tree_code code = TREE_CODE (node);
13400
13401   /* If 1, tell the routine that we have to return error_mark_node
13402      after checking for the initialization of the RHS */
13403   int error_found = 0;
13404
13405   EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
13406
13407   /* If either op<n>_type are NULL, this might be early signs of an
13408      error situation, unless it's too early to tell (in case we're
13409      handling a `+', `==', `!=' or `instanceof'.) We want to set op<n>_type
13410      correctly so the error can be later on reported accurately. */
13411   if (! (code == PLUS_EXPR || code == NE_EXPR
13412          || code == EQ_EXPR || code == INSTANCEOF_EXPR))
13413     {
13414       tree n;
13415       if (! op1_type)
13416         {
13417           n = java_complete_tree (op1);
13418           op1_type = TREE_TYPE (n);
13419         }
13420       if (! op2_type)
13421         {
13422           n = java_complete_tree (op2);
13423           op2_type = TREE_TYPE (n);
13424         }
13425     }
13426
13427   switch (code)
13428     {
13429     /* 15.16 Multiplicative operators */
13430     case MULT_EXPR:             /* 15.16.1 Multiplication Operator * */
13431     case RDIV_EXPR:             /* 15.16.2 Division Operator / */
13432     case TRUNC_DIV_EXPR:        /* 15.16.2 Integral type Division Operator / */
13433     case TRUNC_MOD_EXPR:        /* 15.16.3 Remainder operator % */
13434       if (!JNUMERIC_TYPE_P (op1_type) || !JNUMERIC_TYPE_P (op2_type))
13435         {
13436           if (!JNUMERIC_TYPE_P (op1_type))
13437             ERROR_CANT_CONVERT_TO_NUMERIC (wfl_operator, node, op1_type);
13438           if (!JNUMERIC_TYPE_P (op2_type) && (op1_type != op2_type))
13439             ERROR_CANT_CONVERT_TO_NUMERIC (wfl_operator, node, op2_type);
13440           TREE_TYPE (node) = error_mark_node;
13441           error_found = 1;
13442           break;
13443         }
13444       prom_type = binary_numeric_promotion (op1_type, op2_type, &op1, &op2);
13445
13446       /* Detect integral division by zero */
13447       if ((code == RDIV_EXPR || code == TRUNC_MOD_EXPR)
13448           && TREE_CODE (prom_type) == INTEGER_TYPE
13449           && (op2 == integer_zero_node || op2 == long_zero_node ||
13450               (TREE_CODE (op2) == INTEGER_CST &&
13451                ! TREE_INT_CST_LOW (op2)  && ! TREE_INT_CST_HIGH (op2))))
13452         {
13453           parse_warning_context (wfl_operator, "Evaluating this expression will result in an arithmetic exception being thrown");
13454           TREE_CONSTANT (node) = 0;
13455         }
13456
13457       /* Change the division operator if necessary */
13458       if (code == RDIV_EXPR && TREE_CODE (prom_type) == INTEGER_TYPE)
13459         TREE_SET_CODE (node, TRUNC_DIV_EXPR);
13460
13461       /* Before divisions as is disappear, try to simplify and bail if
13462          applicable, otherwise we won't perform even simple
13463          simplifications like (1-1)/3. We can't do that with floating
13464          point number, folds can't handle them at this stage. */
13465       if (code == RDIV_EXPR && TREE_CONSTANT (op1) && TREE_CONSTANT (op2)
13466           && JINTEGRAL_TYPE_P (op1) && JINTEGRAL_TYPE_P (op2))
13467         {
13468           TREE_TYPE (node) = prom_type;
13469           node = fold (node);
13470           if (TREE_CODE (node) != code)
13471             return node;
13472         }
13473
13474       if (TREE_CODE (prom_type) == INTEGER_TYPE
13475           && flag_use_divide_subroutine
13476           && ! flag_emit_class_files
13477           && (code == RDIV_EXPR || code == TRUNC_MOD_EXPR))
13478         return build_java_soft_divmod (TREE_CODE (node), prom_type, op1, op2);
13479
13480       /* This one is more complicated. FLOATs are processed by a
13481          function call to soft_fmod. Duplicate the value of the
13482          COMPOUND_ASSIGN_P flag. */
13483       if (code == TRUNC_MOD_EXPR)
13484         {
13485           tree mod = build_java_binop (TRUNC_MOD_EXPR, prom_type, op1, op2);
13486           COMPOUND_ASSIGN_P (mod) = COMPOUND_ASSIGN_P (node);
13487           TREE_SIDE_EFFECTS (mod)
13488             = TREE_SIDE_EFFECTS (op1) | TREE_SIDE_EFFECTS (op2);
13489           return mod;
13490         }
13491       break;
13492
13493     /* 15.17 Additive Operators */
13494     case PLUS_EXPR:             /* 15.17.1 String Concatenation Operator + */
13495
13496       /* Operation is valid if either one argument is a string
13497          constant, a String object or a StringBuffer crafted for the
13498          purpose of the a previous usage of the String concatenation
13499          operator */
13500
13501       if (TREE_CODE (op1) == STRING_CST
13502           || TREE_CODE (op2) == STRING_CST
13503           || JSTRING_TYPE_P (op1_type)
13504           || JSTRING_TYPE_P (op2_type)
13505           || IS_CRAFTED_STRING_BUFFER_P (op1)
13506           || IS_CRAFTED_STRING_BUFFER_P (op2))
13507         return build_string_concatenation (op1, op2);
13508
13509     case MINUS_EXPR:            /* 15.17.2 Additive Operators (+ and -) for
13510                                    Numeric Types */
13511       if (!JNUMERIC_TYPE_P (op1_type) || !JNUMERIC_TYPE_P (op2_type))
13512         {
13513           if (!JNUMERIC_TYPE_P (op1_type))
13514             ERROR_CANT_CONVERT_TO_NUMERIC (wfl_operator, node, op1_type);
13515           if (!JNUMERIC_TYPE_P (op2_type) && (op1_type != op2_type))
13516             ERROR_CANT_CONVERT_TO_NUMERIC (wfl_operator, node, op2_type);
13517           TREE_TYPE (node) = error_mark_node;
13518           error_found = 1;
13519           break;
13520         }
13521       prom_type = binary_numeric_promotion (op1_type, op2_type, &op1, &op2);
13522       break;
13523
13524     /* 15.18 Shift Operators */
13525     case LSHIFT_EXPR:
13526     case RSHIFT_EXPR:
13527     case URSHIFT_EXPR:
13528       if (!JINTEGRAL_TYPE_P (op1_type) || !JINTEGRAL_TYPE_P (op2_type))
13529         {
13530           if (!JINTEGRAL_TYPE_P (op1_type))
13531             ERROR_CAST_NEEDED_TO_INTEGRAL (wfl_operator, node, op1_type);
13532           else
13533             {
13534               if (JNUMERIC_TYPE_P (op2_type))
13535                 parse_error_context (wfl_operator,
13536                                      "Incompatible type for `%s'. Explicit cast needed to convert shift distance from `%s' to integral",
13537                                      operator_string (node),
13538                                      lang_printable_name (op2_type, 0));
13539               else
13540                 parse_error_context (wfl_operator,
13541                                      "Incompatible type for `%s'. Can't convert shift distance from `%s' to integral",
13542                                      operator_string (node),
13543                                      lang_printable_name (op2_type, 0));
13544             }
13545           TREE_TYPE (node) = error_mark_node;
13546           error_found = 1;
13547           break;
13548         }
13549
13550       /* Unary numeric promotion (5.6.1) is performed on each operand
13551          separately */
13552       op1 = do_unary_numeric_promotion (op1);
13553       op2 = do_unary_numeric_promotion (op2);
13554
13555       /* If the right hand side is of type `long', first cast it to
13556          `int'.  */
13557       if (TREE_TYPE (op2) == long_type_node)
13558         op2 = build1 (CONVERT_EXPR, int_type_node, op2);
13559
13560       /* The type of the shift expression is the type of the promoted
13561          type of the left-hand operand */
13562       prom_type = TREE_TYPE (op1);
13563
13564       /* Shift int only up to 0x1f and long up to 0x3f */
13565       if (prom_type == int_type_node)
13566         op2 = fold (build (BIT_AND_EXPR, int_type_node, op2,
13567                            build_int_2 (0x1f, 0)));
13568       else
13569         op2 = fold (build (BIT_AND_EXPR, int_type_node, op2,
13570                            build_int_2 (0x3f, 0)));
13571
13572       /* The >>> operator is a >> operating on unsigned quantities */
13573       if (code == URSHIFT_EXPR && ! flag_emit_class_files)
13574         {
13575           tree to_return;
13576           tree utype = java_unsigned_type (prom_type);
13577           op1 = convert (utype, op1);
13578           TREE_SET_CODE (node, RSHIFT_EXPR);
13579           TREE_OPERAND (node, 0) = op1;
13580           TREE_OPERAND (node, 1) = op2;
13581           TREE_TYPE (node) = utype;
13582           to_return = convert (prom_type, node);
13583           /* Copy the original value of the COMPOUND_ASSIGN_P flag */
13584           COMPOUND_ASSIGN_P (to_return) = COMPOUND_ASSIGN_P (node);
13585           TREE_SIDE_EFFECTS (to_return)
13586             = TREE_SIDE_EFFECTS (op1) | TREE_SIDE_EFFECTS (op2);
13587           return to_return;
13588         }
13589       break;
13590
13591       /* 15.19.1 Type Comparison Operator instanceof */
13592     case INSTANCEOF_EXPR:
13593
13594       TREE_TYPE (node) = boolean_type_node;
13595
13596       /* OP1_TYPE might be NULL when OP1 is a string constant.  */
13597       if ((cn = patch_string (op1)))
13598         {
13599           op1 = cn;
13600           op1_type = TREE_TYPE (op1);
13601         }
13602       if (op1_type == NULL_TREE)
13603         abort ();
13604
13605       if (!(op2_type = resolve_type_during_patch (op2)))
13606         return error_mark_node;
13607
13608       /* The first operand must be a reference type or the null type */
13609       if (!JREFERENCE_TYPE_P (op1_type) && op1 != null_pointer_node)
13610         error_found = 1;        /* Error reported further below */
13611
13612       /* The second operand must be a reference type */
13613       if (!JREFERENCE_TYPE_P (op2_type))
13614         {
13615           SET_WFL_OPERATOR (wfl_operator, node, wfl_op2);
13616           parse_error_context
13617             (wfl_operator, "Invalid argument `%s' for `instanceof'",
13618              lang_printable_name (op2_type, 0));
13619           error_found = 1;
13620         }
13621
13622       if (!error_found && valid_ref_assignconv_cast_p (op1_type, op2_type, 1))
13623         {
13624           /* If the first operand is null, the result is always false */
13625           if (op1 == null_pointer_node)
13626             return boolean_false_node;
13627           else if (flag_emit_class_files)
13628             {
13629               TREE_OPERAND (node, 1) = op2_type;
13630               TREE_SIDE_EFFECTS (node) = TREE_SIDE_EFFECTS (op1);
13631               return node;
13632             }
13633           /* Otherwise we have to invoke instance of to figure it out */
13634           else
13635             return build_instanceof (op1, op2_type);
13636         }
13637       /* There is no way the expression operand can be an instance of
13638          the type operand. This is a compile time error. */
13639       else
13640         {
13641           char *t1 = xstrdup (lang_printable_name (op1_type, 0));
13642           SET_WFL_OPERATOR (wfl_operator, node, wfl_op1);
13643           parse_error_context
13644             (wfl_operator, "Impossible for `%s' to be instance of `%s'",
13645              t1, lang_printable_name (op2_type, 0));
13646           free (t1);
13647           error_found = 1;
13648         }
13649
13650       break;
13651
13652       /* 15.21 Bitwise and Logical Operators */
13653     case BIT_AND_EXPR:
13654     case BIT_XOR_EXPR:
13655     case BIT_IOR_EXPR:
13656       if (JINTEGRAL_TYPE_P (op1_type) && JINTEGRAL_TYPE_P (op2_type))
13657         /* Binary numeric promotion is performed on both operand and the
13658            expression retain that type */
13659         prom_type = binary_numeric_promotion (op1_type, op2_type, &op1, &op2);
13660
13661       else if (TREE_CODE (op1_type) == BOOLEAN_TYPE
13662                && TREE_CODE (op1_type) == BOOLEAN_TYPE)
13663         /* The type of the bitwise operator expression is BOOLEAN */
13664         prom_type = boolean_type_node;
13665       else
13666         {
13667           if (!JINTEGRAL_TYPE_P (op1_type))
13668             ERROR_CAST_NEEDED_TO_INTEGRAL (wfl_operator, node, op1_type);
13669           if (!JINTEGRAL_TYPE_P (op2_type) && (op1_type != op2_type))
13670             ERROR_CAST_NEEDED_TO_INTEGRAL (wfl_operator, node, op2_type);
13671           TREE_TYPE (node) = error_mark_node;
13672           error_found = 1;
13673           /* Insert a break here if adding thing before the switch's
13674              break for this case */
13675         }
13676       break;
13677
13678       /* 15.22 Conditional-And Operator */
13679     case TRUTH_ANDIF_EXPR:
13680       /* 15.23 Conditional-Or Operator */
13681     case TRUTH_ORIF_EXPR:
13682       /* Operands must be of BOOLEAN type */
13683       if (TREE_CODE (op1_type) != BOOLEAN_TYPE ||
13684           TREE_CODE (op2_type) != BOOLEAN_TYPE)
13685         {
13686           if (TREE_CODE (op1_type) != BOOLEAN_TYPE)
13687             ERROR_CANT_CONVERT_TO_BOOLEAN (wfl_operator, node, op1_type);
13688           if (TREE_CODE (op2_type) != BOOLEAN_TYPE && (op1_type != op2_type))
13689             ERROR_CANT_CONVERT_TO_BOOLEAN (wfl_operator, node, op2_type);
13690           TREE_TYPE (node) = boolean_type_node;
13691           error_found = 1;
13692           break;
13693         }
13694       else if (integer_zerop (op1))
13695         {
13696           return code == TRUTH_ANDIF_EXPR ? op1 : op2;
13697         }
13698       else if (integer_onep (op1))
13699         {
13700           return code == TRUTH_ANDIF_EXPR ? op2 : op1;
13701         }
13702       /* The type of the conditional operators is BOOLEAN */
13703       prom_type = boolean_type_node;
13704       break;
13705
13706       /* 15.19.1 Numerical Comparison Operators <, <=, >, >= */
13707     case LT_EXPR:
13708     case GT_EXPR:
13709     case LE_EXPR:
13710     case GE_EXPR:
13711       /* The type of each of the operands must be a primitive numeric
13712          type */
13713       if (!JNUMERIC_TYPE_P (op1_type) || ! JNUMERIC_TYPE_P (op2_type))
13714         {
13715           if (!JNUMERIC_TYPE_P (op1_type))
13716             ERROR_CANT_CONVERT_TO_NUMERIC (wfl_operator, node, op1_type);
13717           if (!JNUMERIC_TYPE_P (op2_type) && (op1_type != op2_type))
13718             ERROR_CANT_CONVERT_TO_NUMERIC (wfl_operator, node, op2_type);
13719           TREE_TYPE (node) = boolean_type_node;
13720           error_found = 1;
13721           break;
13722         }
13723       /* Binary numeric promotion is performed on the operands */
13724       binary_numeric_promotion (op1_type, op2_type, &op1, &op2);
13725       /* The type of the relation expression is always BOOLEAN */
13726       prom_type = boolean_type_node;
13727       break;
13728
13729       /* 15.20 Equality Operator */
13730     case EQ_EXPR:
13731     case NE_EXPR:
13732       /* It's time for us to patch the strings. */
13733       if ((cn = patch_string (op1)))
13734        {
13735          op1 = cn;
13736          op1_type = TREE_TYPE (op1);
13737        }
13738       if ((cn = patch_string (op2)))
13739        {
13740          op2 = cn;
13741          op2_type = TREE_TYPE (op2);
13742        }
13743
13744       /* 15.20.1 Numerical Equality Operators == and != */
13745       /* Binary numeric promotion is performed on the operands */
13746       if (JNUMERIC_TYPE_P (op1_type) && JNUMERIC_TYPE_P (op2_type))
13747         binary_numeric_promotion (op1_type, op2_type, &op1, &op2);
13748
13749       /* 15.20.2 Boolean Equality Operators == and != */
13750       else if (TREE_CODE (op1_type) == BOOLEAN_TYPE &&
13751           TREE_CODE (op2_type) == BOOLEAN_TYPE)
13752         ;                       /* Nothing to do here */
13753
13754       /* 15.20.3 Reference Equality Operators == and != */
13755       /* Types have to be either references or the null type. If
13756          they're references, it must be possible to convert either
13757          type to the other by casting conversion. */
13758       else if (op1 == null_pointer_node || op2 == null_pointer_node
13759                || (JREFERENCE_TYPE_P (op1_type) && JREFERENCE_TYPE_P (op2_type)
13760                    && (valid_ref_assignconv_cast_p (op1_type, op2_type, 1)
13761                        || valid_ref_assignconv_cast_p (op2_type,
13762                                                        op1_type, 1))))
13763         ;                       /* Nothing to do here */
13764
13765       /* Else we have an error figure what can't be converted into
13766          what and report the error */
13767       else
13768         {
13769           char *t1;
13770           t1 = xstrdup (lang_printable_name (op1_type, 0));
13771           parse_error_context
13772             (wfl_operator,
13773              "Incompatible type for `%s'. Can't convert `%s' to `%s'",
13774              operator_string (node), t1,
13775              lang_printable_name (op2_type, 0));
13776           free (t1);
13777           TREE_TYPE (node) = boolean_type_node;
13778           error_found = 1;
13779           break;
13780         }
13781       prom_type = boolean_type_node;
13782       break;
13783     default:
13784       abort ();
13785     }
13786
13787   if (error_found)
13788     return error_mark_node;
13789
13790   TREE_OPERAND (node, 0) = op1;
13791   TREE_OPERAND (node, 1) = op2;
13792   TREE_TYPE (node) = prom_type;
13793   TREE_SIDE_EFFECTS (node) = TREE_SIDE_EFFECTS (op1) | TREE_SIDE_EFFECTS (op2);
13794
13795   if (flag_emit_xref)
13796     return node;
13797
13798   /* fold does not respect side-effect order as required for Java but not C.
13799    * Also, it sometimes create SAVE_EXPRs which are bad when emitting
13800    * bytecode.
13801    */
13802   if (flag_emit_class_files ? (TREE_CONSTANT (op1) && TREE_CONSTANT (op2))
13803       : ! TREE_SIDE_EFFECTS (node))
13804     node = fold (node);
13805   return node;
13806 }
13807
13808 /* Concatenate the STRING_CST CSTE and STRING. When AFTER is a non
13809    zero value, the value of CSTE comes after the valude of STRING */
13810
13811 static tree
13812 do_merge_string_cste (tree cste, const char *string, int string_len, int after)
13813 {
13814   const char *old = TREE_STRING_POINTER (cste);
13815   int old_len = TREE_STRING_LENGTH (cste);
13816   int len = old_len + string_len;
13817   char *new = alloca (len+1);
13818
13819   if (after)
13820     {
13821       memcpy (new, string, string_len);
13822       memcpy (&new [string_len], old, old_len);
13823     }
13824   else
13825     {
13826       memcpy (new, old, old_len);
13827       memcpy (&new [old_len], string, string_len);
13828     }
13829   new [len] = '\0';
13830   return build_string (len, new);
13831 }
13832
13833 /* Tries to merge OP1 (a STRING_CST) and OP2 (if suitable). Return a
13834    new STRING_CST on success, NULL_TREE on failure.  */
13835
13836 static tree
13837 merge_string_cste (tree op1, tree op2, int after)
13838 {
13839   /* Handle two string constants right away.  */
13840   if (TREE_CODE (op2) == STRING_CST)
13841     return do_merge_string_cste (op1, TREE_STRING_POINTER (op2),
13842                                  TREE_STRING_LENGTH (op2), after);
13843
13844   /* Reasonable integer constant can be treated right away.  */
13845   if (TREE_CODE (op2) == INTEGER_CST && !TREE_CONSTANT_OVERFLOW (op2))
13846     {
13847       static const char *const boolean_true = "true";
13848       static const char *const boolean_false = "false";
13849       static const char *const null_pointer = "null";
13850       char ch[4];
13851       const char *string;
13852
13853       if (op2 == boolean_true_node)
13854         string = boolean_true;
13855       else if (op2 == boolean_false_node)
13856         string = boolean_false;
13857       else if (op2 == null_pointer_node
13858                || (integer_zerop (op2)
13859                    && TREE_CODE (TREE_TYPE (op2)) == POINTER_TYPE))
13860         /* FIXME: null is not a compile-time constant, so it is only safe to
13861            merge if the overall expression is non-constant. However, this
13862            code always merges without checking the overall expression.  */
13863         string = null_pointer;
13864       else if (TREE_TYPE (op2) == char_type_node)
13865         {
13866           /* Convert the character into UTF-8.  */
13867           unsigned int c = (unsigned int) TREE_INT_CST_LOW (op2);
13868           unsigned char *p = (unsigned char *) ch;
13869           if (0x01 <= c && c <= 0x7f)
13870             *p++ = (unsigned char) c;
13871           else if (c < 0x7ff)
13872             {
13873               *p++ = (unsigned char) (c >> 6 | 0xc0);
13874               *p++ = (unsigned char) ((c & 0x3f) | 0x80);
13875             }
13876           else
13877             {
13878               *p++ = (unsigned char) (c >> 12 | 0xe0);
13879               *p++ = (unsigned char) (((c >> 6) & 0x3f) | 0x80);
13880               *p++ = (unsigned char) ((c & 0x3f) | 0x80);
13881             }
13882           *p = '\0';
13883
13884           string = ch;
13885         }
13886       else
13887         string = string_convert_int_cst (op2);
13888
13889       return do_merge_string_cste (op1, string, strlen (string), after);
13890     }
13891   return NULL_TREE;
13892 }
13893
13894 /* Tries to statically concatenate OP1 and OP2 if possible. Either one
13895    has to be a STRING_CST and the other part must be a STRING_CST or a
13896    INTEGRAL constant. Return a new STRING_CST if the operation
13897    succeed, NULL_TREE otherwise.
13898
13899    If the case we want to optimize for space, we might want to return
13900    NULL_TREE for each invocation of this routine. FIXME */
13901
13902 static tree
13903 string_constant_concatenation (tree op1, tree op2)
13904 {
13905   if (TREE_CODE (op1) == STRING_CST || (TREE_CODE (op2) == STRING_CST))
13906     {
13907       tree string, rest;
13908       int invert;
13909
13910       string = (TREE_CODE (op1) == STRING_CST ? op1 : op2);
13911       rest   = (string == op1 ? op2 : op1);
13912       invert = (string == op1 ? 0 : 1 );
13913
13914       /* Walk REST, only if it looks reasonable */
13915       if (TREE_CODE (rest) != STRING_CST
13916           && !IS_CRAFTED_STRING_BUFFER_P (rest)
13917           && !JSTRING_TYPE_P (TREE_TYPE (rest))
13918           && TREE_CODE (rest) == EXPR_WITH_FILE_LOCATION)
13919         {
13920           rest = java_complete_tree (rest);
13921           if (rest == error_mark_node)
13922             return error_mark_node;
13923           rest = fold (rest);
13924         }
13925       return merge_string_cste (string, rest, invert);
13926     }
13927   return NULL_TREE;
13928 }
13929
13930 /* Implement the `+' operator. Does static optimization if possible,
13931    otherwise create (if necessary) and append elements to a
13932    StringBuffer. The StringBuffer will be carried around until it is
13933    used for a function call or an assignment. Then toString() will be
13934    called on it to turn it into a String object. */
13935
13936 static tree
13937 build_string_concatenation (tree op1, tree op2)
13938 {
13939   tree result;
13940   int side_effects = TREE_SIDE_EFFECTS (op1) | TREE_SIDE_EFFECTS (op2);
13941
13942   if (flag_emit_xref)
13943     return build (PLUS_EXPR, string_type_node, op1, op2);
13944
13945   /* Try to do some static optimization */
13946   if ((result = string_constant_concatenation (op1, op2)))
13947     return result;
13948
13949   /* Discard empty strings on either side of the expression */
13950   if (TREE_CODE (op1) == STRING_CST && TREE_STRING_LENGTH (op1) == 0)
13951     {
13952       op1 = op2;
13953       op2 = NULL_TREE;
13954     }
13955   else if (TREE_CODE (op2) == STRING_CST && TREE_STRING_LENGTH (op2) == 0)
13956     op2 = NULL_TREE;
13957
13958   /* If operands are string constant, turn then into object references */
13959   if (TREE_CODE (op1) == STRING_CST)
13960     op1 = patch_string_cst (op1);
13961   if (op2 && TREE_CODE (op2) == STRING_CST)
13962     op2 = patch_string_cst (op2);
13963
13964   /* If either one of the constant is null and the other non null
13965      operand is a String constant, return it. */
13966   if ((TREE_CODE (op1) == STRING_CST) && !op2)
13967     return op1;
13968
13969   /* If OP1 isn't already a StringBuffer, create and
13970      initialize a new one */
13971   if (!IS_CRAFTED_STRING_BUFFER_P (op1))
13972     {
13973       /* Two solutions here:
13974          1) OP1 is a constant string reference, we call new StringBuffer(OP1)
13975          2) OP1 is something else, we call new StringBuffer().append(OP1).  */
13976       if (TREE_CONSTANT (op1) && JSTRING_TYPE_P (TREE_TYPE (op1)))
13977         op1 = BUILD_STRING_BUFFER (op1);
13978       else
13979         {
13980           tree aNew = BUILD_STRING_BUFFER (NULL_TREE);
13981           op1 = make_qualified_primary (aNew, BUILD_APPEND (op1), 0);
13982         }
13983     }
13984
13985   if (op2)
13986     {
13987       /* OP1 is no longer the last node holding a crafted StringBuffer */
13988       IS_CRAFTED_STRING_BUFFER_P (op1) = 0;
13989       /* Create a node for `{new...,xxx}.append (op2)' */
13990       if (op2)
13991         op1 = make_qualified_primary (op1, BUILD_APPEND (op2), 0);
13992     }
13993
13994   /* Mark the last node holding a crafted StringBuffer */
13995   IS_CRAFTED_STRING_BUFFER_P (op1) = 1;
13996
13997   TREE_SIDE_EFFECTS (op1) = side_effects;
13998   return op1;
13999 }
14000
14001 /* Patch the string node NODE. NODE can be a STRING_CST of a crafted
14002    StringBuffer. If no string were found to be patched, return
14003    NULL. */
14004
14005 static tree
14006 patch_string (tree node)
14007 {
14008   if (node == error_mark_node)
14009     return error_mark_node;
14010   if (TREE_CODE (node) == STRING_CST)
14011     return patch_string_cst (node);
14012   else if (IS_CRAFTED_STRING_BUFFER_P (node))
14013     {
14014       int saved = ctxp->explicit_constructor_p;
14015       tree invoke = build_method_invocation (wfl_to_string, NULL_TREE);
14016       tree ret;
14017       /* Temporary disable forbid the use of `this'. */
14018       ctxp->explicit_constructor_p = 0;
14019       ret = java_complete_tree (make_qualified_primary (node, invoke, 0));
14020       /* String concatenation arguments must be evaluated in order too. */
14021       ret = force_evaluation_order (ret);
14022       /* Restore it at its previous value */
14023       ctxp->explicit_constructor_p = saved;
14024       return ret;
14025     }
14026   return NULL_TREE;
14027 }
14028
14029 /* Build the internal representation of a string constant.  */
14030
14031 static tree
14032 patch_string_cst (tree node)
14033 {
14034   int location;
14035   if (! flag_emit_class_files)
14036     {
14037       node = get_identifier (TREE_STRING_POINTER (node));
14038       location = alloc_name_constant (CONSTANT_String, node);
14039       node = build_ref_from_constant_pool (location);
14040     }
14041   TREE_TYPE (node) = string_ptr_type_node;
14042   TREE_CONSTANT (node) = 1;
14043   return node;
14044 }
14045
14046 /* Build an incomplete unary operator expression. */
14047
14048 static tree
14049 build_unaryop (int op_token, int op_location, tree op1)
14050 {
14051   enum tree_code op;
14052   tree unaryop;
14053   switch (op_token)
14054     {
14055     case PLUS_TK: op = UNARY_PLUS_EXPR; break;
14056     case MINUS_TK: op = NEGATE_EXPR; break;
14057     case NEG_TK: op = TRUTH_NOT_EXPR; break;
14058     case NOT_TK: op = BIT_NOT_EXPR; break;
14059     default: abort ();
14060     }
14061
14062   unaryop = build1 (op, NULL_TREE, op1);
14063   TREE_SIDE_EFFECTS (unaryop) = 1;
14064   /* Store the location of the operator, for better error report. The
14065      string of the operator will be rebuild based on the OP value. */
14066   EXPR_WFL_LINECOL (unaryop) = op_location;
14067   return unaryop;
14068 }
14069
14070 /* Special case for the ++/-- operators, since they require an extra
14071    argument to build, which is set to NULL and patched
14072    later. IS_POST_P is 1 if the operator, 0 otherwise.  */
14073
14074 static tree
14075 build_incdec (int op_token, int op_location, tree op1, int is_post_p)
14076 {
14077   static const enum tree_code lookup [2][2] =
14078     {
14079       { PREDECREMENT_EXPR, PREINCREMENT_EXPR, },
14080       { POSTDECREMENT_EXPR, POSTINCREMENT_EXPR, },
14081     };
14082   tree node = build (lookup [is_post_p][(op_token - DECR_TK)],
14083                      NULL_TREE, op1, NULL_TREE);
14084   TREE_SIDE_EFFECTS (node) = 1;
14085   /* Store the location of the operator, for better error report. The
14086      string of the operator will be rebuild based on the OP value. */
14087   EXPR_WFL_LINECOL (node) = op_location;
14088   return node;
14089 }
14090
14091 /* Build an incomplete cast operator, based on the use of the
14092    CONVERT_EXPR. Note that TREE_TYPE of the constructed node is
14093    set. java_complete_tree is trained to walk a CONVERT_EXPR even
14094    though its type is already set.  */
14095
14096 static tree
14097 build_cast (int location, tree type, tree exp)
14098 {
14099   tree node = build1 (CONVERT_EXPR, type, exp);
14100   EXPR_WFL_LINECOL (node) = location;
14101   return node;
14102 }
14103
14104 /* Build an incomplete class reference operator.  */
14105 static tree
14106 build_incomplete_class_ref (int location, tree class_name)
14107 {
14108   tree node = build1 (CLASS_LITERAL, NULL_TREE, class_name);
14109   tree class_decl = GET_CPC ();
14110   tree this_class = TREE_TYPE (class_decl);
14111
14112   /* Generate the synthetic static method `class$'.  (Previously we
14113      deferred this, causing different method tables to be emitted
14114      for native code and bytecode.)  */
14115   if (!TYPE_DOT_CLASS (this_class)
14116       && !JPRIMITIVE_TYPE_P (class_name)
14117       && !(TREE_CODE (class_name) == VOID_TYPE))
14118     {
14119       tree target_class;
14120
14121       if (CLASS_INTERFACE (TYPE_NAME (this_class)))
14122         {
14123           /* For interfaces, adding a static 'class$' method directly 
14124              is illegal.  So create an inner class to contain the new
14125              method.  Empirically this matches the behavior of javac.  */
14126           tree t = build_wfl_node (DECL_NAME (TYPE_NAME (object_type_node)));
14127           tree inner = create_anonymous_class (0, t);
14128           target_class = TREE_TYPE (inner);
14129           end_class_declaration (1);
14130         }
14131       else
14132         {
14133           /* For inner classes, add a 'class$' method to their outermost
14134              context, creating it if necessary.  */
14135           while (INNER_CLASS_DECL_P (class_decl))
14136             class_decl = DECL_CONTEXT (class_decl);
14137           target_class = TREE_TYPE (class_decl);
14138         }
14139
14140       if (TYPE_DOT_CLASS (target_class) == NULL_TREE)
14141         build_dot_class_method (target_class);
14142
14143       if (this_class != target_class)
14144         TYPE_DOT_CLASS (this_class) = TYPE_DOT_CLASS (target_class);
14145     }
14146
14147   EXPR_WFL_LINECOL (node) = location;
14148   return node;
14149 }
14150
14151 /* Complete an incomplete class reference operator.  */
14152 static tree
14153 patch_incomplete_class_ref (tree node)
14154 {
14155   tree type = TREE_OPERAND (node, 0);
14156   tree ref_type;
14157
14158   if (!(ref_type = resolve_type_during_patch (type)))
14159     return error_mark_node;
14160
14161   /* If we're not emitting class files and we know ref_type is a
14162      compiled class, build a direct reference.  */
14163   if ((! flag_emit_class_files && is_compiled_class (ref_type))
14164       || JPRIMITIVE_TYPE_P (ref_type)
14165       || TREE_CODE (ref_type) == VOID_TYPE)
14166     {
14167       tree dot = build_class_ref (ref_type);
14168       /* A class referenced by `foo.class' is initialized.  */
14169       if (!flag_emit_class_files)
14170        dot = build_class_init (ref_type, dot);
14171       return java_complete_tree (dot);
14172     }
14173
14174   /* If we're emitting class files and we have to deal with non
14175      primitive types, we invoke the synthetic static method `class$'.  */
14176   ref_type = build_dot_class_method_invocation (current_class, ref_type);
14177   return java_complete_tree (ref_type);
14178 }
14179
14180 /* 15.14 Unary operators. We return error_mark_node in case of error,
14181    but preserve the type of NODE if the type is fixed.  */
14182
14183 static tree
14184 patch_unaryop (tree node, tree wfl_op)
14185 {
14186   tree op = TREE_OPERAND (node, 0);
14187   tree op_type = TREE_TYPE (op);
14188   tree prom_type = NULL_TREE, value, decl;
14189   int outer_field_flag = 0;
14190   int code = TREE_CODE (node);
14191   int error_found = 0;
14192
14193   EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
14194
14195   switch (code)
14196     {
14197       /* 15.13.2 Postfix Increment Operator ++ */
14198     case POSTINCREMENT_EXPR:
14199       /* 15.13.3 Postfix Increment Operator -- */
14200     case POSTDECREMENT_EXPR:
14201       /* 15.14.1 Prefix Increment Operator ++ */
14202     case PREINCREMENT_EXPR:
14203       /* 15.14.2 Prefix Decrement Operator -- */
14204     case PREDECREMENT_EXPR:
14205       op = decl = strip_out_static_field_access_decl (op);
14206       outer_field_flag = outer_field_expanded_access_p (op, NULL, NULL, NULL);
14207       /* We might be trying to change an outer field accessed using
14208          access method. */
14209       if (outer_field_flag)
14210         {
14211           /* Retrieve the decl of the field we're trying to access. We
14212              do that by first retrieving the function we would call to
14213              access the field. It has been already verified that this
14214              field isn't final */
14215           if (flag_emit_class_files)
14216             decl = TREE_OPERAND (op, 0);
14217           else
14218             decl = TREE_OPERAND (TREE_OPERAND (TREE_OPERAND (op, 0), 0), 0);
14219           decl = DECL_FUNCTION_ACCESS_DECL (decl);
14220         }
14221       /* We really should have a JAVA_ARRAY_EXPR to avoid this */
14222       else if (!JDECL_P (decl)
14223           && TREE_CODE (decl) != COMPONENT_REF
14224           && !(flag_emit_class_files && TREE_CODE (decl) == ARRAY_REF)
14225           && TREE_CODE (decl) != INDIRECT_REF
14226           && !(TREE_CODE (decl) == COMPOUND_EXPR
14227                && TREE_OPERAND (decl, 1)
14228                && (TREE_CODE (TREE_OPERAND (decl, 1)) == INDIRECT_REF)))
14229         {
14230           TREE_TYPE (node) = error_mark_node;
14231           error_found = 1;
14232         }
14233
14234       /* From now on, we know that op if a variable and that it has a
14235          valid wfl. We use wfl_op to locate errors related to the
14236          ++/-- operand. */
14237       if (!JNUMERIC_TYPE_P (op_type))
14238         {
14239           parse_error_context
14240             (wfl_op, "Invalid argument type `%s' to `%s'",
14241              lang_printable_name (op_type, 0), operator_string (node));
14242           TREE_TYPE (node) = error_mark_node;
14243           error_found = 1;
14244         }
14245       else
14246         {
14247           /* Before the addition, binary numeric promotion is performed on
14248              both operands, if really necessary */
14249           if (JINTEGRAL_TYPE_P (op_type))
14250             {
14251               value = build_int_2 (1, 0);
14252               TREE_TYPE (value) = TREE_TYPE (node) = op_type;
14253             }
14254           else
14255             {
14256               value = build_int_2 (1, 0);
14257               TREE_TYPE (node) =
14258                 binary_numeric_promotion (op_type,
14259                                           TREE_TYPE (value), &op, &value);
14260             }
14261
14262           /* We remember we might be accessing an outer field */
14263           if (outer_field_flag)
14264             {
14265               /* We re-generate an access to the field */
14266               value = build (PLUS_EXPR, TREE_TYPE (op),
14267                              build_outer_field_access (wfl_op, decl), value);
14268
14269               /* And we patch the original access$() into a write
14270                  with plus_op as a rhs */
14271               return outer_field_access_fix (node, op, value);
14272             }
14273
14274           /* And write back into the node. */
14275           TREE_OPERAND (node, 0) = op;
14276           TREE_OPERAND (node, 1) = value;
14277           /* Convert the overall back into its original type, if
14278              necessary, and return */
14279           if (JINTEGRAL_TYPE_P (op_type))
14280             return fold (node);
14281           else
14282             return fold (convert (op_type, node));
14283         }
14284       break;
14285
14286       /* 15.14.3 Unary Plus Operator + */
14287     case UNARY_PLUS_EXPR:
14288       /* 15.14.4 Unary Minus Operator - */
14289     case NEGATE_EXPR:
14290       if (!JNUMERIC_TYPE_P (op_type))
14291         {
14292           ERROR_CANT_CONVERT_TO_NUMERIC (wfl_operator, node, op_type);
14293           TREE_TYPE (node) = error_mark_node;
14294           error_found = 1;
14295         }
14296       /* Unary numeric promotion is performed on operand */
14297       else
14298         {
14299           op = do_unary_numeric_promotion (op);
14300           prom_type = TREE_TYPE (op);
14301           if (code == UNARY_PLUS_EXPR)
14302             return fold (op);
14303         }
14304       break;
14305
14306       /* 15.14.5 Bitwise Complement Operator ~ */
14307     case BIT_NOT_EXPR:
14308       if (!JINTEGRAL_TYPE_P (op_type))
14309         {
14310           ERROR_CAST_NEEDED_TO_INTEGRAL (wfl_operator, node, op_type);
14311           TREE_TYPE (node) = error_mark_node;
14312           error_found = 1;
14313         }
14314       else
14315         {
14316           op = do_unary_numeric_promotion (op);
14317           prom_type = TREE_TYPE (op);
14318         }
14319       break;
14320
14321       /* 15.14.6 Logical Complement Operator ! */
14322     case TRUTH_NOT_EXPR:
14323       if (TREE_CODE (op_type) != BOOLEAN_TYPE)
14324         {
14325           ERROR_CANT_CONVERT_TO_BOOLEAN (wfl_operator, node, op_type);
14326           /* But the type is known. We will report an error if further
14327              attempt of a assignment is made with this rhs */
14328           TREE_TYPE (node) = boolean_type_node;
14329           error_found = 1;
14330         }
14331       else
14332         prom_type = boolean_type_node;
14333       break;
14334
14335       /* 15.15 Cast Expression */
14336     case CONVERT_EXPR:
14337       value = patch_cast (node, wfl_operator);
14338       if (value == error_mark_node)
14339         {
14340           /* If this cast is part of an assignment, we tell the code
14341              that deals with it not to complain about a mismatch,
14342              because things have been cast, anyways */
14343           TREE_TYPE (node) = error_mark_node;
14344           error_found = 1;
14345         }
14346       else
14347         {
14348           value = fold (value);
14349           TREE_SIDE_EFFECTS (value) = TREE_SIDE_EFFECTS (op);
14350           return value;
14351         }
14352       break;
14353     }
14354
14355   if (error_found)
14356     return error_mark_node;
14357
14358   /* There are cases where node has been replaced by something else
14359      and we don't end up returning here: UNARY_PLUS_EXPR,
14360      CONVERT_EXPR, {POST,PRE}{INCR,DECR}EMENT_EXPR. */
14361   TREE_OPERAND (node, 0) = fold (op);
14362   TREE_TYPE (node) = prom_type;
14363   TREE_SIDE_EFFECTS (node) = TREE_SIDE_EFFECTS (op);
14364   return fold (node);
14365 }
14366
14367 /* Generic type resolution that sometimes takes place during node
14368    patching. Returned the resolved type or generate an error
14369    message. Return the resolved type or NULL_TREE.  */
14370
14371 static tree
14372 resolve_type_during_patch (tree type)
14373 {
14374   if (unresolved_type_p (type, NULL))
14375     {
14376       tree type_decl = resolve_and_layout (EXPR_WFL_NODE (type), type);
14377       if (!type_decl)
14378         {
14379           parse_error_context (type,
14380                                "Class `%s' not found in type declaration",
14381                                IDENTIFIER_POINTER (EXPR_WFL_NODE (type)));
14382           return NULL_TREE;
14383         }
14384
14385       check_deprecation (type, type_decl);
14386
14387       return TREE_TYPE (type_decl);
14388     }
14389   return type;
14390 }
14391
14392 /* 5.5 Casting Conversion. error_mark_node is returned if an error is
14393    found. Otherwise NODE or something meant to replace it is returned.  */
14394
14395 static tree
14396 patch_cast (tree node, tree wfl_op)
14397 {
14398   tree op = TREE_OPERAND (node, 0);
14399   tree cast_type = TREE_TYPE (node);
14400   tree patched, op_type;
14401   char *t1;
14402
14403   /* Some string patching might be necessary at this stage */
14404   if ((patched = patch_string (op)))
14405     TREE_OPERAND (node, 0) = op = patched;
14406   op_type = TREE_TYPE (op);
14407
14408   /* First resolve OP_TYPE if unresolved */
14409   if (!(cast_type = resolve_type_during_patch (cast_type)))
14410     return error_mark_node;
14411
14412   /* Check on cast that are proven correct at compile time */
14413   if (JNUMERIC_TYPE_P (cast_type) && JNUMERIC_TYPE_P (op_type))
14414     {
14415       /* Same type */
14416       if (cast_type == op_type)
14417         return node;
14418
14419       /* A narrowing conversion from a floating-point number to an
14420          integral type requires special handling (5.1.3).  */
14421       if (JFLOAT_TYPE_P (op_type) && JINTEGRAL_TYPE_P (cast_type))
14422         if (cast_type != long_type_node)
14423           op = convert (integer_type_node, op);
14424
14425       /* Try widening/narrowing conversion.  Potentially, things need
14426          to be worked out in gcc so we implement the extreme cases
14427          correctly.  fold_convert() needs to be fixed.  */
14428       return convert (cast_type, op);
14429     }
14430
14431   /* It's also valid to cast a boolean into a boolean */
14432   if (op_type == boolean_type_node && cast_type == boolean_type_node)
14433     return node;
14434
14435   /* null can be casted to references */
14436   if (op == null_pointer_node && JREFERENCE_TYPE_P (cast_type))
14437     return build_null_of_type (cast_type);
14438
14439   /* The remaining legal casts involve conversion between reference
14440      types. Check for their compile time correctness. */
14441   if (JREFERENCE_TYPE_P (op_type) && JREFERENCE_TYPE_P (cast_type)
14442       && valid_ref_assignconv_cast_p (op_type, cast_type, 1))
14443     {
14444       TREE_TYPE (node) = promote_type (cast_type);
14445       /* Now, the case can be determined correct at compile time if
14446          OP_TYPE can be converted into CAST_TYPE by assignment
14447          conversion (5.2) */
14448
14449       if (valid_ref_assignconv_cast_p (op_type, cast_type, 0))
14450         {
14451           TREE_SET_CODE (node, NOP_EXPR);
14452           return node;
14453         }
14454
14455       if (flag_emit_class_files)
14456         {
14457           TREE_SET_CODE (node, CONVERT_EXPR);
14458           return node;
14459         }
14460
14461       /* The cast requires a run-time check */
14462       return build (CALL_EXPR, promote_type (cast_type),
14463                     build_address_of (soft_checkcast_node),
14464                     tree_cons (NULL_TREE, build_class_ref (cast_type),
14465                                build_tree_list (NULL_TREE, op)),
14466                     NULL_TREE);
14467     }
14468
14469   /* Any other casts are proven incorrect at compile time */
14470   t1 = xstrdup (lang_printable_name (op_type, 0));
14471   parse_error_context (wfl_op, "Invalid cast from `%s' to `%s'",
14472                        t1, lang_printable_name (cast_type, 0));
14473   free (t1);
14474   return error_mark_node;
14475 }
14476
14477 /* Build a null constant and give it the type TYPE.  */
14478
14479 static tree
14480 build_null_of_type (tree type)
14481 {
14482   tree node = build_int_2 (0, 0);
14483   TREE_TYPE (node) = promote_type (type);
14484   return node;
14485 }
14486
14487 /* Build an ARRAY_REF incomplete tree node. Note that operand 1 isn't
14488    a list of indices. */
14489 static tree
14490 build_array_ref (int location, tree array, tree index)
14491 {
14492   tree node = build (ARRAY_REF, NULL_TREE, array, index);
14493   EXPR_WFL_LINECOL (node) = location;
14494   return node;
14495 }
14496
14497 /* 15.12 Array Access Expression */
14498
14499 static tree
14500 patch_array_ref (tree node)
14501 {
14502   tree array = TREE_OPERAND (node, 0);
14503   tree array_type  = TREE_TYPE (array);
14504   tree index = TREE_OPERAND (node, 1);
14505   tree index_type = TREE_TYPE (index);
14506   int error_found = 0;
14507
14508   EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
14509
14510   if (TREE_CODE (array_type) == POINTER_TYPE)
14511     array_type = TREE_TYPE (array_type);
14512
14513   /* The array reference must be an array */
14514   if (!TYPE_ARRAY_P (array_type))
14515     {
14516       parse_error_context
14517         (wfl_operator,
14518          "`[]' can only be applied to arrays. It can't be applied to `%s'",
14519          lang_printable_name (array_type, 0));
14520       TREE_TYPE (node) = error_mark_node;
14521       error_found = 1;
14522     }
14523
14524   /* The array index undergoes unary numeric promotion. The promoted
14525      type must be int */
14526   index = do_unary_numeric_promotion (index);
14527   if (TREE_TYPE (index) != int_type_node)
14528     {
14529       if (valid_cast_to_p (index_type, int_type_node))
14530         parse_error_context (wfl_operator,
14531    "Incompatible type for `[]'. Explicit cast needed to convert `%s' to `int'",
14532                              lang_printable_name (index_type, 0));
14533       else
14534         parse_error_context (wfl_operator,
14535           "Incompatible type for `[]'. Can't convert `%s' to `int'",
14536                              lang_printable_name (index_type, 0));
14537       TREE_TYPE (node) = error_mark_node;
14538       error_found = 1;
14539     }
14540
14541   if (error_found)
14542     return error_mark_node;
14543
14544   array_type = TYPE_ARRAY_ELEMENT (array_type);
14545
14546   if (flag_emit_class_files || flag_emit_xref)
14547     {
14548       TREE_OPERAND (node, 0) = array;
14549       TREE_OPERAND (node, 1) = index;
14550     }
14551   else
14552     node = build_java_arrayaccess (array, array_type, index);
14553   TREE_TYPE (node) = array_type;
14554   return node;
14555 }
14556
14557 /* 15.9 Array Creation Expressions */
14558
14559 static tree
14560 build_newarray_node (tree type, tree dims, int extra_dims)
14561 {
14562   tree node =
14563     build (NEW_ARRAY_EXPR, NULL_TREE, type, nreverse (dims),
14564            build_int_2 (extra_dims, 0));
14565   return node;
14566 }
14567
14568 static tree
14569 patch_newarray (tree node)
14570 {
14571   tree type = TREE_OPERAND (node, 0);
14572   tree dims = TREE_OPERAND (node, 1);
14573   tree cdim, array_type;
14574   int error_found = 0;
14575   int ndims = 0;
14576   int xdims = TREE_INT_CST_LOW (TREE_OPERAND (node, 2));
14577
14578   /* Dimension types are verified. It's better for the types to be
14579      verified in order. */
14580   for (cdim = dims, ndims = 0; cdim; cdim = TREE_CHAIN (cdim), ndims++ )
14581     {
14582       int dim_error = 0;
14583       tree dim = TREE_VALUE (cdim);
14584
14585       /* Dim might have been saved during its evaluation */
14586       dim = (TREE_CODE (dim) == SAVE_EXPR ? TREE_OPERAND (dim, 0) : dim);
14587
14588       /* The type of each specified dimension must be an integral type. */
14589       if (!JINTEGRAL_TYPE_P (TREE_TYPE (dim)))
14590         dim_error = 1;
14591
14592       /* Each expression undergoes an unary numeric promotion (5.6.1) and the
14593          promoted type must be int. */
14594       else
14595         {
14596           dim = do_unary_numeric_promotion (dim);
14597           if (TREE_TYPE (dim) != int_type_node)
14598             dim_error = 1;
14599         }
14600
14601       /* Report errors on types here */
14602       if (dim_error)
14603         {
14604           parse_error_context
14605             (TREE_PURPOSE (cdim),
14606              "Incompatible type for dimension in array creation expression. %s convert `%s' to `int'",
14607              (valid_cast_to_p (TREE_TYPE (dim), int_type_node) ?
14608               "Explicit cast needed to" : "Can't"),
14609              lang_printable_name (TREE_TYPE (dim), 0));
14610           error_found = 1;
14611         }
14612
14613       TREE_PURPOSE (cdim) = NULL_TREE;
14614     }
14615
14616   /* Resolve array base type if unresolved */
14617   if (!(type = resolve_type_during_patch (type)))
14618     error_found = 1;
14619
14620   if (error_found)
14621     {
14622       /* We don't want further evaluation of this bogus array creation
14623          operation */
14624       TREE_TYPE (node) = error_mark_node;
14625       return error_mark_node;
14626     }
14627
14628   /* Set array_type to the actual (promoted) array type of the result. */
14629   if (TREE_CODE (type) == RECORD_TYPE)
14630     type = build_pointer_type (type);
14631   while (--xdims >= 0)
14632     {
14633       type = promote_type (build_java_array_type (type, -1));
14634     }
14635   dims = nreverse (dims);
14636   array_type = type;
14637   for (cdim = dims; cdim; cdim = TREE_CHAIN (cdim))
14638     {
14639       type = array_type;
14640       array_type
14641         = build_java_array_type (type,
14642                                  TREE_CODE (cdim) == INTEGER_CST
14643                                  ? (HOST_WIDE_INT) TREE_INT_CST_LOW (cdim)
14644                                  : -1);
14645       array_type = promote_type (array_type);
14646     }
14647   dims = nreverse (dims);
14648
14649   /* The node is transformed into a function call. Things are done
14650      differently according to the number of dimensions. If the number
14651      of dimension is equal to 1, then the nature of the base type
14652      (primitive or not) matters. */
14653   if (ndims == 1)
14654     return build_new_array (type, TREE_VALUE (dims));
14655
14656   /* Can't reuse what's already written in expr.c because it uses the
14657      JVM stack representation. Provide a build_multianewarray. FIXME */
14658   return build (CALL_EXPR, array_type,
14659                 build_address_of (soft_multianewarray_node),
14660                 tree_cons (NULL_TREE, build_class_ref (TREE_TYPE (array_type)),
14661                            tree_cons (NULL_TREE,
14662                                       build_int_2 (ndims, 0), dims )),
14663                 NULL_TREE);
14664 }
14665
14666 /* 10.6 Array initializer.  */
14667
14668 /* Build a wfl for array element that don't have one, so we can
14669    pin-point errors.  */
14670
14671 static tree
14672 maybe_build_array_element_wfl (tree node)
14673 {
14674   if (TREE_CODE (node) != EXPR_WITH_FILE_LOCATION)
14675     return build_expr_wfl (NULL_TREE, ctxp->filename,
14676                            ctxp->elc.line, ctxp->elc.prev_col);
14677   else
14678     return NULL_TREE;
14679 }
14680
14681 /* Build a NEW_ARRAY_INIT that features a CONSTRUCTOR node. This makes
14682    identification of initialized arrays easier to detect during walk
14683    and expansion.  */
14684
14685 static tree
14686 build_new_array_init (int location, tree values)
14687 {
14688   tree constructor = build_constructor (NULL_TREE, values);
14689   tree to_return = build1 (NEW_ARRAY_INIT, NULL_TREE, constructor);
14690   EXPR_WFL_LINECOL (to_return) = location;
14691   return to_return;
14692 }
14693
14694 /* Expand a NEW_ARRAY_INIT node. Return error_mark_node if an error
14695    occurred.  Otherwise return NODE after having set its type
14696    appropriately.  */
14697
14698 static tree
14699 patch_new_array_init (tree type, tree node)
14700 {
14701   int error_seen = 0;
14702   tree current, element_type;
14703   HOST_WIDE_INT length;
14704   int all_constant = 1;
14705   tree init = TREE_OPERAND (node, 0);
14706
14707   if (TREE_CODE (type) != POINTER_TYPE || ! TYPE_ARRAY_P (TREE_TYPE (type)))
14708     {
14709       parse_error_context (node,
14710                            "Invalid array initializer for non-array type `%s'",
14711                            lang_printable_name (type, 1));
14712       return error_mark_node;
14713     }
14714   type = TREE_TYPE (type);
14715   element_type = TYPE_ARRAY_ELEMENT (type);
14716
14717   CONSTRUCTOR_ELTS (init) = nreverse (CONSTRUCTOR_ELTS (init));
14718
14719   for (length = 0, current = CONSTRUCTOR_ELTS (init);
14720        current;  length++, current = TREE_CHAIN (current))
14721     {
14722       tree elt = TREE_VALUE (current);
14723       if (elt == NULL_TREE || TREE_CODE (elt) != NEW_ARRAY_INIT)
14724         {
14725           error_seen |= array_constructor_check_entry (element_type, current);
14726           elt = TREE_VALUE (current);
14727           /* When compiling to native code, STRING_CST is converted to
14728              INDIRECT_REF, but still with a TREE_CONSTANT flag. */
14729           if (! TREE_CONSTANT (elt) || TREE_CODE (elt) == INDIRECT_REF)
14730             all_constant = 0;
14731         }
14732       else
14733         {
14734           TREE_VALUE (current) = patch_new_array_init (element_type, elt);
14735           TREE_PURPOSE (current) = NULL_TREE;
14736           all_constant = 0;
14737         }
14738       if (elt && TREE_CODE (elt) == TREE_LIST
14739           && TREE_VALUE (elt) == error_mark_node)
14740         error_seen = 1;
14741     }
14742
14743   if (error_seen)
14744     return error_mark_node;
14745
14746   /* Create a new type. We can't reuse the one we have here by
14747      patching its dimension because it originally is of dimension -1
14748      hence reused by gcc. This would prevent triangular arrays. */
14749   type = build_java_array_type (element_type, length);
14750   TREE_TYPE (init) = TREE_TYPE (TREE_CHAIN (TREE_CHAIN (TYPE_FIELDS (type))));
14751   TREE_TYPE (node) = promote_type (type);
14752   TREE_CONSTANT (init) = all_constant;
14753   TREE_CONSTANT (node) = all_constant;
14754   return node;
14755 }
14756
14757 /* Verify that one entry of the initializer element list can be
14758    assigned to the array base type. Report 1 if an error occurred, 0
14759    otherwise.  */
14760
14761 static int
14762 array_constructor_check_entry (tree type, tree entry)
14763 {
14764   char *array_type_string = NULL;       /* For error reports */
14765   tree value, type_value, new_value, wfl_value, patched;
14766   int error_seen = 0;
14767
14768   new_value = NULL_TREE;
14769   wfl_value = TREE_VALUE (entry);
14770
14771   value = java_complete_tree (TREE_VALUE (entry));
14772   /* patch_string return error_mark_node if arg is error_mark_node */
14773   if ((patched = patch_string (value)))
14774     value = patched;
14775   if (value == error_mark_node)
14776     return 1;
14777
14778   type_value = TREE_TYPE (value);
14779
14780   /* At anytime, try_builtin_assignconv can report a warning on
14781      constant overflow during narrowing. */
14782   SET_WFL_OPERATOR (wfl_operator, TREE_PURPOSE (entry), wfl_value);
14783   new_value = try_builtin_assignconv (wfl_operator, type, value);
14784   if (!new_value && (new_value = try_reference_assignconv (type, value)))
14785     type_value = promote_type (type);
14786
14787   /* Check and report errors */
14788   if (!new_value)
14789     {
14790       const char *const msg = (!valid_cast_to_p (type_value, type) ?
14791                    "Can't" : "Explicit cast needed to");
14792       if (!array_type_string)
14793         array_type_string = xstrdup (lang_printable_name (type, 1));
14794       parse_error_context
14795         (wfl_operator, "Incompatible type for array. %s convert `%s' to `%s'",
14796          msg, lang_printable_name (type_value, 1), array_type_string);
14797       error_seen = 1;
14798     }
14799
14800   if (new_value)
14801     TREE_VALUE (entry) = new_value;
14802
14803   if (array_type_string)
14804     free (array_type_string);
14805
14806   TREE_PURPOSE (entry) = NULL_TREE;
14807   return error_seen;
14808 }
14809
14810 static tree
14811 build_this (int location)
14812 {
14813   tree node = build_wfl_node (this_identifier_node);
14814   TREE_SET_CODE (node, THIS_EXPR);
14815   EXPR_WFL_LINECOL (node) = location;
14816   return node;
14817 }
14818
14819 /* 14.15 The return statement. It builds a modify expression that
14820    assigns the returned value to the RESULT_DECL that hold the value
14821    to be returned. */
14822
14823 static tree
14824 build_return (int location, tree op)
14825 {
14826   tree node = build1 (RETURN_EXPR, NULL_TREE, op);
14827   EXPR_WFL_LINECOL (node) = location;
14828   node = build_debugable_stmt (location, node);
14829   return node;
14830 }
14831
14832 static tree
14833 patch_return (tree node)
14834 {
14835   tree return_exp = TREE_OPERAND (node, 0);
14836   tree meth = current_function_decl;
14837   tree mtype = TREE_TYPE (TREE_TYPE (current_function_decl));
14838   int error_found = 0;
14839
14840   TREE_TYPE (node) = error_mark_node;
14841   EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
14842
14843   /* It's invalid to have a return value within a function that is
14844      declared with the keyword void or that is a constructor */
14845   if (return_exp && (mtype == void_type_node || DECL_CONSTRUCTOR_P (meth)))
14846     error_found = 1;
14847
14848   /* It's invalid to use a return statement in a static block */
14849   if (DECL_CLINIT_P (current_function_decl))
14850     error_found = 1;
14851
14852   /* It's invalid to have a no return value within a function that
14853      isn't declared with the keyword `void' */
14854   if (!return_exp && (mtype != void_type_node && !DECL_CONSTRUCTOR_P (meth)))
14855     error_found = 2;
14856
14857   if (DECL_INSTINIT_P (current_function_decl))
14858     error_found = 1;
14859
14860   if (error_found)
14861     {
14862       if (DECL_INSTINIT_P (current_function_decl))
14863         parse_error_context (wfl_operator,
14864                              "`return' inside instance initializer");
14865
14866       else if (DECL_CLINIT_P (current_function_decl))
14867         parse_error_context (wfl_operator,
14868                              "`return' inside static initializer");
14869
14870       else if (!DECL_CONSTRUCTOR_P (meth))
14871         {
14872           char *t = xstrdup (lang_printable_name (mtype, 0));
14873           parse_error_context (wfl_operator,
14874                                "`return' with%s value from `%s %s'",
14875                                (error_found == 1 ? "" : "out"),
14876                                t, lang_printable_name (meth, 0));
14877           free (t);
14878         }
14879       else
14880         parse_error_context (wfl_operator,
14881                              "`return' with value from constructor `%s'",
14882                              lang_printable_name (meth, 0));
14883       return error_mark_node;
14884     }
14885
14886   /* If we have a return_exp, build a modify expression and expand
14887      it. Note: at that point, the assignment is declared valid, but we
14888      may want to carry some more hacks */
14889   if (return_exp)
14890     {
14891       tree exp = java_complete_tree (return_exp);
14892       tree modify, patched;
14893
14894       if ((patched = patch_string (exp)))
14895         exp = patched;
14896
14897       modify = build (MODIFY_EXPR, NULL_TREE, DECL_RESULT (meth), exp);
14898       EXPR_WFL_LINECOL (modify) = EXPR_WFL_LINECOL (node);
14899       modify = java_complete_tree (modify);
14900
14901       if (modify != error_mark_node)
14902         {
14903           TREE_SIDE_EFFECTS (modify) = 1;
14904           TREE_OPERAND (node, 0) = modify;
14905         }
14906       else
14907         return error_mark_node;
14908     }
14909   TREE_TYPE (node) = void_type_node;
14910   TREE_SIDE_EFFECTS (node) = 1;
14911   return node;
14912 }
14913
14914 /* 14.8 The if Statement */
14915
14916 static tree
14917 build_if_else_statement (int location, tree expression, tree if_body,
14918                          tree else_body)
14919 {
14920   tree node;
14921   if (!else_body)
14922     else_body = empty_stmt_node;
14923   node = build (COND_EXPR, NULL_TREE, expression, if_body, else_body);
14924   EXPR_WFL_LINECOL (node) = location;
14925   node = build_debugable_stmt (location, node);
14926   return node;
14927 }
14928
14929 static tree
14930 patch_if_else_statement (tree node)
14931 {
14932   tree expression = TREE_OPERAND (node, 0);
14933   int can_complete_normally
14934     = (CAN_COMPLETE_NORMALLY (TREE_OPERAND (node, 1))
14935        | CAN_COMPLETE_NORMALLY (TREE_OPERAND (node, 2)));
14936
14937   TREE_TYPE (node) = error_mark_node;
14938   EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
14939
14940   /* The type of expression must be boolean */
14941   if (TREE_TYPE (expression) != boolean_type_node
14942       && TREE_TYPE (expression) != promoted_boolean_type_node)
14943     {
14944       parse_error_context
14945         (wfl_operator,
14946          "Incompatible type for `if'. Can't convert `%s' to `boolean'",
14947          lang_printable_name (TREE_TYPE (expression), 0));
14948       return error_mark_node;
14949     }
14950
14951   if (TREE_CODE (expression) == INTEGER_CST)
14952     {
14953       if (integer_zerop (expression))
14954         node = TREE_OPERAND (node, 2);
14955       else
14956         node = TREE_OPERAND (node, 1);
14957       if (CAN_COMPLETE_NORMALLY (node) != can_complete_normally)
14958         {
14959           node = build (COMPOUND_EXPR, void_type_node, node, empty_stmt_node);
14960           CAN_COMPLETE_NORMALLY (node) = can_complete_normally;
14961         }
14962       return node;
14963     }
14964   TREE_TYPE (node) = void_type_node;
14965   TREE_SIDE_EFFECTS (node) = 1;
14966   CAN_COMPLETE_NORMALLY (node) = can_complete_normally;
14967   return node;
14968 }
14969
14970 /* 14.6 Labeled Statements */
14971
14972 /* Action taken when a labeled statement is parsed. a new
14973    LABELED_BLOCK_EXPR is created. No statement is attached to the
14974    label, yet.  LABEL can be NULL_TREE for artificially-generated blocks. */
14975
14976 static tree
14977 build_labeled_block (int location, tree label)
14978 {
14979   tree label_name ;
14980   tree label_decl, node;
14981   if (label == NULL_TREE || label == continue_identifier_node)
14982     label_name = label;
14983   else
14984     {
14985       label_name = merge_qualified_name (label_id, label);
14986       /* Issue an error if we try to reuse a label that was previously
14987          declared */
14988       if (IDENTIFIER_LOCAL_VALUE (label_name))
14989         {
14990           EXPR_WFL_LINECOL (wfl_operator) = location;
14991           parse_error_context (wfl_operator,
14992             "Declaration of `%s' shadows a previous label declaration",
14993                                IDENTIFIER_POINTER (label));
14994           EXPR_WFL_LINECOL (wfl_operator) =
14995             EXPR_WFL_LINECOL (IDENTIFIER_LOCAL_VALUE (label_name));
14996           parse_error_context (wfl_operator,
14997             "This is the location of the previous declaration of label `%s'",
14998                                IDENTIFIER_POINTER (label));
14999           java_error_count--;
15000         }
15001     }
15002
15003   label_decl = create_label_decl (label_name);
15004   node = build (LABELED_BLOCK_EXPR, NULL_TREE, label_decl, NULL_TREE);
15005   EXPR_WFL_LINECOL (node) = location;
15006   TREE_SIDE_EFFECTS (node) = 1;
15007   return node;
15008 }
15009
15010 /* A labeled statement LBE is attached a statement.  */
15011
15012 static tree
15013 finish_labeled_statement (tree lbe, /* Labeled block expr */
15014                           tree statement)
15015 {
15016   /* In anyways, tie the loop to its statement */
15017   LABELED_BLOCK_BODY (lbe) = statement;
15018   pop_labeled_block ();
15019   POP_LABELED_BLOCK ();
15020   return lbe;
15021 }
15022
15023 /* 14.10, 14.11, 14.12 Loop Statements */
15024
15025 /* Create an empty LOOP_EXPR and make it the last in the nested loop
15026    list. */
15027
15028 static tree
15029 build_new_loop (tree loop_body)
15030 {
15031   tree loop =  build (LOOP_EXPR, NULL_TREE, loop_body);
15032   TREE_SIDE_EFFECTS (loop) = 1;
15033   PUSH_LOOP (loop);
15034   return loop;
15035 }
15036
15037 /* Create a loop body according to the following structure:
15038      COMPOUND_EXPR
15039        COMPOUND_EXPR            (loop main body)
15040          EXIT_EXPR              (this order is for while/for loops.
15041          LABELED_BLOCK_EXPR      the order is reversed for do loops)
15042            LABEL_DECL           (a continue occurring here branches at the
15043            BODY                  end of this labeled block)
15044        INCREMENT                (if any)
15045
15046   REVERSED, if nonzero, tells that the loop condition expr comes
15047   after the body, like in the do-while loop.
15048
15049   To obtain a loop, the loop body structure described above is
15050   encapsulated within a LOOP_EXPR surrounded by a LABELED_BLOCK_EXPR:
15051
15052    LABELED_BLOCK_EXPR
15053      LABEL_DECL                   (use this label to exit the loop)
15054      LOOP_EXPR
15055        <structure described above> */
15056
15057 static tree
15058 build_loop_body (int location, tree condition, int reversed)
15059 {
15060   tree first, second, body;
15061
15062   condition = build (EXIT_EXPR, NULL_TREE, condition); /* Force walk */
15063   EXPR_WFL_LINECOL (condition) = location; /* For accurate error report */
15064   condition = build_debugable_stmt (location, condition);
15065   TREE_SIDE_EFFECTS (condition) = 1;
15066
15067   body = build_labeled_block (0, continue_identifier_node);
15068   first = (reversed ? body : condition);
15069   second = (reversed ? condition : body);
15070   return
15071     build (COMPOUND_EXPR, NULL_TREE,
15072            build (COMPOUND_EXPR, NULL_TREE, first, second), empty_stmt_node);
15073 }
15074
15075 /* Install CONDITION (if any) and loop BODY (using REVERSED to tell
15076    their order) on the current loop. Unlink the current loop from the
15077    loop list.  */
15078
15079 static tree
15080 finish_loop_body (int location, tree condition, tree body, int reversed)
15081 {
15082   tree to_return = ctxp->current_loop;
15083   tree loop_body = LOOP_EXPR_BODY (to_return);
15084   if (condition)
15085     {
15086       tree cnode = LOOP_EXPR_BODY_CONDITION_EXPR (loop_body, reversed);
15087       /* We wrapped the EXIT_EXPR around a WFL so we can debug it.
15088          The real EXIT_EXPR is one operand further. */
15089       EXPR_WFL_LINECOL (cnode) = location;
15090       /* This one is for accurate error reports */
15091       EXPR_WFL_LINECOL (TREE_OPERAND (cnode, 0)) = location;
15092       TREE_OPERAND (TREE_OPERAND (cnode, 0), 0) = condition;
15093     }
15094   LOOP_EXPR_BODY_BODY_EXPR (loop_body, reversed) = body;
15095   POP_LOOP ();
15096   return to_return;
15097 }
15098
15099 /* Tailored version of finish_loop_body for FOR loops, when FOR
15100    loops feature the condition part */
15101
15102 static tree
15103 finish_for_loop (int location, tree condition, tree update, tree body)
15104 {
15105   /* Put the condition and the loop body in place */
15106   tree loop = finish_loop_body (location, condition, body, 0);
15107   /* LOOP is the current loop which has been now popped of the loop
15108      stack.  Mark the update block as reachable and install it.  We do
15109      this because the (current interpretation of the) JLS requires
15110      that the update expression be considered reachable even if the
15111      for loop's body doesn't complete normally.  */
15112   if (update != NULL_TREE && update != empty_stmt_node)
15113     {
15114       tree up2 = update;
15115       if (TREE_CODE (up2) == EXPR_WITH_FILE_LOCATION)
15116         up2 = EXPR_WFL_NODE (up2);
15117       /* It is possible for the update expression to be an
15118          EXPR_WFL_NODE wrapping nothing.  */
15119       if (up2 != NULL_TREE && up2 != empty_stmt_node)
15120         {
15121           /* Try to detect constraint violations.  These would be
15122              programming errors somewhere.  */
15123           if (! IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (TREE_CODE (up2)))
15124               || TREE_CODE (up2) == LOOP_EXPR)
15125             abort ();
15126           SUPPRESS_UNREACHABLE_ERROR (up2) = 1;
15127         }
15128     }
15129   LOOP_EXPR_BODY_UPDATE_BLOCK (LOOP_EXPR_BODY (loop)) = update;
15130   return loop;
15131 }
15132
15133 /* Try to find the loop a block might be related to. This comprises
15134    the case where the LOOP_EXPR is found as the second operand of a
15135    COMPOUND_EXPR, because the loop happens to have an initialization
15136    part, then expressed as the first operand of the COMPOUND_EXPR. If
15137    the search finds something, 1 is returned. Otherwise, 0 is
15138    returned. The search is assumed to start from a
15139    LABELED_BLOCK_EXPR's block.  */
15140
15141 static tree
15142 search_loop (tree statement)
15143 {
15144   if (TREE_CODE (statement) == LOOP_EXPR)
15145     return statement;
15146
15147   if (TREE_CODE (statement) == BLOCK)
15148     statement = BLOCK_SUBBLOCKS (statement);
15149   else
15150     return NULL_TREE;
15151
15152   if (statement && TREE_CODE (statement) == COMPOUND_EXPR)
15153     while (statement && TREE_CODE (statement) == COMPOUND_EXPR)
15154       statement = TREE_OPERAND (statement, 1);
15155
15156   return (TREE_CODE (statement) == LOOP_EXPR
15157           && FOR_LOOP_P (statement) ? statement : NULL_TREE);
15158 }
15159
15160 /* Return 1 if LOOP can be found in the labeled block BLOCK. 0 is
15161    returned otherwise.  */
15162
15163 static int
15164 labeled_block_contains_loop_p (tree block, tree loop)
15165 {
15166   if (!block)
15167     return 0;
15168
15169   if (LABELED_BLOCK_BODY (block) == loop)
15170     return 1;
15171
15172   if (FOR_LOOP_P (loop) && search_loop (LABELED_BLOCK_BODY (block)) == loop)
15173     return 1;
15174
15175   return 0;
15176 }
15177
15178 /* If the loop isn't surrounded by a labeled statement, create one and
15179    insert LOOP as its body.  */
15180
15181 static tree
15182 patch_loop_statement (tree loop)
15183 {
15184   tree loop_label;
15185
15186   TREE_TYPE (loop) = void_type_node;
15187   if (labeled_block_contains_loop_p (ctxp->current_labeled_block, loop))
15188     return loop;
15189
15190   loop_label = build_labeled_block (0, NULL_TREE);
15191   /* LOOP is an EXPR node, so it should have a valid EXPR_WFL_LINECOL
15192      that LOOP_LABEL could enquire about, for a better accuracy. FIXME */
15193   LABELED_BLOCK_BODY (loop_label) = loop;
15194   PUSH_LABELED_BLOCK (loop_label);
15195   return loop_label;
15196 }
15197
15198 /* 14.13, 14.14: break and continue Statements */
15199
15200 /* Build a break or a continue statement. a null NAME indicates an
15201    unlabeled break/continue statement.  */
15202
15203 static tree
15204 build_bc_statement (int location, int is_break, tree name)
15205 {
15206   tree break_continue, label_block_expr = NULL_TREE;
15207
15208   if (name)
15209     {
15210       if (!(label_block_expr = IDENTIFIER_LOCAL_VALUE
15211             (merge_qualified_name (label_id, EXPR_WFL_NODE (name)))))
15212         /* Null means that we don't have a target for this named
15213            break/continue. In this case, we make the target to be the
15214            label name, so that the error can be reported accurately in
15215            patch_bc_statement. */
15216         label_block_expr = EXPR_WFL_NODE (name);
15217     }
15218   /* Unlabeled break/continue will be handled during the
15219      break/continue patch operation */
15220   break_continue
15221     = build (EXIT_BLOCK_EXPR, NULL_TREE, label_block_expr, NULL_TREE);
15222
15223   IS_BREAK_STMT_P (break_continue) = is_break;
15224   TREE_SIDE_EFFECTS (break_continue) = 1;
15225   EXPR_WFL_LINECOL (break_continue) = location;
15226   break_continue = build_debugable_stmt (location, break_continue);
15227   return break_continue;
15228 }
15229
15230 /* Verification of a break/continue statement. */
15231
15232 static tree
15233 patch_bc_statement (tree node)
15234 {
15235   tree bc_label = EXIT_BLOCK_LABELED_BLOCK (node), target_stmt;
15236   tree labeled_block = ctxp->current_labeled_block;
15237   EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
15238
15239   /* Having an identifier here means that the target is unknown. */
15240   if (bc_label != NULL_TREE && TREE_CODE (bc_label) == IDENTIFIER_NODE)
15241     {
15242       parse_error_context (wfl_operator, "No label definition found for `%s'",
15243                            IDENTIFIER_POINTER (bc_label));
15244       return error_mark_node;
15245     }
15246   if (! IS_BREAK_STMT_P (node))
15247     {
15248       /* It's a continue statement. */
15249       for (;; labeled_block = TREE_CHAIN (labeled_block))
15250         {
15251           if (labeled_block == NULL_TREE)
15252             {
15253               if (bc_label == NULL_TREE)
15254                 parse_error_context (wfl_operator,
15255                                      "`continue' must be in loop");
15256               else
15257                 parse_error_context
15258                   (wfl_operator, "continue label `%s' does not name a loop",
15259                    IDENTIFIER_POINTER (bc_label));
15260               return error_mark_node;
15261             }
15262           if ((DECL_NAME (LABELED_BLOCK_LABEL (labeled_block))
15263                == continue_identifier_node)
15264               && (bc_label == NULL_TREE
15265                   || TREE_CHAIN (labeled_block) == bc_label))
15266             {
15267               bc_label = labeled_block;
15268               break;
15269             }
15270         }
15271     }
15272   else if (!bc_label)
15273     {
15274       for (;; labeled_block = TREE_CHAIN (labeled_block))
15275         {
15276           if (labeled_block == NULL_TREE)
15277             {
15278               parse_error_context (wfl_operator,
15279                                      "`break' must be in loop or switch");
15280               return error_mark_node;
15281             }
15282           target_stmt = LABELED_BLOCK_BODY (labeled_block);
15283           if (TREE_CODE (target_stmt) == SWITCH_EXPR
15284               || search_loop (target_stmt))
15285             {
15286               bc_label = labeled_block;
15287               break;
15288             }
15289         }
15290     }
15291
15292   EXIT_BLOCK_LABELED_BLOCK (node) = bc_label;
15293   CAN_COMPLETE_NORMALLY (bc_label) = 1;
15294
15295   /* Our break/continue don't return values. */
15296   TREE_TYPE (node) = void_type_node;
15297   /* Encapsulate the break within a compound statement so that it's
15298      expanded all the times by expand_expr (and not clobbered
15299      sometimes, like after a if statement) */
15300   node = add_stmt_to_compound (NULL_TREE, void_type_node, node);
15301   TREE_SIDE_EFFECTS (node) = 1;
15302   return node;
15303 }
15304
15305 /* Process the exit expression belonging to a loop. Its type must be
15306    boolean.  */
15307
15308 static tree
15309 patch_exit_expr (tree node)
15310 {
15311   tree expression = TREE_OPERAND (node, 0);
15312   TREE_TYPE (node) = error_mark_node;
15313   EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
15314
15315   /* The type of expression must be boolean */
15316   if (TREE_TYPE (expression) != boolean_type_node)
15317     {
15318       parse_error_context
15319         (wfl_operator,
15320     "Incompatible type for loop conditional. Can't convert `%s' to `boolean'",
15321          lang_printable_name (TREE_TYPE (expression), 0));
15322       return error_mark_node;
15323     }
15324   /* Now we know things are allright, invert the condition, fold and
15325      return */
15326   TREE_OPERAND (node, 0) =
15327     fold (build1 (TRUTH_NOT_EXPR, boolean_type_node, expression));
15328
15329   if (! integer_zerop (TREE_OPERAND (node, 0))
15330       && ctxp->current_loop != NULL_TREE
15331       && TREE_CODE (ctxp->current_loop) == LOOP_EXPR)
15332     CAN_COMPLETE_NORMALLY (ctxp->current_loop) = 1;
15333   if (! integer_onep (TREE_OPERAND (node, 0)))
15334     CAN_COMPLETE_NORMALLY (node) = 1;
15335
15336
15337   TREE_TYPE (node) = void_type_node;
15338   return node;
15339 }
15340
15341 /* 14.9 Switch statement */
15342
15343 static tree
15344 patch_switch_statement (tree node)
15345 {
15346   tree se = TREE_OPERAND (node, 0), se_type;
15347   tree save, iter;
15348
15349   /* Complete the switch expression */
15350   se = TREE_OPERAND (node, 0) = java_complete_tree (se);
15351   se_type = TREE_TYPE (se);
15352   /* The type of the switch expression must be char, byte, short or
15353      int */
15354   if (! JINTEGRAL_TYPE_P (se_type) || se_type == long_type_node)
15355     {
15356       EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (node);
15357       parse_error_context (wfl_operator,
15358           "Incompatible type for `switch'. Can't convert `%s' to `int'",
15359                            lang_printable_name (se_type, 0));
15360       /* This is what java_complete_tree will check */
15361       TREE_OPERAND (node, 0) = error_mark_node;
15362       return error_mark_node;
15363     }
15364
15365   /* Save and restore the outer case label list.  */
15366   save = case_label_list;
15367   case_label_list = NULL_TREE;
15368
15369   TREE_OPERAND (node, 1) = java_complete_tree (TREE_OPERAND (node, 1));
15370
15371   /* See if we've found a duplicate label.  We can't leave this until
15372      code generation, because in `--syntax-only' and `-C' modes we
15373      don't do ordinary code generation.  */
15374   for (iter = case_label_list; iter != NULL_TREE; iter = TREE_CHAIN (iter))
15375     {
15376       HOST_WIDE_INT val = TREE_INT_CST_LOW (TREE_VALUE (iter));
15377       tree subiter;
15378       for (subiter = TREE_CHAIN (iter);
15379            subiter != NULL_TREE;
15380            subiter = TREE_CHAIN (subiter))
15381         {
15382           HOST_WIDE_INT subval = TREE_INT_CST_LOW (TREE_VALUE (subiter));
15383           if (val == subval)
15384             {
15385               EXPR_WFL_LINECOL (wfl_operator)
15386                 = EXPR_WFL_LINECOL (TREE_PURPOSE (iter));
15387               /* The case_label_list is in reverse order, so print the
15388                  outer label first.  */
15389               parse_error_context (wfl_operator, "duplicate case label: `"
15390                                    HOST_WIDE_INT_PRINT_DEC "'", subval);
15391               EXPR_WFL_LINECOL (wfl_operator)
15392                 = EXPR_WFL_LINECOL (TREE_PURPOSE (subiter));
15393               parse_error_context (wfl_operator, "original label is here");
15394
15395               break;
15396             }
15397         }
15398     }
15399
15400   case_label_list = save;
15401
15402   /* Ready to return */
15403   if (TREE_CODE (TREE_OPERAND (node, 1)) == ERROR_MARK)
15404     {
15405       TREE_TYPE (node) = error_mark_node;
15406       return error_mark_node;
15407     }
15408   TREE_TYPE (node) = void_type_node;
15409   TREE_SIDE_EFFECTS (node) = 1;
15410   CAN_COMPLETE_NORMALLY (node)
15411     = CAN_COMPLETE_NORMALLY (TREE_OPERAND (node, 1))
15412       || ! SWITCH_HAS_DEFAULT (node);
15413   return node;
15414 }
15415
15416 /* Assertions.  */
15417
15418 /* Build an assertion expression for `assert CONDITION : VALUE'; VALUE
15419    might be NULL_TREE.  */
15420 static tree
15421 build_assertion (int location, tree condition, tree value)
15422 {
15423   tree node;
15424   tree klass = GET_CPC ();
15425
15426   if (! CLASS_USES_ASSERTIONS (klass))
15427     {
15428       tree field, classdollar, id, call;
15429       tree class_type = TREE_TYPE (klass);
15430
15431       field = add_field (class_type,
15432                          get_identifier ("$assertionsDisabled"),
15433                          boolean_type_node,
15434                          ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
15435       MAYBE_CREATE_VAR_LANG_DECL_SPECIFIC (field);
15436       FIELD_SYNTHETIC (field) = 1;
15437
15438       if (!TYPE_DOT_CLASS (class_type))
15439         build_dot_class_method (class_type);
15440       classdollar = build_dot_class_method_invocation (class_type, class_type);
15441
15442       /* Call CLASS.desiredAssertionStatus().  */
15443       id = build_wfl_node (get_identifier ("desiredAssertionStatus"));
15444       call = build (CALL_EXPR, NULL_TREE, id, NULL_TREE, NULL_TREE);
15445       call = make_qualified_primary (classdollar, call, location);
15446       TREE_SIDE_EFFECTS (call) = 1;
15447
15448       /* Invert to obtain !CLASS.desiredAssertionStatus().  This may
15449          seem odd, but we do it to generate code identical to that of
15450          the JDK.  */
15451       call = build1 (TRUTH_NOT_EXPR, NULL_TREE, call);
15452       TREE_SIDE_EFFECTS (call) = 1;
15453       DECL_INITIAL (field) = call;
15454
15455       /* Record the initializer in the initializer statement list.  */
15456       call = build (MODIFY_EXPR, NULL_TREE, field, call);
15457       TREE_CHAIN (call) = CPC_STATIC_INITIALIZER_STMT (ctxp);
15458       SET_CPC_STATIC_INITIALIZER_STMT (ctxp, call);
15459       MODIFY_EXPR_FROM_INITIALIZATION_P (call) = 1;
15460
15461       CLASS_USES_ASSERTIONS (klass) = 1;
15462     }
15463
15464   if (value != NULL_TREE)
15465     value = tree_cons (NULL_TREE, value, NULL_TREE);
15466
15467   node = build_wfl_node (get_identifier ("java"));
15468   node = make_qualified_name (node, build_wfl_node (get_identifier ("lang")),
15469                               location);
15470   node = make_qualified_name (node, build_wfl_node (get_identifier ("AssertionError")),
15471                               location);
15472
15473   node = build (NEW_CLASS_EXPR, NULL_TREE, node, value, NULL_TREE);
15474   TREE_SIDE_EFFECTS (node) = 1;
15475   /* It is too early to use BUILD_THROW.  */
15476   node = build1 (THROW_EXPR, NULL_TREE, node);
15477   TREE_SIDE_EFFECTS (node) = 1;
15478
15479   /* We invert the condition; if we just put NODE as the `else' part
15480      then we generate weird-looking bytecode.  */
15481   condition = build1 (TRUTH_NOT_EXPR, NULL_TREE, condition);
15482   /* Check $assertionsDisabled.  */
15483   condition
15484     = build (TRUTH_ANDIF_EXPR, NULL_TREE,
15485              build1 (TRUTH_NOT_EXPR, NULL_TREE,
15486                      build_wfl_node (get_identifier ("$assertionsDisabled"))),
15487              condition);
15488   node = build_if_else_statement (location, condition, node, NULL_TREE);
15489   return node;
15490 }
15491
15492 /* 14.18 The try/catch statements */
15493
15494 /* Encapsulate TRY_STMTS' in a try catch sequence. The catch clause
15495    catches TYPE and executes CATCH_STMTS.  */
15496
15497 static tree
15498 encapsulate_with_try_catch (int location, tree type_or_name, tree try_stmts,
15499                             tree catch_stmts)
15500 {
15501   tree try_block, catch_clause_param, catch_block, catch;
15502
15503   /* First build a try block */
15504   try_block = build_expr_block (try_stmts, NULL_TREE);
15505
15506   /* Build a catch block: we need a catch clause parameter */
15507   if (TREE_CODE (type_or_name) == EXPR_WITH_FILE_LOCATION)
15508     {
15509       tree catch_type = obtain_incomplete_type (type_or_name);
15510       jdep *dep;
15511       catch_clause_param = build_decl (VAR_DECL, wpv_id, catch_type);
15512       register_incomplete_type (JDEP_VARIABLE, type_or_name,
15513                                 catch_clause_param, catch_type);
15514       dep = CLASSD_LAST (ctxp->classd_list);
15515       JDEP_GET_PATCH (dep) = &TREE_TYPE (catch_clause_param);
15516     }
15517   else
15518     catch_clause_param = build_decl (VAR_DECL, wpv_id,
15519                                      build_pointer_type (type_or_name));
15520
15521   /* And a block */
15522   catch_block = build_expr_block (NULL_TREE, catch_clause_param);
15523
15524   /* Initialize the variable and store in the block */
15525   catch = build (MODIFY_EXPR, NULL_TREE, catch_clause_param,
15526                  build (JAVA_EXC_OBJ_EXPR, ptr_type_node));
15527   add_stmt_to_block (catch_block, NULL_TREE, catch);
15528
15529   /* Add the catch statements */
15530   add_stmt_to_block (catch_block, NULL_TREE, catch_stmts);
15531
15532   /* Now we can build a CATCH_EXPR */
15533   catch_block = build1 (CATCH_EXPR, NULL_TREE, catch_block);
15534
15535   return build_try_statement (location, try_block, catch_block);
15536 }
15537
15538 static tree
15539 build_try_statement (int location, tree try_block, tree catches)
15540 {
15541   tree node = build (TRY_EXPR, NULL_TREE, try_block, catches);
15542   EXPR_WFL_LINECOL (node) = location;
15543   return node;
15544 }
15545
15546 static tree
15547 build_try_finally_statement (int location, tree try_block, tree finally)
15548 {
15549   tree node = build (TRY_FINALLY_EXPR, NULL_TREE, try_block, finally);
15550   EXPR_WFL_LINECOL (node) = location;
15551   return node;
15552 }
15553
15554 static tree
15555 patch_try_statement (tree node)
15556 {
15557   int error_found = 0;
15558   tree try = TREE_OPERAND (node, 0);
15559   /* Exception handlers are considered in left to right order */
15560   tree catch = nreverse (TREE_OPERAND (node, 1));
15561   tree current, caught_type_list = NULL_TREE;
15562
15563   /* Check catch clauses, if any. Every time we find an error, we try
15564      to process the next catch clause. We process the catch clause before
15565      the try block so that when processing the try block we can check thrown
15566      exceptions againts the caught type list. */
15567   for (current = catch; current; current = TREE_CHAIN (current))
15568     {
15569       tree carg_decl, carg_type;
15570       tree sub_current, catch_block, catch_clause;
15571       int unreachable;
15572
15573       /* At this point, the structure of the catch clause is
15574            CATCH_EXPR           (catch node)
15575              BLOCK              (with the decl of the parameter)
15576                COMPOUND_EXPR
15577                  MODIFY_EXPR   (assignment of the catch parameter)
15578                  BLOCK          (catch clause block)
15579        */
15580       catch_clause = TREE_OPERAND (current, 0);
15581       carg_decl = BLOCK_EXPR_DECLS (catch_clause);
15582       carg_type = TREE_TYPE (TREE_TYPE (carg_decl));
15583
15584       /* Catch clauses can't have more than one parameter declared,
15585          but it's already enforced by the grammar. Make sure that the
15586          only parameter of the clause statement in of class Throwable
15587          or a subclass of Throwable, but that was done earlier. The
15588          catch clause parameter type has also been resolved. */
15589
15590       /* Just make sure that the catch clause parameter type inherits
15591          from java.lang.Throwable */
15592       if (!inherits_from_p (carg_type, throwable_type_node))
15593         {
15594           EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (current);
15595           parse_error_context (wfl_operator,
15596                                "Can't catch class `%s'. Catch clause parameter type must be a subclass of class `java.lang.Throwable'",
15597                                lang_printable_name (carg_type, 0));
15598           error_found = 1;
15599           continue;
15600         }
15601
15602       /* Partial check for unreachable catch statement: The catch
15603          clause is reachable iff is no earlier catch block A in
15604          the try statement such that the type of the catch
15605          clause's parameter is the same as or a subclass of the
15606          type of A's parameter */
15607       unreachable = 0;
15608       for (sub_current = catch;
15609            sub_current != current; sub_current = TREE_CHAIN (sub_current))
15610         {
15611           tree sub_catch_clause, decl;
15612           sub_catch_clause = TREE_OPERAND (sub_current, 0);
15613           decl = BLOCK_EXPR_DECLS (sub_catch_clause);
15614
15615           if (inherits_from_p (carg_type, TREE_TYPE (TREE_TYPE (decl))))
15616             {
15617               EXPR_WFL_LINECOL (wfl_operator) = EXPR_WFL_LINECOL (current);
15618               parse_error_context
15619                 (wfl_operator,
15620                  "`catch' not reached because of the catch clause at line %d",
15621                  EXPR_WFL_LINENO (sub_current));
15622               unreachable = error_found = 1;
15623               break;
15624             }
15625         }
15626       /* Complete the catch clause block */
15627       catch_block = java_complete_tree (TREE_OPERAND (current, 0));
15628       if (catch_block == error_mark_node)
15629         {
15630           error_found = 1;
15631           continue;
15632         }
15633       if (CAN_COMPLETE_NORMALLY (catch_block))
15634         CAN_COMPLETE_NORMALLY (node) = 1;
15635       TREE_OPERAND (current, 0) = catch_block;
15636
15637       if (unreachable)
15638         continue;
15639
15640       /* Things to do here: the exception must be thrown */
15641
15642       /* Link this type to the caught type list */
15643       caught_type_list = tree_cons (NULL_TREE, carg_type, caught_type_list);
15644     }
15645
15646   PUSH_EXCEPTIONS (caught_type_list);
15647   if ((try = java_complete_tree (try)) == error_mark_node)
15648     error_found = 1;
15649   if (CAN_COMPLETE_NORMALLY (try))
15650     CAN_COMPLETE_NORMALLY (node) = 1;
15651   POP_EXCEPTIONS ();
15652
15653   /* Verification ends here */
15654   if (error_found)
15655     return error_mark_node;
15656
15657   TREE_OPERAND (node, 0) = try;
15658   TREE_OPERAND (node, 1) = catch;
15659   TREE_TYPE (node) = void_type_node;
15660   return node;
15661 }
15662
15663 /* 14.17 The synchronized Statement */
15664
15665 static tree
15666 patch_synchronized_statement (tree node, tree wfl_op1)
15667 {
15668   tree expr = java_complete_tree (TREE_OPERAND (node, 0));
15669   tree block = TREE_OPERAND (node, 1);
15670
15671   tree tmp, enter, exit, expr_decl, assignment;
15672
15673   if (expr == error_mark_node)
15674     {
15675       block = java_complete_tree (block);
15676       return expr;
15677     }
15678
15679   /* We might be trying to synchronize on a STRING_CST */
15680   if ((tmp = patch_string (expr)))
15681     expr = tmp;
15682
15683   /* The TYPE of expr must be a reference type */
15684   if (!JREFERENCE_TYPE_P (TREE_TYPE (expr)))
15685     {
15686       SET_WFL_OPERATOR (wfl_operator, node, wfl_op1);
15687       parse_error_context (wfl_operator, "Incompatible type for `synchronized'. Can't convert `%s' to `java.lang.Object'",
15688                            lang_printable_name (TREE_TYPE (expr), 0));
15689       return error_mark_node;
15690     }
15691
15692   if (flag_emit_xref)
15693     {
15694       TREE_OPERAND (node, 0) = expr;
15695       TREE_OPERAND (node, 1) = java_complete_tree (block);
15696       CAN_COMPLETE_NORMALLY (node) = 1;
15697       return node;
15698     }
15699
15700   /* Generate a try-finally for the synchronized statement, except
15701      that the handler that catches all throw exception calls
15702      _Jv_MonitorExit and then rethrow the exception.
15703      The synchronized statement is then implemented as:
15704      TRY
15705        {
15706          _Jv_MonitorEnter (expression)
15707          synchronized_block
15708          _Jv_MonitorExit (expression)
15709        }
15710      CATCH_ALL
15711        {
15712          e = _Jv_exception_info ();
15713          _Jv_MonitorExit (expression)
15714          Throw (e);
15715        } */
15716
15717   expr_decl = build_decl (VAR_DECL, generate_name (), TREE_TYPE (expr));
15718   BUILD_MONITOR_ENTER (enter, expr_decl);
15719   BUILD_MONITOR_EXIT (exit, expr_decl);
15720   CAN_COMPLETE_NORMALLY (enter) = 1;
15721   CAN_COMPLETE_NORMALLY (exit) = 1;
15722   assignment = build (MODIFY_EXPR, NULL_TREE, expr_decl, expr);
15723   TREE_SIDE_EFFECTS (assignment) = 1;
15724   node = build (COMPOUND_EXPR, NULL_TREE,
15725                 build (COMPOUND_EXPR, NULL_TREE, assignment, enter),
15726                 build (TRY_FINALLY_EXPR, NULL_TREE, block, exit));
15727   node = build_expr_block (node, expr_decl);
15728
15729   return java_complete_tree (node);
15730 }
15731
15732 /* 14.16 The throw Statement */
15733
15734 static tree
15735 patch_throw_statement (tree node, tree wfl_op1)
15736 {
15737   tree expr = TREE_OPERAND (node, 0);
15738   tree type = TREE_TYPE (expr);
15739   int unchecked_ok = 0, tryblock_throws_ok = 0;
15740
15741   /* Thrown expression must be assignable to java.lang.Throwable */
15742   if (!try_reference_assignconv (throwable_type_node, expr))
15743     {
15744       SET_WFL_OPERATOR (wfl_operator, node, wfl_op1);
15745       parse_error_context (wfl_operator,
15746     "Can't throw `%s'; it must be a subclass of class `java.lang.Throwable'",
15747                            lang_printable_name (type, 0));
15748       /* If the thrown expression was a reference, we further the
15749          compile-time check. */
15750       if (!JREFERENCE_TYPE_P (type))
15751         return error_mark_node;
15752     }
15753
15754   /* At least one of the following must be true */
15755
15756   /* The type of the throw expression is a not checked exception,
15757      i.e. is a unchecked expression. */
15758   unchecked_ok = IS_UNCHECKED_EXCEPTION_P (TREE_TYPE (type));
15759
15760   SET_WFL_OPERATOR (wfl_operator, node, wfl_op1);
15761   /* An instance can't throw a checked exception unless that exception
15762      is explicitly declared in the `throws' clause of each
15763      constructor. This doesn't apply to anonymous classes, since they
15764      don't have declared constructors. */
15765   if (!unchecked_ok
15766       && DECL_INSTINIT_P (current_function_decl)
15767       && !ANONYMOUS_CLASS_P (current_class))
15768     {
15769       tree current;
15770       for (current = TYPE_METHODS (current_class); current;
15771            current = TREE_CHAIN (current))
15772         if (DECL_CONSTRUCTOR_P (current)
15773             && !check_thrown_exceptions_do (TREE_TYPE (expr)))
15774           {
15775             parse_error_context (wfl_operator, "Checked exception `%s' can't be thrown in instance initializer (not all declared constructor are declaring it in their `throws' clause)",
15776                                  lang_printable_name (TREE_TYPE (expr), 0));
15777             return error_mark_node;
15778           }
15779     }
15780
15781   /* Throw is contained in a try statement and at least one catch
15782      clause can receive the thrown expression or the current method is
15783      declared to throw such an exception. Or, the throw statement is
15784      contained in a method or constructor declaration and the type of
15785      the Expression is assignable to at least one type listed in the
15786      throws clause the declaration. */
15787   if (!unchecked_ok)
15788     tryblock_throws_ok = check_thrown_exceptions_do (TREE_TYPE (expr));
15789   if (!(unchecked_ok || tryblock_throws_ok))
15790     {
15791       /* If there is a surrounding try block that has no matching
15792          clatch clause, report it first. A surrounding try block exits
15793          only if there is something after the list of checked
15794          exception thrown by the current function (if any). */
15795       if (IN_TRY_BLOCK_P ())
15796         parse_error_context (wfl_operator, "Checked exception `%s' can't be caught by any of the catch clause(s) of the surrounding `try' block",
15797                              lang_printable_name (type, 0));
15798       /* If we have no surrounding try statement and the method doesn't have
15799          any throws, report it now. FIXME */
15800
15801       /* We report that the exception can't be throw from a try block
15802          in all circumstances but when the `throw' is inside a static
15803          block. */
15804       else if (!EXCEPTIONS_P (currently_caught_type_list)
15805                && !tryblock_throws_ok)
15806         {
15807           if (DECL_CLINIT_P (current_function_decl))
15808             parse_error_context (wfl_operator,
15809                    "Checked exception `%s' can't be thrown in initializer",
15810                                  lang_printable_name (type, 0));
15811           else
15812             parse_error_context (wfl_operator,
15813                    "Checked exception `%s' isn't thrown from a `try' block",
15814                                  lang_printable_name (type, 0));
15815         }
15816       /* Otherwise, the current method doesn't have the appropriate
15817          throws declaration */
15818       else
15819         parse_error_context (wfl_operator, "Checked exception `%s' doesn't match any of current method's `throws' declaration(s)",
15820                              lang_printable_name (type, 0));
15821       return error_mark_node;
15822     }
15823
15824   if (! flag_emit_class_files && ! flag_emit_xref)
15825     BUILD_THROW (node, expr);
15826
15827   /* If doing xrefs, keep the location where the `throw' was seen. */
15828   if (flag_emit_xref)
15829     EXPR_WFL_LINECOL (node) = EXPR_WFL_LINECOL (wfl_op1);
15830   return node;
15831 }
15832
15833 /* Check that exception said to be thrown by method DECL can be
15834    effectively caught from where DECL is invoked.  THIS_EXPR is the
15835    expression that computes `this' for the method call.  */
15836 static void
15837 check_thrown_exceptions (int location, tree decl, tree this_expr)
15838 {
15839   tree throws;
15840   int is_array_call = 0;
15841
15842   /* Skip check within generated methods, such as access$<n>.  */
15843   if (OUTER_FIELD_ACCESS_IDENTIFIER_P (DECL_NAME (current_function_decl)))
15844     return;
15845
15846   if (this_expr != NULL_TREE
15847       && TREE_CODE (TREE_TYPE (this_expr)) == POINTER_TYPE
15848       && TYPE_ARRAY_P (TREE_TYPE (TREE_TYPE (this_expr))))
15849     is_array_call = 1;
15850
15851   /* For all the unchecked exceptions thrown by DECL.  */
15852   for (throws = DECL_FUNCTION_THROWS (decl); throws;
15853        throws = TREE_CHAIN (throws))
15854     if (!check_thrown_exceptions_do (TREE_VALUE (throws)))
15855       {
15856         /* Suppress errors about cloning arrays.  */
15857         if (is_array_call && DECL_NAME (decl) == get_identifier ("clone"))
15858           continue;
15859
15860         EXPR_WFL_LINECOL (wfl_operator) = location;
15861         if (DECL_FINIT_P (current_function_decl))
15862           parse_error_context
15863             (wfl_operator, "Exception `%s' can't be thrown in initializer",
15864              lang_printable_name (TREE_VALUE (throws), 0));
15865         else
15866           {
15867             parse_error_context
15868               (wfl_operator, "Exception `%s' must be caught, or it must be declared in the `throws' clause of `%s'",
15869                lang_printable_name (TREE_VALUE (throws), 0),
15870                (DECL_INIT_P (current_function_decl) ?
15871                 IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (current_class))) :
15872                 IDENTIFIER_POINTER (DECL_NAME (current_function_decl))));
15873           }
15874       }
15875 }
15876
15877 /* Return 1 if checked EXCEPTION is caught at the current nesting level of
15878    try-catch blocks, OR is listed in the `throws' clause of the
15879    current method.  */
15880
15881 static int
15882 check_thrown_exceptions_do (tree exception)
15883 {
15884   tree list = currently_caught_type_list;
15885   resolve_and_layout (exception, NULL_TREE);
15886   /* First, all the nested try-catch-finally at that stage. The
15887      last element contains `throws' clause exceptions, if any. */
15888   if (IS_UNCHECKED_EXCEPTION_P (exception))
15889     return 1;
15890   while (list)
15891     {
15892       tree caught;
15893       for (caught = TREE_VALUE (list); caught; caught = TREE_CHAIN (caught))
15894         if (valid_ref_assignconv_cast_p (exception, TREE_VALUE (caught), 0))
15895           return 1;
15896       list = TREE_CHAIN (list);
15897     }
15898   return 0;
15899 }
15900
15901 static void
15902 purge_unchecked_exceptions (tree mdecl)
15903 {
15904   tree throws = DECL_FUNCTION_THROWS (mdecl);
15905   tree new = NULL_TREE;
15906
15907   while (throws)
15908     {
15909       tree next = TREE_CHAIN (throws);
15910       if (!IS_UNCHECKED_EXCEPTION_P (TREE_VALUE (throws)))
15911         {
15912           TREE_CHAIN (throws) = new;
15913           new = throws;
15914         }
15915       throws = next;
15916     }
15917   /* List is inverted here, but it doesn't matter */
15918   DECL_FUNCTION_THROWS (mdecl) = new;
15919 }
15920
15921 /* This function goes over all of CLASS_TYPE ctors and checks whether
15922    each of them features at least one unchecked exception in its
15923    `throws' clause. If it's the case, it returns `true', `false'
15924    otherwise.  */
15925
15926 static bool
15927 ctors_unchecked_throws_clause_p (tree class_type)
15928 {
15929   tree current;
15930
15931   for (current = TYPE_METHODS (class_type); current;
15932        current = TREE_CHAIN (current))
15933     {
15934       bool ctu = false; /* Ctor Throws Unchecked */
15935       if (DECL_CONSTRUCTOR_P (current))
15936         {
15937           tree throws;
15938           for (throws = DECL_FUNCTION_THROWS (current); throws && !ctu;
15939                throws = TREE_CHAIN (throws))
15940             if (inherits_from_p (TREE_VALUE (throws), exception_type_node))
15941               ctu = true;
15942         }
15943       /* We return false as we found one ctor that is unfit. */
15944       if (!ctu && DECL_CONSTRUCTOR_P (current))
15945         return false;
15946     }
15947   /* All ctors feature at least one unchecked exception in their
15948      `throws' clause. */
15949   return true;
15950 }
15951
15952 /* 15.24 Conditional Operator ?: */
15953
15954 static tree
15955 patch_conditional_expr (tree node, tree wfl_cond, tree wfl_op1)
15956 {
15957   tree cond = TREE_OPERAND (node, 0);
15958   tree op1 = TREE_OPERAND (node, 1);
15959   tree op2 = TREE_OPERAND (node, 2);
15960   tree resulting_type = NULL_TREE;
15961   tree t1, t2, patched;
15962   int error_found = 0;
15963
15964   /* Operands of ?: might be StringBuffers crafted as a result of a
15965      string concatenation. Obtain a descent operand here.  */
15966   if ((patched = patch_string (op1)))
15967     TREE_OPERAND (node, 1) = op1 = patched;
15968   if ((patched = patch_string (op2)))
15969     TREE_OPERAND (node, 2) = op2 = patched;
15970
15971   t1 = TREE_TYPE (op1);
15972   t2 = TREE_TYPE (op2);
15973
15974   /* The first expression must be a boolean */
15975   if (TREE_TYPE (cond) != boolean_type_node)
15976     {
15977       SET_WFL_OPERATOR (wfl_operator, node, wfl_cond);
15978       parse_error_context (wfl_operator,
15979                "Incompatible type for `?:'. Can't convert `%s' to `boolean'",
15980                            lang_printable_name (TREE_TYPE (cond), 0));
15981       error_found = 1;
15982     }
15983
15984   /* Second and third can be numeric, boolean (i.e. primitive),
15985      references or null. Anything else results in an error */
15986   if (!((JNUMERIC_TYPE_P (t1) && JNUMERIC_TYPE_P (t2))
15987         || ((JREFERENCE_TYPE_P (t1) || op1 == null_pointer_node)
15988             && (JREFERENCE_TYPE_P (t2) || op2 == null_pointer_node))
15989         || (t1 == boolean_type_node && t2 == boolean_type_node)))
15990     error_found = 1;
15991
15992   /* Determine the type of the conditional expression. Same types are
15993      easy to deal with */
15994   else if (t1 == t2)
15995     resulting_type = t1;
15996
15997   /* There are different rules for numeric types */
15998   else if (JNUMERIC_TYPE_P (t1))
15999     {
16000       /* if byte/short found, the resulting type is short */
16001       if ((t1 == byte_type_node && t2 == short_type_node)
16002           || (t1 == short_type_node && t2 == byte_type_node))
16003         resulting_type = short_type_node;
16004
16005       /* If t1 is a constant int and t2 is of type byte, short or char
16006          and t1's value fits in t2, then the resulting type is t2 */
16007       else if ((t1 == int_type_node && TREE_CONSTANT (TREE_OPERAND (node, 1)))
16008           && JBSC_TYPE_P (t2) && int_fits_type_p (TREE_OPERAND (node, 1), t2))
16009         resulting_type = t2;
16010
16011       /* If t2 is a constant int and t1 is of type byte, short or char
16012          and t2's value fits in t1, then the resulting type is t1 */
16013       else if ((t2 == int_type_node && TREE_CONSTANT (TREE_OPERAND (node, 2)))
16014           && JBSC_TYPE_P (t1) && int_fits_type_p (TREE_OPERAND (node, 2), t1))
16015         resulting_type = t1;
16016
16017       /* Otherwise, binary numeric promotion is applied and the
16018          resulting type is the promoted type of operand 1 and 2 */
16019       else
16020         resulting_type = binary_numeric_promotion (t1, t2,
16021                                                    &TREE_OPERAND (node, 1),
16022                                                    &TREE_OPERAND (node, 2));
16023     }
16024
16025   /* Cases of a reference and a null type */
16026   else if (JREFERENCE_TYPE_P (t1) && op2 == null_pointer_node)
16027     resulting_type = t1;
16028
16029   else if (JREFERENCE_TYPE_P (t2) && op1 == null_pointer_node)
16030     resulting_type = t2;
16031
16032   /* Last case: different reference types. If a type can be converted
16033      into the other one by assignment conversion, the latter
16034      determines the type of the expression */
16035   else if ((resulting_type = try_reference_assignconv (t1, op2)))
16036     resulting_type = promote_type (t1);
16037
16038   else if ((resulting_type = try_reference_assignconv (t2, op1)))
16039     resulting_type = promote_type (t2);
16040
16041   /* If we don't have any resulting type, we're in trouble */
16042   if (!resulting_type)
16043     {
16044       char *t = xstrdup (lang_printable_name (t1, 0));
16045       SET_WFL_OPERATOR (wfl_operator, node, wfl_op1);
16046       parse_error_context (wfl_operator,
16047                  "Incompatible type for `?:'. Can't convert `%s' to `%s'",
16048                            t, lang_printable_name (t2, 0));
16049       free (t);
16050       error_found = 1;
16051     }
16052
16053   if (error_found)
16054     {
16055       TREE_TYPE (node) = error_mark_node;
16056       return error_mark_node;
16057     }
16058
16059   TREE_TYPE (node) = resulting_type;
16060   TREE_SET_CODE (node, COND_EXPR);
16061   CAN_COMPLETE_NORMALLY (node) = 1;
16062   return node;
16063 }
16064
16065 /* Wrap EXPR with code to initialize DECL's class, if appropriate. */
16066
16067 static tree
16068 maybe_build_class_init_for_field (tree decl, tree expr)
16069 {
16070   tree clas = DECL_CONTEXT (decl);
16071   if (flag_emit_class_files || flag_emit_xref)
16072     return expr;
16073
16074   if (TREE_CODE (decl) == VAR_DECL && FIELD_STATIC (decl)
16075       && FIELD_FINAL (decl))
16076     {
16077       tree init = DECL_INITIAL (decl);
16078       if (init != NULL_TREE)
16079         init = fold_constant_for_init (init, decl);
16080       if (init != NULL_TREE && CONSTANT_VALUE_P (init))
16081         return expr;
16082     }
16083
16084   return build_class_init (clas, expr);
16085 }
16086
16087 /* Try to constant fold NODE.
16088    If NODE is not a constant expression, return NULL_EXPR.
16089    CONTEXT is a static final VAR_DECL whose initializer we are folding. */
16090
16091 static tree
16092 fold_constant_for_init (tree node, tree context)
16093 {
16094   tree op0, op1, val;
16095   enum tree_code code = TREE_CODE (node);
16096
16097   switch (code)
16098     {
16099     case INTEGER_CST:
16100       if (node == null_pointer_node)
16101         return NULL_TREE;
16102     case STRING_CST:
16103     case REAL_CST:
16104       return node;
16105
16106     case PLUS_EXPR:
16107     case MINUS_EXPR:
16108     case MULT_EXPR:
16109     case TRUNC_MOD_EXPR:
16110     case RDIV_EXPR:
16111     case LSHIFT_EXPR:
16112     case RSHIFT_EXPR:
16113     case URSHIFT_EXPR:
16114     case BIT_AND_EXPR:
16115     case BIT_XOR_EXPR:
16116     case BIT_IOR_EXPR:
16117     case TRUTH_ANDIF_EXPR:
16118     case TRUTH_ORIF_EXPR:
16119     case EQ_EXPR:
16120     case NE_EXPR:
16121     case GT_EXPR:
16122     case GE_EXPR:
16123     case LT_EXPR:
16124     case LE_EXPR:
16125       op0 = TREE_OPERAND (node, 0);
16126       op1 = TREE_OPERAND (node, 1);
16127       val = fold_constant_for_init (op0, context);
16128       if (val == NULL_TREE || ! TREE_CONSTANT (val))
16129         return NULL_TREE;
16130       TREE_OPERAND (node, 0) = val;
16131       val = fold_constant_for_init (op1, context);
16132       if (val == NULL_TREE || ! TREE_CONSTANT (val))
16133         return NULL_TREE;
16134       TREE_OPERAND (node, 1) = val;
16135       return patch_binop (node, op0, op1);
16136
16137     case UNARY_PLUS_EXPR:
16138     case NEGATE_EXPR:
16139     case TRUTH_NOT_EXPR:
16140     case BIT_NOT_EXPR:
16141     case CONVERT_EXPR:
16142       op0 = TREE_OPERAND (node, 0);
16143       val = fold_constant_for_init (op0, context);
16144       if (val == NULL_TREE || ! TREE_CONSTANT (val))
16145         return NULL_TREE;
16146       TREE_OPERAND (node, 0) = val;
16147       val = patch_unaryop (node, op0);
16148       if (! TREE_CONSTANT (val))
16149         return NULL_TREE;
16150       return val;
16151
16152       break;
16153
16154     case COND_EXPR:
16155       val = fold_constant_for_init (TREE_OPERAND (node, 0), context);
16156       if (val == NULL_TREE || ! TREE_CONSTANT (val))
16157         return NULL_TREE;
16158       TREE_OPERAND (node, 0) = val;
16159       val = fold_constant_for_init (TREE_OPERAND (node, 1), context);
16160       if (val == NULL_TREE || ! TREE_CONSTANT (val))
16161         return NULL_TREE;
16162       TREE_OPERAND (node, 1) = val;
16163       val = fold_constant_for_init (TREE_OPERAND (node, 2), context);
16164       if (val == NULL_TREE || ! TREE_CONSTANT (val))
16165         return NULL_TREE;
16166       TREE_OPERAND (node, 2) = val;
16167       return integer_zerop (TREE_OPERAND (node, 0)) ? TREE_OPERAND (node, 1)
16168         : TREE_OPERAND (node, 2);
16169
16170     case VAR_DECL:
16171     case FIELD_DECL:
16172       if (! FIELD_FINAL (node)
16173           || DECL_INITIAL (node) == NULL_TREE)
16174         return NULL_TREE;
16175       val = DECL_INITIAL (node);
16176       /* Guard against infinite recursion. */
16177       DECL_INITIAL (node) = NULL_TREE;
16178       val = fold_constant_for_init (val, node);
16179       if (val != NULL_TREE && TREE_CODE (val) != STRING_CST)
16180         val = try_builtin_assignconv (NULL_TREE, TREE_TYPE (node), val);
16181       DECL_INITIAL (node) = val;
16182       return val;
16183
16184     case EXPR_WITH_FILE_LOCATION:
16185       /* Compare java_complete_tree and resolve_expression_name. */
16186       if (!EXPR_WFL_NODE (node) /* Or a PRIMARY flag ? */
16187           || TREE_CODE (EXPR_WFL_NODE (node)) == IDENTIFIER_NODE)
16188         {
16189           tree name = EXPR_WFL_NODE (node);
16190           tree decl;
16191           if (PRIMARY_P (node))
16192             return NULL_TREE;
16193           else if (! QUALIFIED_P (name))
16194             {
16195               decl = lookup_field_wrapper (DECL_CONTEXT (context), name);
16196               if (decl == NULL_TREE
16197                   || (! FIELD_STATIC (decl) && ! FIELD_FINAL (decl)))
16198                 return NULL_TREE;
16199               return fold_constant_for_init (decl, decl);
16200             }
16201           else
16202             {
16203               /* Install the proper context for the field resolution.
16204                  The prior context is restored once the name is
16205                  properly qualified. */
16206               tree saved_current_class = current_class;
16207               /* Wait until the USE_COMPONENT_REF re-write.  FIXME. */
16208               current_class = DECL_CONTEXT (context);
16209               qualify_ambiguous_name (node);
16210               current_class = saved_current_class;
16211               if (resolve_field_access (node, &decl, NULL)
16212                   && decl != NULL_TREE)
16213                 return fold_constant_for_init (decl, decl);
16214               return NULL_TREE;
16215             }
16216         }
16217       else
16218         {
16219           op0 = TREE_OPERAND (node, 0);
16220           val = fold_constant_for_init (op0, context);
16221           if (val == NULL_TREE || ! TREE_CONSTANT (val))
16222             return NULL_TREE;
16223           TREE_OPERAND (node, 0) = val;
16224           return val;
16225         }
16226
16227 #ifdef USE_COMPONENT_REF
16228     case IDENTIFIER:
16229     case COMPONENT_REF:
16230       ?;
16231 #endif
16232
16233     default:
16234       return NULL_TREE;
16235     }
16236 }
16237
16238 #ifdef USE_COMPONENT_REF
16239 /* Context is 'T' for TypeName, 'P' for PackageName,
16240    'M' for MethodName, 'E' for ExpressionName, and 'A' for AmbiguousName. */
16241
16242 tree
16243 resolve_simple_name (tree name, int context)
16244 {
16245 }
16246
16247 tree
16248 resolve_qualified_name (tree name, int context)
16249 {
16250 }
16251 #endif
16252
16253 void
16254 init_src_parse (void)
16255 {
16256   /* Sanity check; we've been bit by this before.  */
16257   if (ARRAY_SIZE (ctxp->modifier_ctx) != MODIFIER_TK - PUBLIC_TK)
16258     abort ();
16259 }
16260
16261 \f
16262
16263 /* This section deals with the functions that are called when tables
16264    recording class initialization information are traversed.  */
16265
16266 /* Attach to PTR (a block) the declaration found in ENTRY. */
16267
16268 static int
16269 attach_init_test_initialization_flags (void **entry, void *ptr)
16270 {
16271   tree block = (tree)ptr;
16272   struct treetreehash_entry *ite = (struct treetreehash_entry *) *entry;
16273
16274   if (block != error_mark_node)
16275     {
16276       TREE_CHAIN (ite->value) = BLOCK_EXPR_DECLS (block);
16277       BLOCK_EXPR_DECLS (block) = ite->value;
16278     }
16279   return true;
16280 }
16281
16282 /* This function is called for each class that is known definitely
16283    initialized when a given static method was called. This function
16284    augments a compound expression (INFO) storing all assignment to
16285    initialized static class flags if a flag already existed, otherwise
16286    a new one is created.  */
16287
16288 static int
16289 emit_test_initialization (void **entry_p, void *info)
16290 {
16291   tree l = (tree) info;
16292   tree decl, init;
16293   tree key = (tree) *entry_p;
16294   tree *ite;
16295   htab_t cf_ht = DECL_FUNCTION_INIT_TEST_TABLE (current_function_decl);
16296
16297   /* If we haven't found a flag and we're dealing with self registered
16298      with current_function_decl, then don't do anything. Self is
16299      always added as definitely initialized but this information is
16300      valid only if used outside the current function. */
16301   if (current_function_decl == TREE_PURPOSE (l)
16302       && java_treetreehash_find (cf_ht, key) == NULL)
16303     return true;
16304
16305   ite = java_treetreehash_new (cf_ht, key);
16306
16307   /* If we don't have a variable, create one and install it. */
16308   if (*ite == NULL)
16309     {
16310       tree block;
16311
16312       decl = build_decl (VAR_DECL, NULL_TREE, boolean_type_node);
16313       MAYBE_CREATE_VAR_LANG_DECL_SPECIFIC (decl);
16314       LOCAL_CLASS_INITIALIZATION_FLAG (decl) = 1;
16315       DECL_CONTEXT (decl) = current_function_decl;
16316       DECL_INITIAL (decl) = boolean_true_node;
16317       /* Don't emit any symbolic debugging info for this decl.  */
16318       DECL_IGNORED_P (decl) = 1;
16319
16320       /* The trick is to find the right context for it. */
16321       block = BLOCK_SUBBLOCKS (GET_CURRENT_BLOCK (current_function_decl));
16322       TREE_CHAIN (decl) = BLOCK_EXPR_DECLS (block);
16323       BLOCK_EXPR_DECLS (block) = decl;
16324       *ite = decl;
16325     }
16326   else
16327     decl = *ite;
16328
16329   /* Now simply augment the compound that holds all the assignments
16330      pertaining to this method invocation. */
16331   init = build (MODIFY_EXPR, boolean_type_node, decl, boolean_true_node);
16332   TREE_SIDE_EFFECTS (init) = 1;
16333   TREE_VALUE (l) = add_stmt_to_compound (TREE_VALUE (l), void_type_node, init);
16334   TREE_SIDE_EFFECTS (TREE_VALUE (l)) = 1;
16335
16336   return true;
16337 }
16338
16339 #include "gt-java-parse.h"
16340 #include "gtype-java.h"