blob: ae14f64f4c4f95aef4359ef2750d8b18a71b0341 (
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
|
/*******************************************************************************
* Copyright (c) 2005-2009 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.internal.xtend.expression.ast;
import java.util.Set;
import org.eclipse.xtend.expression.AnalysationIssue;
import org.eclipse.xtend.expression.EvaluationException;
import org.eclipse.xtend.expression.ExecutionContext;
import org.eclipse.xtend.typesystem.Type;
/**
* @author Sven Efftinge (http://www.efftinge.de)
* @author Arno Haase
* @author Bernd Kolb
*/
public class IfExpression extends Expression {
private Expression condition;
private Expression thenPart;
private Expression elsePart;
public IfExpression(final Expression condition,
final Expression thenPart, final Expression elsePart) {
this.condition = condition;
this.thenPart = thenPart;
this.elsePart = elsePart;
}
public Expression getCondition() {
return condition;
}
public Expression getElsePart() {
return elsePart;
}
public Expression getThenPart() {
return thenPart;
}
@Override
public Object evaluateInternal(final ExecutionContext ctx) {
Object val = getCondition().evaluate(ctx);
if (val == null)
val = Boolean.FALSE;
if (!(val instanceof Boolean))
throw new EvaluationException("Boolean expected!", getCondition(), ctx);
if (((Boolean) val).booleanValue())
return getThenPart().evaluate(ctx);
else {
if (getElsePart()==null)
return null;
return getElsePart().evaluate(ctx);
}
}
public Type analyzeInternal(final ExecutionContext ctx, final Set<AnalysationIssue> issues) {
final Type conditionType = getCondition().analyze(ctx, issues);
if (conditionType != null && !conditionType.equals(ctx.getBooleanType())) {
issues.add(new AnalysationIssue(AnalysationIssue.INCOMPATIBLE_TYPES, "Boolean expected", getCondition()));
}
final Type thenPartType = getThenPart().analyze(ctx, issues);
final Type elsePartType = getElsePart()!=null ? getElsePart().analyze(ctx, issues) : ctx.getVoidType();
if (thenPartType == null || elsePartType == null)
return null;
if (thenPartType.isAssignableFrom(elsePartType))
return elsePartType;
else if (elsePartType.isAssignableFrom(thenPartType))
return thenPartType;
else
return ctx.getObjectType();
}
@Override
protected String toStringInternal() {
return "if "+condition.toString() + " then " + thenPart + (elsePart!=null ? " else " + elsePart : "");
}
}
|