public static Set<String> getReferencedLabels(final Step step) {
        final Set<String> referencedLabels = new HashSet<>();

        if (step instanceof Scoping) {
            final Set<String> labels = new HashSet<>(((Scoping) step).getScopeKeys());
            if (step instanceof MatchStep) {
                // if this is the last step, keep everything, else just add founds
                if (step.getNextStep() instanceof EmptyStep) {
                    labels.addAll(((MatchStep) step).getMatchEndLabels());
                    labels.addAll(((MatchStep) step).getMatchStartLabels());
                }
            }
            referencedLabels.addAll(labels);
        }

        return referencedLabels;
    }
@author Ted Wilmes (http://twilmes.org)
@author Stephen Mallette (http://stephen.genoprime.com)
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/PathUtil.java