org.eclipse.lsp4j.DocumentSymbol Java Examples

The following examples show how to use org.eclipse.lsp4j.DocumentSymbol. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocumentSymbolProcessor.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> getDocumentSymbols() {
	return CompletableFuture.supplyAsync(() -> {
		if (textDocumentItem.getUri().endsWith(".xml")) {
			try {
				List<Either<SymbolInformation, DocumentSymbol>> symbolInformations = new ArrayList<>();
				NodeList routeNodes = parserFileHelper.getRouteNodes(textDocumentItem);
				if (routeNodes != null) {
					symbolInformations.addAll(convertToSymbolInformation(routeNodes));
				}
				NodeList camelContextNodes = parserFileHelper.getCamelContextNodes(textDocumentItem);
				if (camelContextNodes != null) {
					symbolInformations.addAll(convertToSymbolInformation(camelContextNodes));
				}
				return symbolInformations;
			} catch (Exception e) {
				LOGGER.error(CANNOT_DETERMINE_DOCUMENT_SYMBOLS, e);
			}
		}
		return Collections.emptyList();
	});
}
 
Example #2
Source File: N4JSDocumentSymbolMapper.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public DocumentSymbol toDocumentSymbol(EObject object) {
	SymbolKind symbolKind = kindCalculationHelper.getSymbolKind(object);
	if (symbolKind == null) {
		return null;
	}

	DocumentSymbol documentSymbol = super.toDocumentSymbol(object);
	documentSymbol.setKind(symbolKind);

	String symbolLabel = labelHelper.getSymbolLabel(object);
	if (symbolLabel != null) {
		documentSymbol.setName(symbolLabel);
	}
	return documentSymbol;
}
 
Example #3
Source File: TextDocumentServiceImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(DocumentSymbolParams params) {
    JavaSource js = getSource(params.getTextDocument().getUri());
    List<Either<SymbolInformation, DocumentSymbol>> result = new ArrayList<>();
    try {
        js.runUserActionTask(cc -> {
            cc.toPhase(JavaSource.Phase.RESOLVED);
            for (Element tel : cc.getTopLevelElements()) {
                DocumentSymbol ds = element2DocumentSymbol(cc, tel);
                if (ds != null)
                    result.add(Either.forRight(ds));
            }
        }, true);
    } catch (IOException ex) {
        //TODO: include stack trace:
        client.logMessage(new MessageParams(MessageType.Error, ex.getMessage()));
    }

    return CompletableFuture.completedFuture(result);
}
 
Example #4
Source File: TextDocumentServiceImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private DocumentSymbol element2DocumentSymbol(CompilationInfo info, Element el) throws BadLocationException {
    TreePath path = info.getTrees().getPath(el);
    if (path == null)
        return null;
    long start = info.getTrees().getSourcePositions().getStartPosition(path.getCompilationUnit(), path.getLeaf());
    long end   = info.getTrees().getSourcePositions().getEndPosition(path.getCompilationUnit(), path.getLeaf());
    if (end == (-1))
        return null;
    Range range = new Range(createPosition(info.getCompilationUnit(), (int) start),
                            createPosition(info.getCompilationUnit(), (int) end));
    List<DocumentSymbol> children = new ArrayList<>();
    for (Element c : el.getEnclosedElements()) {
        DocumentSymbol ds = element2DocumentSymbol(info, c);
        if (ds != null) {
            children.add(ds);
        }
    }
    return new DocumentSymbol(el.getSimpleName().toString(), elementKind2SymbolKind(el.getKind()), range, range, null, children);
}
 
