Search in sources :

Example 1 with LSDocument

use of org.ballerinalang.langserver.common.LSDocument in project ballerina by ballerina-lang.

the class CommandUtil method getCommandsByDiagnostic.

/**
 * Get the command instances for a given diagnostic.
 * @param diagnostic        Diagnostic to get the command against
 * @param params            Code Action parameters
 * @param lsPackageCache    Lang Server Package cache
 * @return  {@link List}    List of commands related to the given diagnostic
 */
public static List<Command> getCommandsByDiagnostic(Diagnostic diagnostic, CodeActionParams params, LSPackageCache lsPackageCache) {
    String diagnosticMessage = diagnostic.getMessage();
    List<Command> commands = new ArrayList<>();
    if (isUndefinedPackage(diagnosticMessage)) {
        String packageAlias = diagnosticMessage.substring(diagnosticMessage.indexOf("'") + 1, diagnosticMessage.lastIndexOf("'"));
        LSDocument sourceDocument = new LSDocument(params.getTextDocument().getUri());
        Path openedPath = CommonUtil.getPath(sourceDocument);
        String sourceRoot = TextDocumentServiceUtil.getSourceRoot(openedPath);
        sourceDocument.setSourceRoot(sourceRoot);
        lsPackageCache.getPackageMap().entrySet().stream().filter(pkgEntry -> {
            String fullPkgName = pkgEntry.getValue().packageID.orgName.getValue() + "/" + pkgEntry.getValue().packageID.getName().getValue();
            return fullPkgName.endsWith("." + packageAlias) || fullPkgName.endsWith("/" + packageAlias);
        }).forEach(pkgEntry -> {
            PackageID packageID = pkgEntry.getValue().packageID;
            String commandTitle = CommandConstants.IMPORT_PKG_TITLE + " " + packageID.getName().toString();
            String fullPkgName = packageID.getOrgName() + "/" + packageID.getName().getValue();
            CommandArgument pkgArgument = new CommandArgument(CommandConstants.ARG_KEY_PKG_NAME, fullPkgName);
            CommandArgument docUriArgument = new CommandArgument(CommandConstants.ARG_KEY_DOC_URI, params.getTextDocument().getUri());
            commands.add(new Command(commandTitle, CommandConstants.CMD_IMPORT_PACKAGE, new ArrayList<>(Arrays.asList(pkgArgument, docUriArgument))));
        });
    }
    return commands;
}
Also used : Path(java.nio.file.Path) CommonUtil(org.ballerinalang.langserver.common.utils.CommonUtil) Arrays(java.util.Arrays) BLangVariable(org.wso2.ballerinalang.compiler.tree.BLangVariable) CommandConstants(org.ballerinalang.langserver.common.constants.CommandConstants) Diagnostic(org.eclipse.lsp4j.Diagnostic) ArrayList(java.util.ArrayList) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) LSDocument(org.ballerinalang.langserver.common.LSDocument) BLangResource(org.wso2.ballerinalang.compiler.tree.BLangResource) DocTag(org.ballerinalang.model.elements.DocTag) Locale(java.util.Locale) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode) DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) Path(java.nio.file.Path) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) BLangObject(org.wso2.ballerinalang.compiler.tree.BLangObject) PackageID(org.ballerinalang.model.elements.PackageID) FunctionNode(org.ballerinalang.model.tree.FunctionNode) LSPackageCache(org.ballerinalang.langserver.LSPackageCache) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) BLangAnnotationAttachment(org.wso2.ballerinalang.compiler.tree.BLangAnnotationAttachment) BLangTransformer(org.wso2.ballerinalang.compiler.tree.BLangTransformer) TextDocumentServiceUtil(org.ballerinalang.langserver.TextDocumentServiceUtil) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) List(java.util.List) BLangEnum(org.wso2.ballerinalang.compiler.tree.BLangEnum) Command(org.eclipse.lsp4j.Command) BEndpointVarSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BEndpointVarSymbol) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) Collections(java.util.Collections) Command(org.eclipse.lsp4j.Command) LSDocument(org.ballerinalang.langserver.common.LSDocument) ArrayList(java.util.ArrayList) PackageID(org.ballerinalang.model.elements.PackageID)

Example 2 with LSDocument

