Skip to main content
summaryrefslogtreecommitdiffstats
blob: 4a23cef3d4697a896db5266ae0c5695d00994281 (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
/*******************************************************************************
 * Copyright (c) 2009, 2017 Cloudsmith Inc. 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
 *
 * Contributors:
 *     Cloudsmith Inc. - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.internal.p2.metadata.expression;

import java.util.*;
import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext;

/**
 * An expression that will collect items recursively based on a <code>rule</code>.
 * The <code>rule</code> is applied for each item in the <code>collection</code> and
 * is supposed to create a new collection. The <code>rule</code> is then applied for each item
 * in the new collection. All items are collected into a set and items that are already
 * in that set will not be perused again. The set becomes the result of the traversal.
 */
final class Traverse extends CollectionFilter {

	Traverse(Expression collection, LambdaExpression lambda) {
		super(collection, lambda);
	}

	@Override
	public Object evaluate(IEvaluationContext context, Iterator<?> itor) {
		return evaluateAsIterator(context, itor);
	}

	@Override
	public Iterator<?> evaluateAsIterator(IEvaluationContext context, Iterator<?> iterator) {
		HashSet<Object> collector = new HashSet<>();
		while (iterator.hasNext())
			traverse(collector, iterator.next(), context);
		return collector.iterator();
	}

	@Override
	public int getExpressionType() {
		return TYPE_TRAVERSE;
	}

	@Override
	public String getOperator() {
		return KEYWORD_TRAVERSE;
	}

	void traverse(Set<Object> collector, Object parent, IEvaluationContext context) {
		if (collector.add(parent)) {
			Variable variable = lambda.getItemVariable();
			context = EvaluationContext.create(context, variable);
			variable.setValue(context, parent);
			Iterator<?> subIterator = lambda.evaluateAsIterator(context);
			while (subIterator.hasNext())
				traverse(collector, subIterator.next(), context);
		}
	}
}

Back to the top