Skip to main content
summaryrefslogtreecommitdiffstats
blob: c402c69ef75264d5ae453713a300eed3afca1320 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/**********************************************************************
 * This file is part of "Object Teams Development Tooling"-Software
 *
 * Copyright 2003, 2010 Fraunhofer Gesellschaft, Munich, Germany,
 * for its Fraunhofer Institute for Computer Architecture and Software
 * Technology (FIRST), Berlin, Germany and Technical University Berlin,
 * Germany.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 * $Id: AstConverter.java 23416 2010-02-03 19:59:31Z stephan $
 *
 * Please visit http://www.eclipse.org/objectteams for updates and contact.
 *
 * Contributors:
 * Fraunhofer FIRST - Initial API and implementation
 * Technical University Berlin - Initial API and implementation
 **********************************************************************/
/**
 * ObjectTeams Eclipse source extensions
 *
 * @author Markus Witte
 *
 * @date 17.09.2003
 */
package org.eclipse.objectteams.otdt.internal.core.compiler.util;

import java.util.Arrays;

import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.Expression.DecapsulationState;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.impl.IntConstant;
import org.eclipse.jdt.internal.compiler.impl.StringConstant;
import org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.ElementValuePair;
import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
import org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.objectteams.otdt.core.compiler.IOTConstants;
import org.eclipse.objectteams.otdt.core.exceptions.InternalCompilerError;
import org.eclipse.objectteams.otdt.internal.core.compiler.bytecode.ConstantPoolObjectMapper;
import org.eclipse.objectteams.otdt.internal.core.compiler.control.ITranslationStates;

/**
 * Create AST-nodes from some other representation.
 *
 * @version $Id: AstConverter.java 23416 2010-02-03 19:59:31Z stephan $
 */
public class AstConverter implements ClassFileConstants, ExtraCompilerModifiers, IOTConstants {

	static final char[] VALUE_ARG     = "value".toCharArray(); //$NON-NLS-1$
	public static final char[] ROLE_ARG_NAME = "_OT$rolearg".toCharArray(); //$NON-NLS-1$

	// ==== Mostly For RoleSplitting ====

	/**
	 * Create the interface part of a role. Transfer superInterfaces from class part to interface.
	 *
	 * Only create AST, no bindings.
	 *
	 * @param teamDeclaration
	 * @param roleClassDeclaration
	 * @return the interface AST
	 */
	public static TypeDeclaration genRoleInterface(TypeDeclaration teamDeclaration, TypeDeclaration roleClassDeclaration)
	{
		TypeDeclaration typeDeclaration =
			new TypeDeclaration(roleClassDeclaration.compilationResult); // same result as class part (might be role file)
	    // make it an interface, but clear Team and final flag if set.
		// (there is no use in marking an interface as team: it has no member types!)
	    typeDeclaration.modifiers     = (roleClassDeclaration.modifiers
											| AccSynthIfc | AccRole)
										& ~(ExtraCompilerModifiers.AccTeam|AccFinal);
	    typeDeclaration.isGenerated   = true;
		typeDeclaration.name          = roleClassDeclaration.name;
		typeDeclaration.sourceStart   = roleClassDeclaration.sourceStart;
	    typeDeclaration.sourceEnd     = roleClassDeclaration.sourceEnd;
	    if (roleClassDeclaration.isRoleFile())
	    	AstEdit.addTypeDeclaration(roleClassDeclaration.compilationUnit, typeDeclaration);

    	typeDeclaration.typeParameters= AstClone.copyTypeParameters(roleClassDeclaration.typeParameters);

		// transfer superInterfaces from class to interface:
	    if (roleClassDeclaration.superInterfaces != null) {
	        typeDeclaration.superInterfaces = roleClassDeclaration.superInterfaces;
			roleClassDeclaration.superInterfaces = null;
	    }
	    TypeReference superClass= roleClassDeclaration.superclass;
	    if (   superClass != null
	    	&& superClass instanceof SingleTypeReference
	    	&& CharOperation.equals(((SingleTypeReference)superClass).token, IOTConstants.CONFINED))
	    {
	    	// if class extends Confined mark the role interface to extend __OT__Confined instead of Object.
	    	AstGenerator gen= new AstGenerator(roleClassDeclaration.sourceStart, roleClassDeclaration.sourceEnd);
	    	typeDeclaration.superclass= gen.singleTypeReference(IOTConstants.OTCONFINED);
	    }
		return typeDeclaration;
	}