use of org.ballerinalang.langserver.common.LSDocument in project ballerina by ballerina-lang.

the class ParserUtils method compile.

/**
 * Compile a Ballerina file.
 *
 * @param content       file content
 * @param path          file path
 * @param compilerPhase {CompilerPhase} set phase for the compiler.
 * @return
 */
public static BallerinaFile compile(String content, Path path, CompilerPhase compilerPhase) {
    if (documentManager.isFileOpen(path)) {
        documentManager.updateFile(path, content);
    } else {
        documentManager.openFile(path, content);
    }
    String sourceRoot = TextDocumentServiceUtil.getSourceRoot(path);
    String pkgName = TextDocumentServiceUtil.getPackageNameForGivenFile(sourceRoot, path.toString());
    LSDocument sourceDocument = new LSDocument();
    sourceDocument.setUri(path.toUri().toString());
    sourceDocument.setSourceRoot(sourceRoot);
    PackageRepository packageRepository = new WorkspacePackageRepository(sourceRoot, documentManager);
    CompilerContext context = TextDocumentServiceUtil.prepareCompilerContext(packageRepository, sourceDocument, true, documentManager, CompilerPhase.DEFINE);
    List<org.ballerinalang.util.diagnostic.Diagnostic> balDiagnostics = new ArrayList<>();
    CollectDiagnosticListener diagnosticListener = new CollectDiagnosticListener(balDiagnostics);
    context.put(DiagnosticListener.class, diagnosticListener);
    BLangPackage bLangPackage = null;
    try {
        Compiler compiler = Compiler.getInstance(context);
        if ("".equals(pkgName)) {
            Path filePath = path.getFileName();
            if (filePath != null) {
                bLangPackage = compiler.compile(filePath.toString());
            }
        } else {
            bLangPackage = compiler.compile(pkgName);
        }
    } catch (Exception e) {
    // Ignore.
    }
    BallerinaFile bfile = new BallerinaFile();
    bfile.setBLangPackage(bLangPackage);
    bfile.setDiagnostics(balDiagnostics);
    return bfile;
}
Also used : Path(java.nio.file.Path) Compiler(org.wso2.ballerinalang.compiler.Compiler) BallerinaFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) ArrayList(java.util.ArrayList) Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic) BDiagnostic(org.wso2.ballerinalang.compiler.util.diagnotic.BDiagnostic) WorkspacePackageRepository(org.ballerinalang.langserver.workspace.repository.WorkspacePackageRepository) PackageRepository(org.ballerinalang.repository.PackageRepository) WorkspacePackageRepository(org.ballerinalang.langserver.workspace.repository.WorkspacePackageRepository) IOException(java.io.IOException) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) LSDocument(org.ballerinalang.langserver.common.LSDocument) CollectDiagnosticListener(org.ballerinalang.langserver.CollectDiagnosticListener)

Example 3 with LSDocument

use of org.ballerinalang.langserver.common.LSDocument in project ballerina by ballerina-lang.

the class BallerinaTextDocumentService method formatting.

@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
    return CompletableFuture.supplyAsync(() -> {
        String textEditContent = null;
        TextDocumentServiceContext formatContext = new TextDocumentServiceContext();
        formatContext.put(DocumentServiceKeys.FILE_URI_KEY, params.getTextDocument().getUri());
        LSDocument document = new LSDocument(params.getTextDocument().getUri());
        String fileContent = documentManager.getFileContent(CommonUtil.getPath(document));
        String[] contentComponents = fileContent.split("\\n|\\r\\n|\\r");
        int lastNewLineCharIndex = Math.max(fileContent.lastIndexOf("\n"), fileContent.lastIndexOf("\r"));
        int lastCharCol = fileContent.substring(lastNewLineCharIndex + 1).length();
        int totalLines = contentComponents.length;
        Range range = new Range(new Position(0, 0), new Position(totalLines, lastCharCol));
        try {
            // Source generation for given ast.
            JsonObject ast = TextDocumentFormatUtil.getAST(params, documentManager, formatContext);
            SourceGen sourceGen = new SourceGen(0);
            sourceGen.build(ast.getAsJsonObject("model"), null, "CompilationUnit");
            textEditContent = sourceGen.getSourceOf(ast.getAsJsonObject("model"), true, false);
        } catch (Exception e) {
        // Ignore
        }
        TextEdit textEdit = textEditContent != null ? new TextEdit(range, textEditContent) : null;
        return Collections.singletonList(textEdit);
    });
}
Also used : Position(org.eclipse.lsp4j.Position) LSDocument(org.ballerinalang.langserver.common.LSDocument) TextEdit(org.eclipse.lsp4j.TextEdit) JsonObject(com.google.gson.JsonObject) MarkedString(org.eclipse.lsp4j.MarkedString) Range(org.eclipse.lsp4j.Range)