Example #5
Source File: DocumentSymbolProcessorTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@Test
void testNoExceptionWithJavaFile() throws Exception {
	final TestLogAppender appender = new TestLogAppender();
	final Logger logger = Logger.getRootLogger();
	logger.addAppender(appender);
	File f = new File("src/test/resources/workspace/camel.java");
	try (FileInputStream fis = new FileInputStream(f)) {
		CamelLanguageServer camelLanguageServer = initializeLanguageServer(fis, ".java");
		CompletableFuture<List<Either<SymbolInformation,DocumentSymbol>>> documentSymbolFor = getDocumentSymbolFor(camelLanguageServer);
		List<Either<SymbolInformation, DocumentSymbol>> symbolsInformation = documentSymbolFor.get();
		assertThat(symbolsInformation).isEmpty();
		for (LoggingEvent loggingEvent : appender.getLog()) {
			if (loggingEvent.getMessage() != null) {
				assertThat((String)loggingEvent.getMessage()).doesNotContain(DocumentSymbolProcessor.CANNOT_DETERMINE_DOCUMENT_SYMBOLS);
			}
		}
	}
}
 
Example #6
Source File: SyntaxServerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDocumentSymbol() throws Exception {
	when(preferenceManager.getClientPreferences().isHierarchicalDocumentSymbolSupported()).thenReturn(Boolean.TRUE);

	URI fileURI = openFile("maven/salut4", "src/main/java/java/Foo.java");
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(fileURI.toString());
	DocumentSymbolParams params = new DocumentSymbolParams(identifier);
	List<Either<SymbolInformation, DocumentSymbol>> result = server.documentSymbol(params).join();
	assertNotNull(result);
	assertEquals(2, result.size());
	Either<SymbolInformation, DocumentSymbol> symbol = result.get(0);
	assertTrue(symbol.isRight());
	assertEquals("java", symbol.getRight().getName());
	assertEquals(SymbolKind.Package, symbol.getRight().getKind());
	symbol = result.get(1);
	assertTrue(symbol.isRight());
	assertEquals("Foo", symbol.getRight().getName());
	assertEquals(SymbolKind.Class, symbol.getRight().getKind());
	List<DocumentSymbol> children = symbol.getRight().getChildren();
	assertNotNull(children);
	assertEquals(1, children.size());
	assertEquals("main(String[])", children.get(0).getName());
	assertEquals(SymbolKind.Method, children.get(0).getKind());
}
 
Example #7
Source File: HierarchicalDocumentSymbolService.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * {@code false} if the argument is {@code null} or any of the {@link NonNull} properties are {@code null}.
 * Otherwise, {@code true}.
 */
public static boolean isValid(DocumentSymbol symbol) {
	if (symbol != null) {
		for (Field field : DocumentSymbol.class.getDeclaredFields()) {
			for (Annotation annotation : field.getAnnotations()) {
				if (NonNull.class == annotation.annotationType()) {
					field.setAccessible(true);
					try {
						Object o = field.get(symbol);
						if (o == null) {
							return false;
						}
					} catch (Throwable e) {
						throw Exceptions.sneakyThrow(e);
					}
				}
			}
		}
		return true;
	}
	return false;

}
 
Example #8
Source File: DocumentSymbolService.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public List<Either<SymbolInformation, DocumentSymbol>> getSymbols(XtextResource resource,
		CancelIndicator cancelIndicator) {
	String uri = uriExtensions.toUriString(resource.getURI());
	ArrayList<SymbolInformation> infos = new ArrayList<>();
	List<DocumentSymbol> rootSymbols = Lists
			.transform(hierarchicalDocumentSymbolService.getSymbols(resource, cancelIndicator), Either::getRight);
	for (DocumentSymbol rootSymbol : rootSymbols) {
		Iterable<DocumentSymbol> symbols = Traverser.forTree(DocumentSymbol::getChildren)
				.depthFirstPreOrder(rootSymbol);
		Function1<? super DocumentSymbol, ? extends String> containerNameProvider = (DocumentSymbol symbol) -> {
			DocumentSymbol firstSymbol = IterableExtensions.findFirst(symbols, (DocumentSymbol it) -> {
				return it != symbol && !IterableExtensions.isNullOrEmpty(it.getChildren())
						&& it.getChildren().contains(symbol);
			});
			if (firstSymbol != null) {
				return firstSymbol.getName();
			}
			return null;
		};
		for (DocumentSymbol s : symbols) {
			infos.add(createSymbol(uri, s, containerNameProvider));
		}
	}
	return Lists.transform(infos, Either::forLeft);
}
 