	/**
	 * Compute the modifiers for an abstract method to be included in a role interface.
	 *
	 * @param modifiers modifiers of the method as it appears in the role class.
	 * @return modifiers
	 */
	static int computeIfcpartModifiers(int modifiers) {
		return (modifiers
				| AstGenerator.AccIfcMethod)
		   		& ~(AccFinal|AccSynchronized|AccStrictfp|AccNative|AccDeprecated);
	}

	// ==== For CopyInheritance: ====

    public static AbstractMethodDeclaration createMethod(
            MethodBinding      methodBinding,
			ReferenceBinding   site,
            CompilationResult  compilationResult,
            DecapsulationState decapsulation,
            AstGenerator       gen)
    {

		if (methodBinding == null)
			return null;

		AbstractMethodDeclaration abstractMethodDeclaration;

		if (CharOperation.equals(methodBinding.selector, TypeConstants.INIT)) {
			ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult);
			constructorDeclaration.selector = site != null ? site.sourceName : methodBinding.declaringClass.sourceName;
			abstractMethodDeclaration = constructorDeclaration;
		} else  {
			MethodDeclaration methodDeclaration = new MethodDeclaration(compilationResult);

			// on these special methods see class header comment in CopyInheritance:
			if (   CharOperation.prefixEquals(IOTConstants.CAST_PREFIX, methodBinding.selector)
				|| CharOperation.prefixEquals(IOTConstants._OT_LIFT_TO, methodBinding.selector))
				methodDeclaration.returnType = new SingleTypeReference(methodBinding.returnType.internalName(),0);
			else
	            methodDeclaration.returnType = gen.typeReference(methodBinding.returnType);

			methodDeclaration.returnType.setBaseclassDecapsulation(decapsulation);
            methodDeclaration.selector = methodBinding.selector;
            TypeVariableBinding[] typeVariables= methodBinding.typeVariables();
            if (typeVariables != Binding.NO_TYPE_VARIABLES) {
            	TypeParameter[] parameters= new TypeParameter[typeVariables.length];
            	for (int i = 0; i < typeVariables.length; i++)
					parameters[i]= gen.typeParameter(typeVariables[i]);
				methodDeclaration.typeParameters= parameters;
            }
			abstractMethodDeclaration = methodDeclaration;
		}
		gen.setMethodPositions(abstractMethodDeclaration);

		abstractMethodDeclaration.modifiers = methodBinding.modifiers & ~ClassFileConstants.AccSynthetic;
		if (methodBinding.isAbstract())
			// AccSemicolonBody - flag does not exist in binary methods:
			abstractMethodDeclaration.modifiers |= AccSemicolonBody;
		abstractMethodDeclaration.arguments = createArguments(methodBinding.parameters, site, decapsulation, gen);
		abstractMethodDeclaration.isCopied = true;
		abstractMethodDeclaration.sourceMethodBinding=methodBinding;

		abstractMethodDeclaration.thrownExceptions = AstClone.copyExceptions(methodBinding, gen);