Example 4 with LSDocument

use of org.ballerinalang.langserver.common.LSDocument in project ballerina by ballerina-lang.

the class CommonUtil method topLevelNodeTypeInLine.

/**
 * Get the top level node type in the line.
 *
 * @param identifier    Document Identifier
 * @param startPosition Start position
 * @param docManager    Workspace document manager
 * @return {@link String}   Top level node type
 */
public static String topLevelNodeTypeInLine(TextDocumentIdentifier identifier, Position startPosition, WorkspaceDocumentManager docManager) {
    // TODO: Need to support service and resources as well.
    List<String> topLevelKeywords = Arrays.asList("function", "service", "resource", "struct", "enum", "transformer", "object");
    LSDocument document = new LSDocument(identifier.getUri());
    String fileContent = docManager.getFileContent(getPath(document));
    String[] splitedFileContent = fileContent.split("\\n|\\r\\n|\\r");
    if ((splitedFileContent.length - 1) >= startPosition.getLine()) {
        String lineContent = splitedFileContent[startPosition.getLine()];
        List<String> alphaNumericTokens = new ArrayList<>(Arrays.asList(lineContent.split("[^\\w']+")));
        for (String topLevelKeyword : topLevelKeywords) {
            if (alphaNumericTokens.contains(topLevelKeyword)) {
                return topLevelKeyword;
            }
        }
    }
    return null;
}
Also used : LSDocument(org.ballerinalang.langserver.common.LSDocument) ArrayList(java.util.ArrayList)

Example 5 with LSDocument

use of org.ballerinalang.langserver.common.LSDocument in project ballerina by ballerina-lang.

the class RenameUtil method getReplaceSymbolName.

/**
 * Get the symbol name to replace.
 *
 * @param params          {@link RenameParams} for operation
 * @param documentManager {@link WorkspaceDocumentManager} instance
 * @return {@link String}       Symbol name to replace
 */
public static String getReplaceSymbolName(RenameParams params, WorkspaceDocumentManager documentManager) {
    Position position = params.getPosition();
    int line = position.getLine();
    int column = position.getCharacter();
    String fileContent = documentManager.getFileContent(CommonUtil.getPath(new LSDocument(params.getTextDocument().getUri())));
    String lineContent = fileContent.split("\\n|\\r\\n|\\r")[line];
    return getIdentifierLiterals(lineContent, column - 1, -1).reverse().toString() + getIdentifierLiterals(lineContent, column, 1).toString();
}
Also used : Position(org.eclipse.lsp4j.Position) LSDocument(org.ballerinalang.langserver.common.LSDocument)

Aggregations

LSDocument (org.ballerinalang.langserver.common.LSDocument)14 Path (java.nio.file.Path)10 ArrayList (java.util.ArrayList)7 Position (org.eclipse.lsp4j.Position)5 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)5 MarkedString (org.eclipse.lsp4j.MarkedString)4 Range (org.eclipse.lsp4j.Range)4 List (java.util.List)3 CommonUtil (org.ballerinalang.langserver.common.utils.CommonUtil)3 WorkspacePackageRepository (org.ballerinalang.langserver.workspace.repository.WorkspacePackageRepository)3 PackageRepository (org.ballerinalang.repository.PackageRepository)3 Location (org.eclipse.lsp4j.Location)3 Compiler (org.wso2.ballerinalang.compiler.Compiler)3 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 LSPackageCache (org.ballerinalang.langserver.LSPackageCache)2 PackageID (org.ballerinalang.model.elements.PackageID)2 Diagnostic (org.eclipse.lsp4j.Diagnostic)2 TextDocumentPositionParams (org.eclipse.lsp4j.TextDocumentPositionParams)2 TextEdit (org.eclipse.lsp4j.TextEdit)2