Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 1abb5425a0a05ac1dff8157f02a97f640aff6b90 (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
/*******************************************************************************
 * Copyright (c) 2012, 2014 Wind River Systems, Inc. and others.
 *
 * 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
 *
 * Contributors:
 *     Markus Schorn - initial API and implementation
 *     Sergey Prigogin (Google)
 *******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics;

import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.typeFromReturnType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.ExpressionTypes.valueCategoryFromReturnType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.CVTYPE;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.TDEF;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.ast.DOMException;
import org.eclipse.cdt.core.dom.ast.IASTExpression.ValueCategory;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.IProblemBinding;
import org.eclipse.cdt.core.dom.ast.ISemanticProblem;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.IValue;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBasicType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassTemplate;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunction;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPSpecialization;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateParameterMap;
import org.eclipse.cdt.core.parser.util.ArrayUtil;
import org.eclipse.cdt.internal.core.dom.parser.CompositeValue;
import org.eclipse.cdt.internal.core.dom.parser.DependentValue;
import org.eclipse.cdt.internal.core.dom.parser.ITypeMarshalBuffer;
import org.eclipse.cdt.internal.core.dom.parser.IntegralValue;
import org.eclipse.cdt.internal.core.dom.parser.SizeofCalculator;
import org.eclipse.cdt.internal.core.dom.parser.SizeofCalculator.SizeAndAlignment;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPFunction;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPPointerType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ClassTypeHelper;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ClassTypeHelper.MethodKind;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPEvaluation;
import org.eclipse.cdt.internal.core.dom.parser.cpp.InstantiationContext;
import org.eclipse.core.runtime.CoreException;

/**
 * Performs evaluation of an expression.
 */
public class EvalTypeId extends CPPDependentEvaluation {
	public static final ICPPFunction AGGREGATE_INITIALIZATION = new CPPFunction(null) {
		@Override
		public String toString() {
			return "AGGREGATE_INITIALIZATION"; //$NON-NLS-1$
		}
	};

	private final IType fInputType;
	private final ICPPEvaluation[] fArguments;
	private final boolean fRepresentsNewExpression;
	private boolean fUsesBracedInitList; // Whether the constructor call uses { ... } instead of (...).
	private IType fOutputType;

	private ICPPFunction fConstructor = CPPFunction.UNINITIALIZED_FUNCTION;
	private boolean fCheckedIsTypeDependent;
	private boolean fIsTypeDependent;
	private boolean fCheckedIsConstantExpression;
	private boolean fIsConstantExpression;

	public EvalTypeId(IType type, IASTNode pointOfDefinition, boolean usesBracedInitList, ICPPEvaluation... arguments) {
		this(type, findEnclosingTemplate(pointOfDefinition), false, usesBracedInitList, arguments);
	}

	public EvalTypeId(IType type, IBinding templateDefinition, boolean forNewExpression, boolean usesBracedInitList,
			ICPPEvaluation... arguments) {
		super(templateDefinition);
		if (arguments == null)
			throw new NullPointerException("arguments"); //$NON-NLS-1$

		if (!CPPTemplates.isDependentType(type))
			type = SemanticUtil.getNestedType(type, TDEF);
		fInputType = type;
		fArguments = arguments;
		fRepresentsNewExpression = forNewExpression;
		fUsesBracedInitList = usesBracedInitList;
	}

	public static EvalTypeId createForNewExpression(IType type, IASTNode pointOfDefinition, boolean usesBracedInitList,
			ICPPEvaluation... arguments) {
		return new EvalTypeId(type, findEnclosingTemplate(pointOfDefinition), true, usesBracedInitList, arguments);
	}

	public IType getInputType() {
		return fInputType;
	}

	public ICPPEvaluation[] getArguments() {
		return fArguments;
	}

	public boolean representsNewExpression() {
		return fRepresentsNewExpression;
	}

	public boolean usesBracedInitList() {
		return fUsesBracedInitList;
	}

	@Override
	public boolean isInitializerList() {
		return false;
	}

	@Override
	public boolean isFunctionSet() {
		return false;
	}

	@Override
	public IType getType() {
		if (fOutputType == null) {
			fOutputType = computeType();
		}
		return fOutputType;
	}

	private IType computeType() {
		if (isTypeDependent())
			return new TypeOfDependentExpression(this);

		IType type = typeFromReturnType(fInputType);
		if (fRepresentsNewExpression)
			return new CPPPointerType(type);
		return type;
	}

	@Override
	public IValue getValue() {
		if (isValueDependent())
			return DependentValue.create(this);
		if (isTypeDependent())
			return DependentValue.create(this);
		if (fRepresentsNewExpression)
			return IntegralValue.UNKNOWN;

		IType inputType = SemanticUtil.getNestedType(fInputType, CVTYPE);
		if (inputType instanceof ICPPClassType) {
			ICPPClassType classType = (ICPPClassType) inputType;
			IBinding ctor = getConstructor();
			if (EvalUtil.isCompilerGeneratedCtor(ctor)) {
				return CompositeValue.create(classType);
			} else if (ctor == AGGREGATE_INITIALIZATION) {
				return CompositeValue.create(new EvalInitList(fArguments, getTemplateDefinition()), classType);
			} else if (ctor != null) {
				EvalConstructor evalCtor = new EvalConstructor(classType, (ICPPConstructor) ctor, fArguments,
						getTemplateDefinition());
				ICPPEvaluation computedEvalCtor = evalCtor.computeForFunctionCall(new ActivationRecord(),
						new ConstexprEvaluationContext());
				return computedEvalCtor.getValue();
			} else {
				return IntegralValue.ERROR;
			}
		}
		if (fArguments.length == 0 || isEmptyInitializerList(fArguments)) {
			if (inputType instanceof ICPPBasicType) {
				switch (((ICPPBasicType) inputType).getKind()) {
				case eInt:
				case eInt128:
				case eDouble:
				case eBoolean:
				case eFloat:
				case eFloat128:
				case eNullPtr:
				case eChar:
				case eChar16:
				case eChar32:
				case eWChar:
					return IntegralValue.create(0l);
				case eUnspecified:
				case eVoid:
				default:
					return IntegralValue.UNKNOWN;
				}
			}
		}
		if (fArguments.length == 1) {
			IValue argVal = fArguments[0].getValue();
			if (argVal instanceof IntegralValue && argVal.numberValue() != null) {
				// Cast signed integer to unsigned.
				Long val = argVal.numberValue().longValue();
				if (val < 0 && inputType instanceof ICPPBasicType && ((ICPPBasicType) inputType).isUnsigned()) {
					SizeAndAlignment sizeAndAlignment = SizeofCalculator.getSizeAndAlignment(inputType);
					if (sizeAndAlignment != null) {
						long sizeof = sizeAndAlignment.size;
						if (sizeof > 4) {
							// Java's "long" can't represent the full range of an 64-bit unsigned integer
							// in C++.
							sizeof = 4;
						}
						long range = (1L << (sizeof * 8 - 1));
						val += range;
						return IntegralValue.create(val);
					}
				}
			}
			return argVal;
		}
		return IntegralValue.UNKNOWN;
	}

	private boolean isEmptyInitializerList(ICPPEvaluation[] arguments) {
		return arguments.length == 1 && arguments[0] instanceof EvalInitList
				&& ((EvalInitList) arguments[0]).getClauses().length == 0;
	}

	@Override
	public boolean isTypeDependent() {
		if (!fCheckedIsTypeDependent) {
			fCheckedIsTypeDependent = true;
			fIsTypeDependent = CPPTemplates.isDependentType(fInputType) || containsDependentType(fArguments);
		}
		return fIsTypeDependent;
	}

	@Override
	public boolean isValueDependent() {
		if (CPPTemplates.isDependentType(fInputType))
			return true;
		for (ICPPEvaluation arg : fArguments) {
			if (arg.isValueDependent())
				return true;
		}
		return false;
	}

	@Override
	public boolean isConstantExpression() {
		if (!fCheckedIsConstantExpression) {
			fCheckedIsConstantExpression = true;
			fIsConstantExpression = computeIsConstantExpression();
		}
		return fIsConstantExpression;
	}

	private boolean computeIsConstantExpression() {
		if (getConstructor() == null && fArguments.length == 1) {
			// maybe EvalTypeID represents a conversion
			ICPPEvaluation conversionEval = maybeApplyConversion(fArguments[0], fInputType, false, false);
			if (!conversionEval.isConstantExpression())
				return false;
		}
		return !fRepresentsNewExpression && areAllConstantExpressions(fArguments)
				&& isNullOrConstexprFunc(getConstructor());
	}

	@Override
	public boolean isEquivalentTo(ICPPEvaluation other) {
		if (!(other instanceof EvalTypeId)) {
			return false;
		}
		EvalTypeId o = (EvalTypeId) other;
		return fInputType.isSameType(o.fInputType) && areEquivalentEvaluations(fArguments, o.fArguments)
				&& fRepresentsNewExpression == o.fRepresentsNewExpression
				&& fUsesBracedInitList == o.fUsesBracedInitList;
	}

	@Override
	public ValueCategory getValueCategory() {
		return valueCategoryFromReturnType(fInputType);
	}

	public ICPPFunction getConstructor() {
		if (fConstructor == CPPFunction.UNINITIALIZED_FUNCTION) {
			fConstructor = computeConstructor();
		}
		return fConstructor;
	}

	private static boolean allConstructorsAreCompilerGenerated(ICPPConstructor[] constructors) {
		for (ICPPConstructor constructor : constructors) {
			if (!EvalUtil.isCompilerGeneratedCtor(constructor))
				return false;
		}
		return true;
	}

	private ICPPFunction computeConstructor() {
		if (isTypeDependent())
			return null;

		IType simplifiedType = SemanticUtil.getNestedType(fInputType, TDEF | CVTYPE);
		if (simplifiedType instanceof ICPPClassType) {
			ICPPClassType classType = (ICPPClassType) simplifiedType;
			ICPPEvaluation[] arguments = fArguments;
			ICPPConstructor[] constructors = classType.getConstructors();
			if (arguments.length == 1 && arguments[0] instanceof EvalInitList && !fUsesBracedInitList) {
				// List-initialization of a class (dcl.init.list-3).
				if (TypeTraits.isAggregateClass(classType)) {
					// Pretend that aggregate initialization is calling the default constructor.
					return findDefaultConstructor(classType, constructors);
				}
				if (((EvalInitList) arguments[0]).getClauses().length == 0) {
					ICPPMethod ctor = findDefaultConstructor(classType, constructors);
					if (ctor != null)
						return ctor;
				}
				ICPPConstructor[] ctors = getInitializerListConstructors(constructors);
				if (ctors.length != 0) {
					constructors = ctors;
				} else {
					arguments = ((EvalInitList) arguments[0]).getClauses();
				}
			}

			LookupData data = new LookupData(classType.getNameCharArray(), null, CPPSemantics.getCurrentLookupPoint());
			data.foundItems = constructors;
			data.setFunctionArguments(false, arguments);
			try {
				IBinding binding = CPPSemantics.resolveFunction(data, constructors, true, false);
				if (binding instanceof ICPPFunction) {
					return (ICPPFunction) binding;
				}
				if (fUsesBracedInitList && allConstructorsAreCompilerGenerated(constructors)) {
					Cost cost = AggregateInitialization.check(classType,
							new EvalInitList(arguments, getTemplateDefinition()));
					if (cost.converts())
						return AGGREGATE_INITIALIZATION;
					else
						return new CPPFunction.CPPFunctionProblem(null, ISemanticProblem.BINDING_NOT_FOUND,
								classType.getNameCharArray());
				}
				if (binding instanceof IProblemBinding && !(binding instanceof ICPPFunction))
					return new CPPFunction.CPPFunctionProblem(null, ((IProblemBinding) binding).getID(),
							classType.getNameCharArray());
			} catch (DOMException e) {
				CCorePlugin.log(e);
			}
		}
		return null;
	}

	private ICPPConstructor findDefaultConstructor(ICPPClassType classType, ICPPConstructor[] constructors) {
		for (ICPPConstructor ctor : constructors) {
			if (ctor.isImplicit() && ClassTypeHelper.getMethodKind(classType, ctor) == MethodKind.DEFAULT_CTOR)
				return ctor;
		}
		return null;
	}

	/**
	 * Returns constructors that can be called by passing a single {@code std::initializer_list}
	 * as an argument.
	 */
	private ICPPConstructor[] getInitializerListConstructors(ICPPConstructor[] constructors) {
		ICPPConstructor[] result = ICPPConstructor.EMPTY_CONSTRUCTOR_ARRAY;
		ICPPClassTemplate template = CPPVisitor.get_initializer_list();
		if (template == null)
			return result;

		for (ICPPConstructor ctor : constructors) {
			if (ctor.getRequiredArgumentCount() <= 1) {
				IType[] parameterTypes = ctor.getType().getParameterTypes();
				if (parameterTypes.length != 0) {
					IType type = parameterTypes[0];
					if (type instanceof ICPPSpecialization) {
						IBinding specialized = ((ICPPSpecialization) type).getSpecializedBinding();
						if (specialized instanceof ICPPClassTemplate && template.isSameType((IType) specialized)) {
							result = ArrayUtil.append(result, ctor);
						}
					}
				}
			}
		}
		return ArrayUtil.trim(result);
	}

	@Override
	public void marshal(ITypeMarshalBuffer buffer, boolean includeValue) throws CoreException {
		short firstBytes = ITypeMarshalBuffer.EVAL_TYPE_ID;
		if (fRepresentsNewExpression)
			firstBytes |= ITypeMarshalBuffer.FLAG1;
		if (fUsesBracedInitList)
			firstBytes |= ITypeMarshalBuffer.FLAG2;

		buffer.putShort(firstBytes);
		buffer.marshalType(fInputType);
		buffer.putInt(fArguments.length);
		for (ICPPEvaluation arg : fArguments) {
			buffer.marshalEvaluation(arg, includeValue);
		}
		marshalTemplateDefinition(buffer);
	}

	public static ICPPEvaluation unmarshal(short firstBytes, ITypeMarshalBuffer buffer) throws CoreException {
		IType type = buffer.unmarshalType();
		ICPPEvaluation[] args = null;
		int len = buffer.getInt();
		args = new ICPPEvaluation[len];
		for (int i = 0; i < args.length; i++) {
			args[i] = buffer.unmarshalEvaluation();
		}
		IBinding templateDefinition = buffer.unmarshalBinding();
		boolean forNewExpression = (firstBytes & ITypeMarshalBuffer.FLAG1) != 0;
		boolean usesBracedInitList = (firstBytes & ITypeMarshalBuffer.FLAG2) != 0;
		EvalTypeId result = new EvalTypeId(type, templateDefinition, forNewExpression, usesBracedInitList, args);
		return result;
	}

	@Override
	public ICPPEvaluation instantiate(InstantiationContext context, int maxDepth) {
		ICPPEvaluation[] args = instantiateExpressions(fArguments, context, maxDepth);
		IType type = CPPTemplates.instantiateType(fInputType, context);
		if (args == fArguments && type == fInputType)
			return this;

		EvalTypeId result = new EvalTypeId(type, getTemplateDefinition(), fRepresentsNewExpression, fUsesBracedInitList,
				args);

		if (!result.isTypeDependent()) {
			IType simplifiedType = SemanticUtil.getNestedType(type, SemanticUtil.TDEF);
			if (simplifiedType instanceof ICPPClassType) {
				// Check the constructor call and return EvalFixed.INCOMPLETE to indicate a substitution
				// failure if the call cannot be resolved.
				ICPPFunction constructor = result.getConstructor();
				if (constructor == null || constructor instanceof IProblemBinding || constructor.isDeleted()) {
					return EvalFixed.INCOMPLETE;
				}
			}
		}

		return result;
	}

	@Override
	public ICPPEvaluation computeForFunctionCall(ActivationRecord record, ConstexprEvaluationContext context) {
		ICPPFunction constructor = getConstructor();
		if (constructor != null && constructor instanceof ICPPConstructor) {
			return new EvalConstructor(fInputType, (ICPPConstructor) constructor, fArguments, getTemplateDefinition())
					.computeForFunctionCall(record, context);
		}

		ICPPEvaluation[] args = fArguments;
		for (int i = 0; i < fArguments.length; i++) {
			ICPPEvaluation arg = fArguments[i].computeForFunctionCall(record, context.recordStep());
			if (arg != fArguments[i]) {
				if (args == fArguments) {
					args = new ICPPEvaluation[fArguments.length];
					System.arraycopy(fArguments, 0, args, 0, fArguments.length);
				}
				args[i] = arg;
			}
		}

		if (args == fArguments) {
			return this;
		}
		EvalTypeId evalTypeId = new EvalTypeId(fInputType, getTemplateDefinition(), fRepresentsNewExpression,
				fUsesBracedInitList, args);
		return evalTypeId;
	}

	@Override
	public int determinePackSize(ICPPTemplateParameterMap tpMap) {
		int r = CPPTemplates.determinePackSize(fInputType, tpMap);
		for (ICPPEvaluation arg : fArguments) {
			r = CPPTemplates.combinePackSize(r, arg.determinePackSize(tpMap));
		}
		return r;
	}

	@Override
	public boolean referencesTemplateParameter() {
		for (ICPPEvaluation arg : fArguments) {
			if (arg.referencesTemplateParameter())
				return true;
		}
		return false;
	}

	@Override
	public boolean isNoexcept() {
		if (getConstructor() instanceof CPPFunction) {
			CPPFunction f = (CPPFunction) getConstructor();
			if (f != AGGREGATE_INITIALIZATION) {
				if (!EvalUtil.evaluateNoexceptSpecifier(f.getType().getNoexceptSpecifier()))
					return false;
			}
		} else if (fArguments.length == 1) {
			// maybe EvalTypeID represents a conversion
			ICPPEvaluation conversionEval = maybeApplyConversion(fArguments[0], fInputType, false, false);
			return conversionEval.isNoexcept();
		}
		for (ICPPEvaluation arg : fArguments) {
			if (!arg.isNoexcept())
				return false;
		}
		return true;
	}
}

Back to the top