Example #9
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public static void testDocumentSymbolsFor(String xml, String fileURI, XMLSymbolSettings symbolSettings,
		DocumentSymbol... expected) {
	TextDocument document = new TextDocument(xml, fileURI != null ? fileURI : "test.xml");

	XMLLanguageService xmlLanguageService = new XMLLanguageService();

	ContentModelSettings settings = new ContentModelSettings();
	settings.setUseCache(false);
	xmlLanguageService.doSave(new SettingsSaveContext(settings));

	DOMDocument xmlDocument = DOMParser.getInstance().parse(document,
			xmlLanguageService.getResolverExtensionManager());
	xmlLanguageService.setDocumentProvider((uri) -> xmlDocument);

	List<DocumentSymbol> actual = xmlLanguageService.findDocumentSymbols(xmlDocument, symbolSettings);
	assertDocumentSymbols(actual, expected);

}
 
Example #10
Source File: DocumentSymbolMapper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Converts the {@code EObject} argument into a {@link DocumentSymbol document symbol} without the
 * {@link DocumentSymbol#children children} information filled in.
 */
public DocumentSymbol toDocumentSymbol(EObject object) {
	DocumentSymbol documentSymbol = new DocumentSymbol();
	String objectName = nameProvider.getName(object);
	if (objectName != null) {
		documentSymbol.setName(objectName);
	}
	SymbolKind objectKind = kindProvider.getSymbolKind(object);
	if (objectKind != null) {
		documentSymbol.setKind(objectKind);
	}
	Range objectRange = rangeProvider.getRange(object);
	if (objectRange != null) {
		documentSymbol.setRange(objectRange);
	}
	Range objectSelectionRange = rangeProvider.getSelectionRange(object);
	if (objectSelectionRange != null) {
		documentSymbol.setSelectionRange(objectSelectionRange);
	}
	documentSymbol.setDetail(detailsProvider.getDetails(object));
	documentSymbol.setDeprecated(deprecationInfoProvider.isDeprecated(object));
	documentSymbol.setChildren(new ArrayList<>());
	return documentSymbol;
}
 
Example #11
Source File: JDTLanguageServer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(DocumentSymbolParams params) {
	logInfo(">> document/documentSymbol");
	boolean hierarchicalDocumentSymbolSupported = preferenceManager.getClientPreferences().isHierarchicalDocumentSymbolSupported();
	DocumentSymbolHandler handler = new DocumentSymbolHandler(hierarchicalDocumentSymbolSupported);
	return computeAsync((monitor) -> {
		waitForLifecycleJobs(monitor);
		return handler.documentSymbol(params, monitor);
	});
}
 
Example #12
Source File: DocumentSymbolHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Stream<DocumentSymbol> asStream(Collection<? extends DocumentSymbol> symbols) {
	//@formatter:off
	return symbols.stream()
			.map(s -> TreeTraverser.<DocumentSymbol>using(ds -> ds.getChildren() == null
				? Collections.<DocumentSymbol>emptyList()
				: ds.getChildren()).breadthFirstTraversal(s).toList())
			.flatMap(List::stream);
	//@formatter:on
}
 
Example #13
Source File: SyntaxLanguageServer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(DocumentSymbolParams params) {
	logInfo(">> document/documentSymbol");
	boolean hierarchicalDocumentSymbolSupported = preferenceManager.getClientPreferences().isHierarchicalDocumentSymbolSupported();
	DocumentSymbolHandler handler = new DocumentSymbolHandler(hierarchicalDocumentSymbolSupported);
	return computeAsync((monitor) -> {
		waitForLifecycleJobs(monitor);
		return handler.documentSymbol(params, monitor);
	});
}
 
Example #14
Source File: GroovyServices.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(
		DocumentSymbolParams params) {
	URI uri = URI.create(params.getTextDocument().getUri());
	recompileIfContextChanged(uri);

	DocumentSymbolProvider provider = new DocumentSymbolProvider(astVisitor);
	return provider.provideDocumentSymbols(params.getTextDocument());
}
 
Example #15
Source File: DocumentSymbolHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTypes_hierarchical() throws Exception {
	String className = "org.sample.Bar";
	List<? extends DocumentSymbol> symbols = getHierarchicalSymbols(className);
	assertHasHierarchicalSymbol("main(String[]) : void", "Bar", SymbolKind.Method, symbols);
	assertHasHierarchicalSymbol("MyInterface", "Bar", SymbolKind.Interface, symbols);
	assertHasHierarchicalSymbol("foo() : void", "MyInterface", SymbolKind.Method, symbols);
	assertHasHierarchicalSymbol("MyClass", "Bar", SymbolKind.Class, symbols);
	assertHasHierarchicalSymbol("bar() : void", "MyClass", SymbolKind.Method, symbols);
}
 
Example #16
Source File: DocumentSymbolHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private DocumentSymbol toDocumentSymbol(IJavaElement unit, IProgressMonitor monitor) {
	int type = unit.getElementType();
	if (type != TYPE && type != FIELD && type != METHOD && type != PACKAGE_DECLARATION && type != COMPILATION_UNIT) {
		return null;
	}
	if (monitor.isCanceled()) {
		throw new OperationCanceledException("User abort");
	}
	DocumentSymbol symbol = new DocumentSymbol();
	try {
		String name = getName(unit);
		symbol.setName(name);
		symbol.setRange(getRange(unit));
		symbol.setSelectionRange(getSelectionRange(unit));
		symbol.setKind(mapKind(unit));
		symbol.setDeprecated(isDeprecated(unit));
		symbol.setDetail(getDetail(unit, name));
		if (unit instanceof IParent) {
			//@formatter:off
			IJavaElement[] children = filter(((IParent) unit).getChildren());
			symbol.setChildren(Stream.of(children)
					.map(child -> toDocumentSymbol(child, monitor))
					.filter(Objects::nonNull)
					.collect(Collectors.toList()));
			//@formatter:off
		}
	} catch (JavaModelException e) {
		Exceptions.sneakyThrow(e);
	}
	return symbol;
}
 
Example #17
Source File: XLanguageServerImpl.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(
		DocumentSymbolParams params) {
	URI uri = getURI(params.getTextDocument());
	return openFilesManager.runInOpenFileContext(uri, "documentSymbol", (ofc, ci) -> {
		return documentSymbol(ofc, params, ci);
	});
}
 
Example #18
Source File: DocumentSymbolHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSyntheticMember_hierarchical_noSourceAttached() throws Exception {
	String className = "foo.bar";
	List<? extends DocumentSymbol> symbols = asStream(internalGetHierarchicalSymbols(noSourceProject, monitor, className)).collect(Collectors.toList());
	assertHasHierarchicalSymbol("bar()", "bar", SymbolKind.Constructor, symbols);
	assertHasHierarchicalSymbol("add(int...) : int", "bar", SymbolKind.Method, symbols);
}
 
Example #19
Source File: ServerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String toString(DocumentSymbol sym) {
    return sym.getKind().toString() + ":" +
           sym.getName() + ":" +
           sym.getRange() + ":" +
           sym.getChildren()
              .stream()
              .map(this::toString)
              .collect(Collectors.joining(", ", "(", ")"));
}
 
Example #20
Source File: DocumentSymbolHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static List<? extends DocumentSymbol> internalGetHierarchicalSymbols(IProject project, IProgressMonitor monitor, String className)
		throws JavaModelException, UnsupportedEncodingException, InterruptedException, ExecutionException {
	String uri = ClassFileUtil.getURI(project, className);
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(uri);
	DocumentSymbolParams params = new DocumentSymbolParams();
	params.setTextDocument(identifier);
	//@formatter:off
	List<DocumentSymbol> symbols = new DocumentSymbolHandler(true)
			.documentSymbol(params, monitor).stream()
			.map(Either::getRight).collect(toList());
	//@formatter:on
	assertTrue(symbols.size() > 0);
	return symbols;
}
 
Example #21
Source File: DocumentSymbolHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void assertHasHierarchicalSymbol(String expectedType, String expectedParent, SymbolKind expectedKind, Collection<? extends DocumentSymbol> symbols) {
	Optional<? extends DocumentSymbol> parent = asStream(symbols).filter(s -> expectedParent.equals(s.getName() + s.getDetail())).findFirst();
	assertTrue("Cannot find parent with name: " + expectedParent, parent.isPresent());
	Optional<? extends DocumentSymbol> symbol = asStream(symbols)
														.filter(s -> expectedType.equals(s.getName() + s.getDetail()) && parent.get().getChildren().contains(s))
														.findFirst();
	assertTrue(expectedType + " (" + expectedParent + ")" + " is missing from " + symbols, symbol.isPresent());
	assertKind(expectedKind, symbol.get());
}
 
Example #22
Source File: DocumentSymbolHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSyntheticMember_hierarchical() throws Exception {
	String className = "org.apache.commons.lang3.text.StrTokenizer";
	List<? extends DocumentSymbol> symbols = asStream(getHierarchicalSymbols(className)).collect(Collectors.toList());
	boolean overloadedMethod1Found = false;
	boolean overloadedMethod2Found = false;
	String overloadedMethod1 = "getCSVInstance(String) : StrTokenizer";
	String overloadedMethod2 = "reset() : StrTokenizer";
	for (DocumentSymbol symbol : symbols) {
		Range fullRange = symbol.getRange();
		Range selectionRange = symbol.getSelectionRange();
		assertTrue("Class: " + className + ", Symbol:" + symbol.getName() + " - invalid location.",
				fullRange != null && isValid(fullRange) && selectionRange != null && isValid(selectionRange));
		assertFalse("Class: " + className + ", Symbol:" + symbol.getName() + " - invalid name",
				symbol.getName().startsWith("access$"));
		assertFalse("Class: " + className + ", Symbol:" + symbol.getName() + "- invalid name",
				symbol.getName().equals("<clinit>"));
		if (overloadedMethod1.equals(symbol.getName() + symbol.getDetail())) {
			overloadedMethod1Found = true;
		}
		if (overloadedMethod2.equals(symbol.getName() + symbol.getDetail())) {
			overloadedMethod2Found = true;
		}
	}
	assertTrue("The " + overloadedMethod1 + " method hasn't been found", overloadedMethod1Found);
	assertTrue("The " + overloadedMethod2 + " method hasn't been found", overloadedMethod2Found);
}
 
Example #23
Source File: WorkspaceFolderManager.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
public DocumentSymbol definitionToDocumentSymbol(IDefinition definition, ILspProject project)
{
    String definitionBaseName = definition.getBaseName();
    if (definition instanceof IPackageDefinition)
    {
        definitionBaseName = "package " + definitionBaseName;
    }
    if (definitionBaseName.length() == 0)
    {
        //vscode expects all items to have a name
        return null;
    }

    Range range = definitionToRange(definition, project);
    if (range == null)
    {
        //we can't find where the source code for this symbol is located
        return null;
    }

    DocumentSymbol symbol = new DocumentSymbol();
    symbol.setKind(LanguageServerCompilerUtils.getSymbolKindFromDefinition(definition));
    symbol.setName(definitionBaseName);
    symbol.setRange(range);
    symbol.setSelectionRange(range);

    IDeprecationInfo deprecationInfo = definition.getDeprecationInfo();
    if (deprecationInfo != null)
    {
        symbol.setDeprecated(true);
    }

    return symbol;
}
 
Example #24
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
/**
 * Searches by name for a symbol in a specific document (not the whole
 * workspace)
 */
@Override
public CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> documentSymbol(DocumentSymbolParams params)
{
    return CompletableFutures.computeAsync(compilerWorkspace.getExecutorService(), cancelToken ->
    {
        cancelToken.checkCanceled();

        //make sure that the latest changes have been passed to
        //workspace.fileChanged() before proceeding
        if(realTimeProblemsChecker != null)
        {
            realTimeProblemsChecker.updateNow();
        }
        
        compilerWorkspace.startBuilding();
        try
        {
            boolean hierarchicalDocumentSymbolSupport = false;
            try
            {
                hierarchicalDocumentSymbolSupport = clientCapabilities.getTextDocument().getDocumentSymbol().getHierarchicalDocumentSymbolSupport();
            }
            catch(NullPointerException e)
            {
                //ignore
            }
            DocumentSymbolProvider provider = new DocumentSymbolProvider(workspaceFolderManager, hierarchicalDocumentSymbolSupport);
            return provider.documentSymbol(params, cancelToken);
        }
        finally
        {
            compilerWorkspace.doneBuilding();
        }
    });
}
 
Example #25
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void testDocumentSymbol(final Procedure1<? super DocumentSymbolConfiguraiton> configurator) {
  try {
    @Extension
    final DocumentSymbolConfiguraiton configuration = new DocumentSymbolConfiguraiton();
    configuration.setFilePath(("MyModel." + this.fileExtension));
    configurator.apply(configuration);
    final String fileUri = this.initializeContext(configuration).getUri();
    TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(fileUri);
    DocumentSymbolParams _documentSymbolParams = new DocumentSymbolParams(_textDocumentIdentifier);
    final CompletableFuture<List<Either<SymbolInformation, DocumentSymbol>>> symbolsFuture = this.languageServer.documentSymbol(_documentSymbolParams);
    final List<Either<SymbolInformation, DocumentSymbol>> symbols = symbolsFuture.get();
    Procedure1<? super List<Either<SymbolInformation, DocumentSymbol>>> _assertSymbols = configuration.getAssertSymbols();
    boolean _tripleNotEquals = (_assertSymbols != null);
    if (_tripleNotEquals) {
      configuration.getAssertSymbols().apply(symbols);
    } else {
      final Function1<Either<SymbolInformation, DocumentSymbol>, Object> _function = (Either<SymbolInformation, DocumentSymbol> it) -> {
        Object _xifexpression = null;
        if (this.hierarchicalDocumentSymbolSupport) {
          _xifexpression = it.getRight();
        } else {
          _xifexpression = it.getLeft();
        }
        return _xifexpression;
      };
      final List<Object> unwrappedSymbols = ListExtensions.<Either<SymbolInformation, DocumentSymbol>, Object>map(symbols, _function);
      final String actualSymbols = this.toExpectation(unwrappedSymbols);
      this.assertEquals(configuration.getExpectedSymbols(), actualSymbols);
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #26
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Compute the symbol information. Executed in a read request.
 * @since 2.20
 */
protected List<Either<SymbolInformation, DocumentSymbol>> documentSymbol(DocumentSymbolParams params,
		CancelIndicator cancelIndicator) {
	URI uri = getURI(params.getTextDocument());
	IDocumentSymbolService documentSymbolService = getIDocumentSymbolService(getResourceServiceProvider(uri));
	if (documentSymbolService == null) {
		return Collections.emptyList();
	}
	return workspaceManager.doRead(uri,
			(document, resource) -> documentSymbolService.getSymbols(document, resource, params, cancelIndicator));
}
 
Example #27
Source File: HierarchicalDocumentSymbolService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public List<Either<SymbolInformation, DocumentSymbol>> getSymbols(XtextResource resource,
		CancelIndicator cancelIndicator) {
	HashMap<EObject, DocumentSymbol> allSymbols = new HashMap<>();
	ArrayList<DocumentSymbol> rootSymbols = new ArrayList<>();
	Iterator<Object> itr = getAllContents(resource);
	while (itr.hasNext()) {
		operationCanceledManager.checkCanceled(cancelIndicator);
		Optional<EObject> next = toEObject(itr.next());
		if (next.isPresent()) {
			EObject object = next.get();
			DocumentSymbol symbol = symbolMapper.toDocumentSymbol(object);
			if (isValid(symbol)) {
				allSymbols.put(object, symbol);
				EObject parent = object.eContainer();
				if (parent == null) {
					rootSymbols.add(symbol);
				} else {
					DocumentSymbol parentSymbol = allSymbols.get(parent);
					while (parentSymbol == null && parent != null) {
						parent = parent.eContainer();
						parentSymbol = allSymbols.get(parent);
					}
					if (parentSymbol == null) {
						rootSymbols.add(symbol);
					} else {
						parentSymbol.getChildren().add(symbol);
					}
				}
			}
		}
	}
	return rootSymbols.stream().map(symbol -> Either.<SymbolInformation, DocumentSymbol>forRight(symbol))
			.collect(Collectors.toList());
}
 
Example #28
Source File: DocumentSymbolService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.16
 */
protected SymbolInformation createSymbol(String uri, DocumentSymbol symbol,
		Function1<? super DocumentSymbol, ? extends String> containerNameProvider) {
	SymbolInformation symbolInformation = new SymbolInformation();
	symbolInformation.setName(symbol.getName());
	symbolInformation.setKind(symbol.getKind());
	symbolInformation.setDeprecated(symbol.getDeprecated());
	Location location = new Location();
	location.setUri(uri);
	location.setRange(symbol.getSelectionRange());
	symbolInformation.setLocation(location);
	symbolInformation.setContainerName(containerNameProvider.apply(symbol));
	return symbolInformation;
}
 
Example #29
Source File: DocumentSymbolResponseAdapter.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
	PropertyChecker leftChecker = new PropertyChecker("location");
	PropertyChecker rightChecker = new PropertyChecker("range");
	TypeAdapter<Either<SymbolInformation, DocumentSymbol>> elementTypeAdapter = new EitherTypeAdapter<>(gson,
			ELEMENT_TYPE, leftChecker, rightChecker);
	return (TypeAdapter<T>) new CollectionTypeAdapter<>(gson, ELEMENT_TYPE.getType(), elementTypeAdapter, ArrayList::new);
}
 
Example #30
Source File: DocumentSymbolsTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void asIterator() {
	DocumentSymbol depth0 = new DocumentSymbol();
	depth0.setName("root");

	DocumentSymbol depth1_0 = new DocumentSymbol();
	depth1_0.setName("A1");
	DocumentSymbol depth1_1 = new DocumentSymbol();
	depth1_1.setName("B1");
	DocumentSymbol depth1_2 = new DocumentSymbol();
	depth1_2.setName("C1");
	depth0.setChildren(Arrays.asList(depth1_0, depth1_1, depth1_2));

	DocumentSymbol depth2_0_0 = new DocumentSymbol();
	depth2_0_0.setName("A11");
	DocumentSymbol depth2_0_1 = new DocumentSymbol();
	depth2_0_1.setName("A12");
	depth1_0.setChildren(Arrays.asList(depth2_0_0, depth2_0_1));

	DocumentSymbol depth2_1_0 = new DocumentSymbol();
	depth2_1_0.setName("B11");
	DocumentSymbol depth2_1_1 = new DocumentSymbol();
	depth2_1_1.setName("B12");
	depth1_1.setChildren(Arrays.asList(depth2_1_0, depth2_1_1));

	DocumentSymbol depth2_2_0 = new DocumentSymbol();
	depth2_2_0.setName("C11");
	DocumentSymbol depth2_2_1 = new DocumentSymbol();
	depth2_2_1.setName("C12");
	depth1_2.setChildren(Arrays.asList(depth2_2_0, depth2_2_1));

	Iterator<DocumentSymbol> iterator = DocumentSymbols.asIterator(depth0);
	Iterable<DocumentSymbol> iterable = () -> iterator;
	Stream<DocumentSymbol> stream = StreamSupport.stream(iterable.spliterator(), false);
	List<String> actual = stream.map(symbol -> symbol.getName()).collect(toList());
	List<String> expected = Arrays.asList("root, A1", "B1", "C1", "A11", "A12", "B11", "B12", "C11", "C12");

	Assert.assertEquals(Arrays.toString(expected.toArray()), Arrays.toString(actual.toArray()));
}