package org.metaborg.meta.nabl2.spoofax.primitives;

import java.util.List;
import java.util.Optional;

import org.metaborg.meta.nabl2.scopegraph.path.IResolutionPath;
import org.metaborg.meta.nabl2.scopegraph.terms.Label;
import org.metaborg.meta.nabl2.scopegraph.terms.Occurrence;
import org.metaborg.meta.nabl2.scopegraph.terms.Scope;
import org.metaborg.meta.nabl2.scopegraph.terms.path.Paths;
import org.metaborg.meta.nabl2.spoofax.analysis.IScopeGraphContext;
import org.metaborg.meta.nabl2.terms.ITerm;
import org.metaborg.meta.nabl2.terms.generic.TB;
import org.spoofax.interpreter.core.InterpreterException;

import com.google.common.collect.Lists;

public class SG_get_ref_resolution extends ScopeGraphPrimitive {

    public SG_get_ref_resolution() {
        super(SG_get_ref_resolution.class.getSimpleName(), 0, 0);
    }

    @Override public Optional<ITerm> call(IScopeGraphContext<?> context, ITerm term, List<ITerm> terms)
        throws InterpreterException {
        return Occurrence.matcher().match(term).<ITerm>flatMap(ref -> {
            return context.unit(ref.getIndex().getResource()).solution().flatMap(s -> {
                List<ITerm> pathTerms = Lists.newArrayListWithExpectedSize(paths.size());
                for(IResolutionPath<Scope, Label, Occurrence> path : s.getNameResolution().resolve(ref)) {
                    pathTerms.add(TB.newTuple(path.getDeclaration(), Paths.toTerm(path)));
                }
                ITerm result = TB.newList(pathTerms);
                return Optional.of(result);
            });
        });
    }

}

@@ -95,16 +95,38 @@
 ptional;
+%0Aimport java.util.Set;
 %0A%0Aimport
@@ -1148,24 +1148,137 @@
 tMap(s -%3E %7B%0A
+                final Set%3CIResolutionPath%3CScope, Label, Occurrence%3E%3E paths = s.getNameResolution().resolve(ref);%0A
             
@@ -1428,42 +1428,13 @@
 h : 
-s.getNameResolution().resolve(ref)
+paths
 ) %7B%0A

Fix unresolved reference.