Skip to main content
summaryrefslogtreecommitdiffstats
blob: b4f55fe08253d89f5c3fa0dd9e6d379254037d11 (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
/*
Copyright (c) 2008 Arno Haase.
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

Contributors:
    Arno Haase - initial API and implementation
 */
package org.eclipse.xtend.backend.expr;

import java.util.Collection;

import org.eclipse.xtend.backend.common.BackendType;
import org.eclipse.xtend.backend.common.ExecutionContext;
import org.eclipse.xtend.backend.common.ExpressionBase;
import org.eclipse.xtend.backend.common.SourcePos;
import org.eclipse.xtend.backend.syslib.CollectionOperations;
import org.eclipse.xtend.backend.types.builtin.CollectionType;


//TODO refactor: middle ends only use this, and a subsequent step differentiates / optimizes to the other two


/**
 * This class deals with the case where the middle end can not decide statically whether
 *  a property is to be resolved on a single object or on a collection
 *  
 * @author Arno Haase (http://www.haase-consulting.com)
 */
public final class PropertyOnWhateverExpression extends ExpressionBase {
    private final ExpressionBase _inner;
    private final String _propertyName;

    public PropertyOnWhateverExpression (ExpressionBase inner, String propertyName, SourcePos sourcePos) {
        super (sourcePos);
        
        _inner = inner;
        _propertyName = propertyName;
    }

    @Override
    protected Object evaluateInternal(ExecutionContext ctx) {
        final Object o = _inner.evaluate(ctx);
        if (o == null) {
            ctx.logNullDeRef (getPos());
            return null;
        }

        final BackendType t = ctx.getTypesystem().findType (o);
        
        if (CollectionType.INSTANCE.isAssignableFrom(t)) {
            if (isProperty (t, _propertyName))
                return t.getProperty (ctx, o, _propertyName);
            
            final Collection<Object> result = CollectionOperations.createMatchingCollection ((Collection<?>) o);

            for (Object obj: (Collection<?>) o) 
                CollectionOperations.addFlattened (result, ctx.getTypesystem().findType(obj).getProperty(ctx, obj, _propertyName));

            return result;
        }
        else
            return t.getProperty (ctx, o, _propertyName);
    }

    private boolean isProperty (BackendType t, String propName) {
        return t.getProperties().containsKey (propName);
    }
}

Back to the top