下面列出了org.eclipse.jface.text.codemining.ICodeMining#org.eclipse.xtext.xbase.XExpression 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Test if the given expression has side effects.
*
* @param expression the expression.
* @param context the list of context expressions.
* @return {@code true} if the expression has side effects.
*/
protected Boolean _hasSideEffects(XTryCatchFinallyExpression expression, ISideEffectContext context) {
final List<Map<String, List<XExpression>>> buffers = new ArrayList<>();
Map<String, List<XExpression>> buffer = context.createVariableAssignmentBufferForBranch();
if (hasSideEffects(expression.getExpression(), context.branch(buffer))) {
return true;
}
buffers.add(buffer);
for (final XCatchClause clause : expression.getCatchClauses()) {
context.open();
try {
buffer = context.createVariableAssignmentBufferForBranch();
if (hasSideEffects(clause.getExpression(), context.branch(buffer))) {
return true;
}
buffers.add(buffer);
} finally {
context.close();
}
}
context.mergeBranchVariableAssignments(buffers);
if (hasSideEffects(expression.getFinallyExpression(), context)) {
return true;
}
return false;
}
/** {@inheritDoc}.
*
* <p>This function is overriden for:<ul>
* <li>The XAbstractFeatureCall statements are not considered as potential early exit causes.
* in the super function. We need to mark the dead code for the XAbstractFeatureCall statements
* which refer to a function with the {@link EarlyExit} annotation.</li>
* <li>Mark as dead the code after a "break" statement.</li>
* </ul>
*/
@Override
@Check
public void checkDeadCode(XBlockExpression block) {
final EList<XExpression> expressions = block.getExpressions();
final int size = expressions.size();
for (int i = 0; i < size - 1; ++i) {
final XExpression expression = expressions.get(i);
if (this.earlyExitComputer.isEarlyExit(expression)) {
if (expression instanceof XAbstractFeatureCall) {
if (this.earlyExitComputer.isEarlyExitAnnotatedElement(
((XAbstractFeatureCall) expression).getFeature())) {
markAsDeadCode(expressions.get(i + 1));
}
} else {
// XAbstractFeatureCall does already a decent job for its argument lists
// no additional error necessary
markAsDeadCode(expressions.get(i + 1));
}
return;
} else if (this.earlyExitComputer.isEarlyExitLoop(expression)) {
markAsDeadCode(expressions.get(i + 1));
}
}
}
@Override
protected void _format(XForLoopExpression expr, IFormattableDocument document) {
final ISemanticRegionsFinder regionFor = this.textRegionExtensions.regionFor(expr);
document.append(regionFor.keyword(this.keywords.getForKeyword()), ONE_SPACE);
final JvmFormalParameter declaredParam = expr.getDeclaredParam();
document.prepend(declaredParam, NO_SPACE);
document.append(declaredParam, ONE_SPACE);
document.format(declaredParam);
final XExpression forExpression = expr.getForExpression();
document.prepend(forExpression, ONE_SPACE);
document.append(forExpression, NO_SPACE);
document.format(forExpression);
final XExpression eachExpression = expr.getEachExpression();
if (eachExpression != null) {
formatBody(eachExpression, true, document);
} else {
document.prepend(regionFor.keyword(this.keywords.getSemicolonKeyword()), NO_SPACE);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setEachExpression(XExpression newEachExpression)
{
if (newEachExpression != eachExpression)
{
NotificationChain msgs = null;
if (eachExpression != null)
msgs = ((InternalEObject)eachExpression).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - XbasePackage.XFOR_LOOP_EXPRESSION__EACH_EXPRESSION, null, msgs);
if (newEachExpression != null)
msgs = ((InternalEObject)newEachExpression).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - XbasePackage.XFOR_LOOP_EXPRESSION__EACH_EXPRESSION, null, msgs);
msgs = basicSetEachExpression(newEachExpression, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, XbasePackage.XFOR_LOOP_EXPRESSION__EACH_EXPRESSION, newEachExpression, newEachExpression));
}
@Test
public void testSwitchDeclaredParameter() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("{");
_builder.newLine();
_builder.append("\t");
_builder.append("switch Object x : \"lalala\" {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final XExpression block = this.expression(_builder);
this._validationTestHelper.assertNoErrors(block);
this._validationTestHelper.assertWarning(block, TypesPackage.Literals.JVM_FORMAL_PARAMETER, IssueCodes.UNUSED_LOCAL_VARIABLE);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setThen(XExpression newThen)
{
if (newThen != then)
{
NotificationChain msgs = null;
if (then != null)
msgs = ((InternalEObject)then).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - XbasePackage.XCASE_PART__THEN, null, msgs);
if (newThen != null)
msgs = ((InternalEObject)newThen).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - XbasePackage.XCASE_PART__THEN, null, msgs);
msgs = basicSetThen(newThen, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, XbasePackage.XCASE_PART__THEN, newThen, newThen));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setOperand(XExpression newOperand)
{
if (newOperand != operand)
{
NotificationChain msgs = null;
if (operand != null)
msgs = ((InternalEObject)operand).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - XbasePackage.XPOSTFIX_OPERATION__OPERAND, null, msgs);
if (newOperand != null)
msgs = ((InternalEObject)newOperand).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - XbasePackage.XPOSTFIX_OPERATION__OPERAND, null, msgs);
msgs = basicSetOperand(newOperand, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, XbasePackage.XPOSTFIX_OPERATION__OPERAND, newOperand, newOperand));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case SarlPackage.SARL_BEHAVIOR_UNIT__NAME:
setName((JvmParameterizedTypeReference)null);
return;
case SarlPackage.SARL_BEHAVIOR_UNIT__GUARD:
setGuard((XExpression)null);
return;
case SarlPackage.SARL_BEHAVIOR_UNIT__EXPRESSION:
setExpression((XExpression)null);
return;
}
super.eUnset(featureID);
}
@Test
public void testTypeOnlyRegisteredOnce_04() throws Exception {
XNumberLiteral expression = ((XNumberLiteral) expression("1"));
resolver.initializeFrom(expression);
PublicResolvedTypes resolution = new PublicResolvedTypes(resolver);
AnyTypeReference any = resolution.getReferenceOwner().newAnyTypeReference();
new ExpressionBasedRootTypeComputationState(resolution, resolver.getBatchScopeProvider().newSession(expression.eResource()),
expression, any).computeTypes();
Map<XExpression, List<TypeData>> expressionTypes = resolution.basicGetExpressionTypes();
TreeIterator<EObject> allContents = expression.eAllContents();
while (allContents.hasNext()) {
EObject o = allContents.next();
List<TypeData> types = expressionTypes.get((o));
assertEquals(types.toString(), 1, size(filter(types, it -> !it.isReturnType())));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setInitialValue(XExpression newInitialValue)
{
if (newInitialValue != initialValue)
{
NotificationChain msgs = null;
if (initialValue != null)
msgs = ((InternalEObject)initialValue).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - XtendPackage.XTEND_FIELD__INITIAL_VALUE, null, msgs);
if (newInitialValue != null)
msgs = ((InternalEObject)newInitialValue).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - XtendPackage.XTEND_FIELD__INITIAL_VALUE, null, msgs);
msgs = basicSetInitialValue(newInitialValue, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, XtendPackage.XTEND_FIELD__INITIAL_VALUE, newInitialValue, newInitialValue));
}
/** Convert the boolean constant to the object equivalent if possible.
*
* @param expression the expression to convert.
* @return one of the boolean constants {@link Boolean#TRUE} or {@link Boolean#FALSE},
* or {@code null} if the expression is not a constant boolean expression.
*/
@SuppressWarnings("static-method")
public Boolean toBooleanPrimitiveWrapperConstant(XExpression expression) {
if (expression instanceof XBooleanLiteral) {
return ((XBooleanLiteral) expression).isIsTrue() ? Boolean.TRUE : Boolean.FALSE;
}
if (expression instanceof XMemberFeatureCall) {
final XMemberFeatureCall call = (XMemberFeatureCall) expression;
final XExpression receiver = call.getMemberCallTarget();
if (receiver instanceof XFeatureCall) {
final XFeatureCall call2 = (XFeatureCall) receiver;
final String call2Identifier = call2.getConcreteSyntaxFeatureName();
if (Boolean.class.getSimpleName().equals(call2Identifier) || Boolean.class.getName().equals(call2Identifier)) {
final String callIdentifier = call.getConcreteSyntaxFeatureName();
if ("TRUE".equals(callIdentifier)) { //$NON-NLS-1$
return Boolean.TRUE;
} else if ("FALSE".equals(callIdentifier)) { //$NON-NLS-1$
return Boolean.FALSE;
}
}
}
}
return null;
}
@Test public void testInfiniteLoopInJava() throws Exception {
XExpression expression = expression(
"try " +
" new testdata.ClosureClient().infiniteApply(|{null})" +
"catch(Exception e)" +
" 'literal' ", true);
assertNull(interpreter.evaluate(expression, new DefaultEvaluationContext(), new CancelIndicator() {
private int i = 0;
@Override
public boolean isCanceled() {
if (i == 500)
return true;
i++;
return false;
}
}));
}
public Object internalEvaluate(final XExpression it, final Context ctx) {
if (it instanceof XBinaryOperation) {
return _internalEvaluate((XBinaryOperation)it, ctx);
} else if (it instanceof XFeatureCall) {
return _internalEvaluate((XFeatureCall)it, ctx);
} else if (it instanceof XListLiteral) {
return _internalEvaluate((XListLiteral)it, ctx);
} else if (it instanceof XMemberFeatureCall) {
return _internalEvaluate((XMemberFeatureCall)it, ctx);
} else if (it instanceof XUnaryOperation) {
return _internalEvaluate((XUnaryOperation)it, ctx);
} else if (it instanceof XBooleanLiteral) {
return _internalEvaluate((XBooleanLiteral)it, ctx);
} else if (it instanceof XCastedExpression) {
return _internalEvaluate((XCastedExpression)it, ctx);
} else if (it instanceof XNumberLiteral) {
return _internalEvaluate((XNumberLiteral)it, ctx);
} else if (it instanceof XStringLiteral) {
return _internalEvaluate((XStringLiteral)it, ctx);
} else if (it instanceof XTypeLiteral) {
return _internalEvaluate((XTypeLiteral)it, ctx);
} else if (it instanceof XAnnotation) {
return _internalEvaluate((XAnnotation)it, ctx);
} else if (it != null) {
return _internalEvaluate(it, ctx);
} else if (it == null) {
return _internalEvaluate((Void)null, ctx);
} else {
throw new IllegalArgumentException("Unhandled parameter types: " +
Arrays.<Object>asList(it, ctx).toString());
}
}
protected BucketedEObjectDescription createReceiverDescription(QualifiedName name, JvmFeature feature, XExpression receiver,
LightweightTypeReference receiverType, Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> receiverTypeParameterMapping, ExpressionBucket bucket, boolean validStaticState) {
return new InstanceFeatureDescriptionWithImplicitReceiver(
name,
feature,
receiver,
receiverType,
receiverTypeParameterMapping,
ConformanceFlags.CHECKED_SUCCESS,
bucket.getId(),
getSession().isVisible(feature),
validStaticState);
}
@Check
public void checkAssignment(XBinaryOperation binaryOperation) {
if (binaryOperation.isReassignFirstArgument()) {
XExpression leftOperand = binaryOperation.getLeftOperand();
checkAssignment(leftOperand, false);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case XbasePackage.XINSTANCE_OF_EXPRESSION__TYPE:
setType((JvmTypeReference)null);
return;
case XbasePackage.XINSTANCE_OF_EXPRESSION__EXPRESSION:
setExpression((XExpression)null);
return;
}
super.eUnset(featureID);
}
@Override
protected void collectExits(EObject expr, List<XExpression> found) {
super.collectExits(expr, found);
if (expr instanceof XAbstractFeatureCall) {
final JvmIdentifiableElement element = ((XAbstractFeatureCall) expr).getFeature();
if (this.earlyExitComputer.isEarlyExitAnnotatedElement(element)) {
found.add((XExpression) expr);
}
}
}
protected boolean isSimpleFeatureCall(XExpression switch1) {
if (switch1 instanceof XFeatureCall) {
XFeatureCall featureCall = (XFeatureCall) switch1;
return !(featureCall.getFeature() instanceof JvmOperation);
}
return false;
}
public Expression getBody() {
Expression _xblockexpression = null;
{
final XExpression expression = this.getCompilationUnit().getJvmTypesBuilder().getExpression(this.getDelegate());
_xblockexpression = this.getCompilationUnit().toExpression(expression);
}
return _xblockexpression;
}
@Override
public boolean hasSideEffects(final XExpression expr) {
if (expr instanceof XGuardExpression || expr instanceof XIssueExpression) {
return true;
}
return super.hasSideEffects(expr);
}
protected void highlightElement(XtendFunction function, IHighlightedPositionAcceptor acceptor, CancelIndicator cancelIndicator) {
highlightFeature(acceptor, function, XtendPackage.Literals.XTEND_FUNCTION__NAME, METHOD);
XExpression rootExpression = function.getExpression();
highlightRichStrings(rootExpression, acceptor);
CreateExtensionInfo createExtensionInfo = function.getCreateExtensionInfo();
if (createExtensionInfo != null) {
highlightRichStrings(createExtensionInfo.getCreateExpression(), acceptor);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetCondition(XExpression newCondition, NotificationChain msgs)
{
XExpression oldCondition = condition;
condition = newCondition;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FormatPackage.MATCHER__CONDITION, oldCondition, newCondition);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
@Override
public LightweightTypeReference getExpectedType(XExpression expression) {
LightweightTypeReference result = super.getExpectedType(expression);
if (!result.isOwnedBy(getReferenceOwner())) {
throw new IllegalArgumentException("result is not owned by this resolved types");
}
return result;
}
@Override
protected CandidateCompareResult getExpectedTypeCompareResultOther(AbstractPendingLinkingCandidate<?> right) {
if (!(right instanceof FeatureLinkingCandidate) || getState().isIgnored(IssueCodes.SUSPICIOUSLY_OVERLOADED_FEATURE))
return CandidateCompareResult.OTHER;
FeatureLinkingCandidate casted = (FeatureLinkingCandidate) right;
XExpression otherImplicitReceiver = casted.getImplicitReceiver();
if (otherImplicitReceiver != null) {
if (isStatic() == casted.isStatic()) {
if (otherImplicitReceiver instanceof XAbstractFeatureCall && getImplicitReceiver() instanceof XAbstractFeatureCall) {
JvmIdentifiableElement otherImplicitReceiverFeature = ((XAbstractFeatureCall) otherImplicitReceiver).getFeature();
if (otherImplicitReceiverFeature != ((XAbstractFeatureCall) getImplicitReceiver()).getFeature())
return CandidateCompareResult.SUSPICIOUS_OTHER;
}
}
} else {
if (isStatic() && casted.isStatic()) {
JvmIdentifiableElement otherFeature = casted.getFeature();
if (getFeature().eContainer() != otherFeature.eContainer() && otherFeature.eResource() == getExpression().eResource()) {
if (EcoreUtil.isAncestor(otherFeature.eContainer(), getFeature())) {
return CandidateCompareResult.SUSPICIOUS_OTHER;
}
}
}
}
return CandidateCompareResult.OTHER;
}
@Test
public void testBug373054() throws Exception {
StringConcatenation _builder = new StringConcatenation();
_builder.append("package testpackage");
_builder.newLine();
_builder.append("import static extension testpackage.Extension.*");
_builder.newLine();
_builder.append("class Foo {");
_builder.newLine();
_builder.append("\t");
_builder.append("def bar(){}");
_builder.newLine();
_builder.append("\t");
_builder.append("def baz(String it, String s){");
_builder.newLine();
_builder.append("\t\t");
_builder.append("zonk = s + s + s");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final XtendFile xtendFile = this.testHelper.xtendFile(XtendUnsugaredHoverTest.FILEPATH, _builder.toString());
IResourcesSetupUtil.waitForBuild();
XtendMember _get = IterableExtensions.<XtendClass>head(Iterables.<XtendClass>filter(xtendFile.getXtendTypes(), XtendClass.class)).getMembers().get(1);
final XtendFunction function = ((XtendFunction) _get);
XExpression _expression = function.getExpression();
final XBlockExpression block = ((XBlockExpression) _expression);
final XExpression call = block.getExpressions().get(0);
Assert.assertEquals("Extension.setZonk(it, s + s + s)", this.serializer.computeUnsugaredExpression(call));
}
public Context(JvmTypeReference expectedType, ClassFinder classFinder,
Map<String, JvmIdentifiableElement> visibleFeatures, Set<XExpression> alreadyEvaluating) {
this.expectedType = expectedType;
this.classFinder = classFinder;
this.visibleFeatures = visibleFeatures;
this.alreadyEvaluating = alreadyEvaluating;
}
protected Collection<IEarlyExitComputer.ExitPoint> _exitPoints(final XBlockExpression expression) {
EList<XExpression> _expressions = expression.getExpressions();
for (final XExpression child : _expressions) {
{
Collection<IEarlyExitComputer.ExitPoint> exitPoints = this.getExitPoints(child);
boolean _isNotEmpty = this.isNotEmpty(exitPoints);
if (_isNotEmpty) {
return exitPoints;
}
}
}
return Collections.<IEarlyExitComputer.ExitPoint>emptyList();
}
@Override
public Object execute(int lineno, String code) throws Exception {
final List<String> issues = new ArrayList<>();
final Collection<Resource> resources = new ArrayList<>();
final CompiledFile outFile = compile(lineno,
"package x.x.x;\n" //$NON-NLS-1$
+ "class ____Fake_Class____ {\nstatic var __fake_attr__ : Object = {\n" //$NON-NLS-1$
+ code + ";\n};\n}", //$NON-NLS-1$
issues, (it) -> {
resources.add(it);
});
try {
assertNoIssue(lineno, issues);
if (resources.isEmpty()) {
throw new NoXtextResourceException(lineno);
}
for (Resource resource : resources) {
SarlScript script = (SarlScript) resource.getContents().get(0);
SarlClass clazz = (SarlClass) script.getXtendTypes().get(0);
SarlField field = (SarlField) clazz.getMembers().get(0);
XExpression xexpression = field.getInitialValue();
final IExpressionInterpreter interpreter = this.interpreterProvider.get();
if (interpreter instanceof SarlExpressionInterpreter && this.classLoaderBuilder != null) {
final SarlExpressionInterpreter exprEvaluator = (SarlExpressionInterpreter) interpreter;
exprEvaluator.expandClassLoader(this.classLoaderBuilder);
}
IEvaluationResult result = interpreter.evaluate(xexpression);
if (result.getException() == null) {
return result.getResult();
}
throw new RuntimeException(result.getException());
}
} finally {
if (outFile != null && outFile.getRootFolder() != null) {
FileSystem.delete(outFile.getRootFolder());
}
}
return null;
}
@Override
protected IFeatureCallArguments createArgumentsForExecutable(boolean varArgs, List<XExpression> arguments,
List<JvmFormalParameter> parameters, boolean hasReceiver, ITypeReferenceOwner owner) {
if (varArgs) {
List<JvmFormalParameter> reversedParameters = Lists.newArrayList(Lists.reverse(parameters.subList(0, parameters.size() - 1)));
reversedParameters.add(parameters.get(parameters.size() - 1));
List<XExpression> reversedArgumetns = Lists.newArrayList(Lists.reverse(arguments.subList(0, parameters.size() - 1)));
reversedArgumetns.addAll(Lists.reverse(arguments.subList(parameters.size() - 1, arguments.size())));
return super.createArgumentsForExecutable(varArgs, reversedArgumetns, reversedParameters, hasReceiver, owner);
}
return super.createArgumentsForExecutable(varArgs, Lists.reverse(arguments), Lists.reverse(parameters), hasReceiver, owner);
}
protected IFeatureCallArguments toArguments(final String signature, final String invocation, final boolean receiver) {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("def void m(");
_builder.append(signature);
_builder.append(") {");
_builder.newLineIfNotEmpty();
_builder.append("\t");
_builder.append("m(");
_builder.append(invocation, "\t");
_builder.append(")");
_builder.newLineIfNotEmpty();
_builder.append("}");
_builder.newLine();
final String functionString = _builder.toString();
final XtendFunction function = this.function(functionString);
XExpression _expression = function.getExpression();
final XBlockExpression body = ((XBlockExpression) _expression);
XExpression _head = IterableExtensions.<XExpression>head(body.getExpressions());
final XFeatureCall featureCall = ((XFeatureCall) _head);
final EList<XExpression> arguments = featureCall.getFeatureCallArguments();
final JvmOperation operation = this._iXtendJvmAssociations.getDirectlyInferredOperation(function);
final IFeatureCallArguments result = this.factory.createVarArgArguments(arguments, operation.getParameters(), receiver, this.getOwner());
Class<? extends IFeatureCallArguments> _class = result.getClass();
boolean _equals = Objects.equal(_class, VarArgFeatureCallArguments.class);
Assert.assertTrue(_equals);
return result;
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}