		return abstractMethodDeclaration;
	}


	public static FieldDeclaration createField(
            FieldBinding      fieldBinding,
            TypeDeclaration   roleDeclaration,
            AstGenerator      gen)
    {

		if(fieldBinding==null)
			return null;

		FieldDeclaration fieldDeclaration = new FieldDeclaration();
		fieldDeclaration.type = gen.typeReference(fieldBinding.type);

		fieldDeclaration.modifiers = (fieldBinding.modifiers &~ExtraCompilerModifiers.AccBlankFinal); // this modifier is not used on fieldDecl (AST)
		fieldDeclaration.name = fieldBinding.name;
		if (fieldBinding.copyInheritanceSrc != null)
			fieldDeclaration.copyInheritanceSrc = fieldBinding.copyInheritanceSrc;
		else
			fieldDeclaration.copyInheritanceSrc = fieldBinding;

		AnnotationBinding[] annotBindings = fieldBinding.getAnnotations();
		if (annotBindings != Binding.NO_ANNOTATIONS) {
			ProblemReporter pr = fieldBinding.isStatic() ?
						roleDeclaration.staticInitializerScope.problemReporter() :
						roleDeclaration.initializerScope.problemReporter();
			Annotation[] annotDecls = new Annotation[annotBindings.length];
			boolean hasAnnotationError = false;
			for (int i = 0; i < annotBindings.length; i++) {
				AnnotationBinding binding = annotBindings[i];
				ElementValuePair[] elementValuePairs = binding.getElementValuePairs();
				char[][] annotTypeName = binding.getAnnotationType().compoundName;
				if (elementValuePairs == Binding.NO_ELEMENT_VALUE_PAIRS) {
					annotDecls[i] = gen.markerAnnotation(annotTypeName);
				} else {
					int numPairs = elementValuePairs.length;
					char[][] names = new char[numPairs][];
					Expression[] values = new Expression[numPairs];
					for (int j = 0; j<names.length; j++) {
						names[j] = elementValuePairs[j].getName();
						Object elementValue = elementValuePairs[j].getValue();
						values[j] = annotationValues(elementValue, gen, pr);
					}
					if (values.length == 0 || values[0] == null) {
						pr.unexpectedAnnotationStructure(annotTypeName, fieldBinding.name, gen.sourceStart, gen.sourceEnd);
						hasAnnotationError = true;
					} else
					if (   numPairs == 1
						&& CharOperation.equals(names[0], TypeConstants.VALUE)) {
						annotDecls[i] = gen.singleMemberAnnotation(annotTypeName, values[0]);
					} else {
						annotDecls[i] = gen.normalAnnotation(annotTypeName, names, values);
					}
				}
			}
			if (!hasAnnotationError)
				fieldDeclaration.annotations = annotDecls;
		}

		//field initializations are copied using a RoleInitializationMethod
		return fieldDeclaration;
	}

	private static Expression annotationValues(Object elementValue, AstGenerator gen, ProblemReporter pr) {
		if (elementValue instanceof Object[]) {
			Object[] valuesArray = (Object[])elementValue;
			ArrayInitializer arrayInit = new ArrayInitializer();
			arrayInit.expressions = new Expression[valuesArray.length];
			for (int k = 0; k<valuesArray.length; k++) {
				arrayInit.expressions[k] = annotationValue(valuesArray[k], gen, pr);
				if (arrayInit.expressions[k] == null)
					return null; // error detected.
			}
			return arrayInit;
		} else {
			return annotationValue(elementValue, gen, pr);
		}
	}

	private static Expression annotationValue(Object elementValue, AstGenerator gen, ProblemReporter pr) {
		if (elementValue instanceof StringConstant)
			return gen.stringLiteral(((StringConstant)elementValue).stringValue().toCharArray());
		if (elementValue instanceof IntConstant)
			return gen.intLiteral(((IntConstant)elementValue).intValue());
		if (elementValue instanceof FieldBinding) {
			FieldBinding field = (FieldBinding) elementValue;
			if (field.isStatic()) {
				char[][] tokens = CharOperation.splitOn('.', field.declaringClass.readableName());
				tokens = CharOperation.arrayConcat(tokens, field.name);
				return gen.qualifiedNameReference(tokens);
			}
		}
		return null;
	}

	public static TypeDeclaration createNestedType (
            char[]            name,
            int               modifiers,
			boolean 		  isNestedType,
            boolean           isPurelyCopied,
			TypeDeclaration   teamDecl,
			ReferenceBinding  tsuperRole)
    {
		TypeDeclaration enclosingTypeDecl = teamDecl;
        if (tsuperRole != null && isNestedType)
        {
        	ReferenceBinding srcEnclosing = tsuperRole.enclosingType();
        	// TODO (SH): recurse even more
          	TypeDeclaration[] members = enclosingTypeDecl.memberTypes;
          	if (members != null)
          		for (int i=0; i<members.length; i++) {
          			if (CharOperation.equals(members[i].name, srcEnclosing.internalName())) {
          				enclosingTypeDecl =	members[i];
          				break;
          			}
          		}
        }

		TypeDeclaration nestedType =
            new TypeDeclaration(enclosingTypeDecl.compilationResult);
		nestedType.name      = name;
		nestedType.modifiers = modifiers;
        nestedType.isGenerated    = true;
        nestedType.isPurelyCopied = isPurelyCopied;
        int sStart = enclosingTypeDecl.sourceStart;
        int sEnd = enclosingTypeDecl.sourceEnd;
        if (enclosingTypeDecl.superclass != null) {
        	sStart = enclosingTypeDecl.superclass.sourceStart;
        	sEnd   = enclosingTypeDecl.superclass.sourceEnd;
        }
		nestedType.declarationSourceStart = sStart;
		nestedType.declarationSourceEnd   = sEnd;
        nestedType.sourceStart = sStart;
        nestedType.sourceEnd   = sEnd;
        nestedType.bodyStart   = sStart;
        nestedType.bodyEnd     = sEnd;
        AstGenerator gen = new AstGenerator(sStart, sEnd);
        if (tsuperRole != null && tsuperRole.isInterface()) {
        	ReferenceBinding superclass= tsuperRole.superclass();
        	if (superclass != null && CharOperation.equals(superclass.internalName(), IOTConstants.OTCONFINED)) {
        		nestedType.superclass= gen.qualifiedTypeReference(IOTConstants.ORG_OBJECTTEAMS_TEAM_OTCONFINED);
        		nestedType.superclass.resolvedType= superclass;
        	}
        }

        if (tsuperRole != null && tsuperRole.isLocalType()) {
			nestedType.bits  |= ASTNode.IsLocalType;
			if (tsuperRole.isAnonymousType()) {
				// have no name, need at least a super type
				// (otherwise ClassScope.checkAndSetModifiers() will fail)
				ReferenceBinding superType;
				ReferenceBinding[] superIfcs = tsuperRole.superInterfaces();
				if (superIfcs != Binding.NO_SUPERINTERFACES)
					superType = superIfcs[0];
				else
					superType = tsuperRole.superclass();
				nestedType.allocation = new QualifiedAllocationExpression();
				nestedType.allocation.type = gen.typeReference(superType);
				nestedType.allocation.anonymousType = nestedType;
			}
			AstEdit.addLocalTypeDeclaration(enclosingTypeDecl, nestedType);
        } else {
        	AstEdit.addMemberTypeDeclaration(enclosingTypeDecl, nestedType);
        }

        if (tsuperRole != null && tsuperRole.roleModel != null && tsuperRole.roleModel.isRoleFile()) {
        	// for role copied from a role file create an enclosing CUD to allow for
        	// late role catch-up of this phantom role.
        	ProblemReporter reporter = enclosingTypeDecl.scope.problemReporter();
        	CompilationResult compilationResult= new CompilationResult("nofile".toCharArray(), 0, 0, 0);  //$NON-NLS-1$
        	CompilationUnitDeclaration cud = new CompilationUnitDeclaration(reporter, compilationResult, 0);
        	nestedType.compilationResult= compilationResult;
        	nestedType.compilationUnit = cud;
        	cud.types= new TypeDeclaration[] { nestedType };
        	char[][] enclosingName = enclosingTypeDecl.binding.compoundName;
			char[][] tokens= CharOperation.arrayConcat(enclosingName, nestedType.name);
        	long[] positions= new long[tokens.length];
        	Arrays.fill(positions, 0L);
        	cud.currentPackage= new ImportReference(enclosingName, positions, false, ExtraCompilerModifiers.AccTeam);
        }

        // Create TypeBindings for this type
        enclosingTypeDecl.scope.addGeneratedType(nestedType);

        int state= enclosingTypeDecl.getModel().getState();
        if (enclosingTypeDecl.isTeam())
        	state= enclosingTypeDecl.getTeamModel().getState();

        // Create Type-Hierarchy?
        nestedType.scope.connectTypeHierarchyForGenerated(state>=ITranslationStates.STATE_LENV_CONNECT_TYPE_HIERARCHY);


        // don't set past the state of the enclosing team:
        state = Math.min(state, ITranslationStates.STATE_LENV_CONNECT_TYPE_HIERARCHY);

        if (nestedType.getRoleModel() != null)
        	nestedType.getRoleModel().setState(state);
        if (nestedType.isTeam() && nestedType.getTeamModel() != null)
        	nestedType.getTeamModel().setState(state);

		return nestedType;
	}

	/**
	 * Create method arguments which match the given parameters.
	 * If a site is given, try to map all types to this new context.
	 * @param parameters
	 * @param site class for whose context types shall be adjusted, or null.
	 * @return an array of arguments names "arg<n>" with types according to parameters.
	 */
	private static Argument[] createArguments(
            TypeBinding[]      parameters,
			ReferenceBinding   site,
			DecapsulationState decapsulation,
			AstGenerator       gen)
    {
		if(parameters==null || parameters.length == 0)
			return null;

		int length=parameters.length;
		Argument[] arguments = new Argument[length];

		for(int i=0;i<length;i++){
			TypeBinding tb = parameters[i];
			if (site != null	&& (tb instanceof ReferenceBinding))
				tb = ConstantPoolObjectMapper.searchRoleClass((ReferenceBinding)tb, site);
			TypeReference tr = gen.typeReference(tb);
			tr.setBaseclassDecapsulation(decapsulation);
			char[] bez = ("arg"+i).toCharArray(); // dummy argument names, don't have original names. //$NON-NLS-1$
			arguments[i] = new Argument(bez,0,tr,0);

		}
		return arguments;
	}

    /** If a generated method was copied from tsuper, adjust its flags and argument names,
     *  but leave its signature for true overriding.
     *  Thus copying generated methods does the job of signature weakening.
     */
    public static MethodDeclaration findAndAdjustCopiedMethod(
    		TypeDeclaration teamDecl,
			char[]          methodName,
			Argument[]      arguments)
    {
        int argumentsCount = arguments == null ? 0 : arguments.length;
		AbstractMethodDeclaration foundMethod =
        	TypeAnalyzer.findMethodDecl(teamDecl, methodName, argumentsCount);
        if (foundMethod != null)
        {
        	if (!foundMethod.isCopied) {
        		// could mean different things
        		if (!foundMethod.isGenerated) {
        			// it is a user defined method!
        			foundMethod.scope.problemReporter().overridingPredefined(foundMethod);
        			return null;
        		}
        		throw new InternalCompilerError("Generated methods conflicting with each other: "+new String(foundMethod.selector)); //$NON-NLS-1$
        	}
        	foundMethod.isCopied = false;
        	foundMethod.isGenerated = true;
        	foundMethod.modifiers &= ~(AccAbstract|AccSemicolonBody);
        	if (arguments != null) { // redundant via correlation with argumentsCount
        		for (int i = 0; i < argumentsCount; i++) {
        			foundMethod.arguments[i].updateName(arguments[i].name);
        		}
			}
        	if (foundMethod.binding != null) {
        		foundMethod.binding.modifiers &= ~(AccAbstract);
        		if (foundMethod.binding.copyInheritanceSrc != null) {
        			// not directly copied any more but overriding a tsuper version:
        			foundMethod.binding.addOverriddenTSuper(foundMethod.binding.copyInheritanceSrc);
        			foundMethod.binding.setCopyInheritanceSrc(null);
        		}
        	}
        	return (MethodDeclaration)foundMethod;
        }
        return null;
    }

	/**
	 * Create the declaration of a role method to be inserted into the role interface.
	 * @param typeDecl (only need the CompilationResult)
	 * @param classpartMethod
	 * @return the method AST
	 */
	public static MethodDeclaration genRoleIfcMethod(TypeDeclaration typeDecl, MethodDeclaration classpartMethod) {
		MethodDeclaration newmethod = AstClone.copyMethod(typeDecl, classpartMethod, null/*AstGenerator*/);
		// TODO (SH): AccNative is even illegal!
		newmethod.modifiers   = computeIfcpartModifiers(classpartMethod.modifiers);
		classpartMethod.interfacePartMethod = newmethod;
		return newmethod;
	}

	/**
	 * Create the declaration of a role method to be inserted into the role interface.
	 * @param teamDecl
	 * @param classpartMethod
	 * @return the method AST
	 */
	public static MethodDeclaration genIfcMethodFromBinding(TypeDeclaration teamDecl,
													 MethodBinding classpartMethod,
													 AstGenerator  gen)
	{
		MethodDeclaration newmethod =
		    new MethodDeclaration(teamDecl.compilationResult);

		newmethod.selector    = classpartMethod.selector;
		newmethod.modifiers   = computeIfcpartModifiers(classpartMethod.modifiers);
		// special case of copying cast method for non-public role:
		if (   CharOperation.prefixEquals(IOTConstants.CAST_PREFIX, classpartMethod.selector)
			&& !((ReferenceBinding)classpartMethod.returnType).isPublic())
		{
			newmethod.modifiers = AccProtected|AstGenerator.AccIfcMethod; // see StandardElementGenerator.getCastMethod();
		}

		newmethod.isGenerated = true; // don't try to parse it etc..
		// no position, created from binding, so use pre-set default location
		gen.setMethodPositions(newmethod);

		newmethod.arguments = AstConverter.createArgumentsFromParameters(classpartMethod.parameters, gen);

		newmethod.returnType = gen.typeReference(classpartMethod.returnType);

		if (classpartMethod.typeVariables() != Binding.NO_TYPE_VARIABLES) {
			TypeVariableBinding[] typeVarBindings = classpartMethod.typeVariables;
			newmethod.typeParameters = new TypeParameter[typeVarBindings.length];
			for (int i = 0; i < typeVarBindings.length; i++) {
				newmethod.typeParameters[i] = gen.typeParameter(typeVarBindings[i]);
			}
		}

		newmethod.thrownExceptions = AstClone.copyExceptions(classpartMethod, gen);
		return newmethod;
	}

	/**
	 * Create arguments from type bindings by assigning dummy names.
	 * @param parameters template for the new arguments.
	 * @return an array of new Arguments (named "arg<n>")
	 */
	public static Argument[] createArgumentsFromParameters(TypeBinding[] parameters, AstGenerator gen) {
		if (parameters.length == 0)
			return null;
		Argument[] newArguments = new Argument[parameters.length];
		for (int a=0; a<parameters.length; a++) {
		    TypeBinding param = parameters[a];
		    newArguments[a] = new Argument(
		            ("arg"+a).toCharArray(),  //$NON-NLS-1$
		            gen.pos,
		            gen.typeReference(param),
		            /*modifiers*/0);
		}
		return newArguments;
	}
}

//Markus Witte}

Back to the top