Search in sources :

Example 16 with BLangPackage

use of org.wso2.ballerinalang.compiler.tree.BLangPackage in project ballerina by ballerina-lang.

the class BallerinaParserService method validateAndParse.

/**
 * Validates a given ballerina input.
 *
 * @param bFileRequest - Object which holds data about Ballerina content.
 * @return List of errors if any
 */
private JsonObject validateAndParse(BFile bFileRequest) throws InvocationTargetException, IllegalAccessException {
    final java.nio.file.Path filePath = Paths.get(bFileRequest.getFilePath(), bFileRequest.getFileName());
    final String fileName = bFileRequest.getFileName();
    final String content = bFileRequest.getContent();
    BallerinaFile bFile = ParserUtils.compile(content, filePath);
    String programDir = TextDocumentServiceUtil.getSourceRoot(filePath);
    final BLangPackage model = bFile.getBLangPackage();
    final List<Diagnostic> diagnostics = bFile.getDiagnostics();
    ErrorCategory errorCategory = ErrorCategory.NONE;
    if (!diagnostics.isEmpty()) {
        if (model == null) {
            errorCategory = ErrorCategory.SYNTAX;
        } else {
            errorCategory = ErrorCategory.SEMANTIC;
        }
    }
    JsonArray errors = new JsonArray();
    final String errorCategoryName = errorCategory.name();
    diagnostics.forEach(diagnostic -> {
        JsonObject error = new JsonObject();
        Diagnostic.DiagnosticPosition position = diagnostic.getPosition();
        if (position != null) {
            if (!diagnostic.getSource().getCompilationUnitName().equals(fileName)) {
                return;
            }
            error.addProperty("row", position.getStartLine());
            error.addProperty("column", position.getStartColumn());
            error.addProperty("type", "error");
            error.addProperty("category", errorCategoryName);
        } else {
            // position == null means it's a bug in core side.
            error.addProperty("category", ErrorCategory.RUNTIME.name());
        }
        error.addProperty("text", diagnostic.getMessage());
        errors.add(error);
    });
    JsonObject result = new JsonObject();
    result.add("errors", errors);
    Gson gson = new Gson();
    JsonElement diagnosticsJson = gson.toJsonTree(diagnostics);
    result.add("diagnostics", diagnosticsJson);
    if (model != null && bFileRequest.needTree()) {
        BLangCompilationUnit compilationUnit = model.getCompilationUnits().stream().filter(compUnit -> fileName.equals(compUnit.getName())).findFirst().get();
        JsonElement modelElement = generateJSON(compilationUnit, new HashMap<>());
        result.add("model", modelElement);
    }
    final Map<String, ModelPackage> modelPackage = new HashMap<>();
    ParserUtils.loadPackageMap("Current Package", bFile.getBLangPackage(), modelPackage);
    Optional<ModelPackage> packageInfoJson = modelPackage.values().stream().findFirst();
    if (packageInfoJson.isPresent() && bFileRequest.needPackageInfo()) {
        JsonElement packageInfo = gson.toJsonTree(packageInfoJson.get());
        result.add("packageInfo", packageInfo);
    }
    if (programDir != null) {
        result.addProperty("programDirPath", programDir);
    }
    return result;
}
Also used : BallerinaFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile) HashMap(java.util.HashMap) Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) JsonArray(com.google.gson.JsonArray) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) JsonElement(com.google.gson.JsonElement) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit)

Example 17 with BLangPackage

use of org.wso2.ballerinalang.compiler.tree.BLangPackage in project ballerina by ballerina-lang.

the class CommandExecutor method executeAddAllDocumentation.

/**
 * Generate workspace edit for generating doc comments for all top level nodes and resources.
 * @param context   Workspace Service Context
 */
private static void executeAddAllDocumentation(WorkspaceServiceContext context) {
    String documentUri = "";
    VersionedTextDocumentIdentifier textDocumentIdentifier = new VersionedTextDocumentIdentifier();
    for (Object arg : context.get(ExecuteCommandKeys.COMMAND_ARGUMENTS_KEY)) {
        if (((LinkedTreeMap) arg).get(ARG_KEY).equals(CommandConstants.ARG_KEY_DOC_URI)) {
            documentUri = (String) ((LinkedTreeMap) arg).get(ARG_VALUE);
            textDocumentIdentifier.setUri(documentUri);
            context.put(DocumentServiceKeys.FILE_URI_KEY, documentUri);
        }
    }
    BLangPackage bLangPackage = TextDocumentServiceUtil.getBLangPackage(context, context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY), false, LSCustomErrorStrategy.class, false).get(0);
    String fileContent = context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY).getFileContent(Paths.get(URI.create(documentUri)));
    String[] contentComponents = fileContent.split(System.lineSeparator());
    List<TextEdit> textEdits = new ArrayList<>();
    bLangPackage.topLevelNodes.forEach(topLevelNode -> {
        CommandUtil.DocAttachmentInfo docAttachmentInfo = getDocumentEditForNode(topLevelNode);
        if (docAttachmentInfo != null) {
            textEdits.add(getTextEdit(docAttachmentInfo, contentComponents));
        }
        if (topLevelNode instanceof BLangService) {
            ((BLangService) topLevelNode).getResources().forEach(bLangResource -> {
                CommandUtil.DocAttachmentInfo resourceInfo = getDocumentEditForNode(bLangResource);
                if (resourceInfo != null) {
                    textEdits.add(getTextEdit(resourceInfo, contentComponents));
                }
            });
        }
    });
    TextDocumentEdit textDocumentEdit = new TextDocumentEdit(textDocumentIdentifier, textEdits);
    applyWorkspaceEdit(Collections.singletonList(textDocumentEdit), context.get(ExecuteCommandKeys.LANGUAGE_SERVER_KEY).getClient());
}
Also used : LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) ArrayList(java.util.ArrayList) TextDocumentEdit(org.eclipse.lsp4j.TextDocumentEdit) VersionedTextDocumentIdentifier(org.eclipse.lsp4j.VersionedTextDocumentIdentifier) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) TextEdit(org.eclipse.lsp4j.TextEdit) LSCustomErrorStrategy(org.ballerinalang.langserver.common.LSCustomErrorStrategy)

Example 18 with BLangPackage

use of org.wso2.ballerinalang.compiler.tree.BLangPackage in project ballerina by ballerina-lang.

the class CommandUtil method getStructDocumentationByPosition.

/**
 * Get the Documentation attachment for the struct definition.
 * @param bLangPackage      BLangPackage built
 * @param line              Start line of the struct in the source
 * @return {@link String}   Documentation attachment for the struct
 */
static DocAttachmentInfo getStructDocumentationByPosition(BLangPackage bLangPackage, int line) {
    for (TopLevelNode topLevelNode : bLangPackage.topLevelNodes) {
        if (topLevelNode instanceof BLangStruct) {
            BLangStruct structNode = (BLangStruct) topLevelNode;
            DiagnosticPos structPos = CommonUtil.toZeroBasedPosition(structNode.getPosition());
            int structStart = structPos.getStartLine();
            if (structStart == line) {
                return getStructNodeDocumentation(structNode, line);
            }
        }
    }
    return null;
}
Also used : DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode)

Example 19 with BLangPackage

use of org.wso2.ballerinalang.compiler.tree.BLangPackage in project ballerina by ballerina-lang.

the class CommandUtil method getServiceDocumentationByPosition.

/**
 * Get the Documentation attachment for the service.
 * @param bLangPackage      BLangPackage built
 * @param line              Start line of the service in the source
 * @return {@link String}   Documentation attachment for the service
 */
static DocAttachmentInfo getServiceDocumentationByPosition(BLangPackage bLangPackage, int line) {
    // TODO: Currently resource position is invalid and we use the annotation attachment positions.
    for (TopLevelNode topLevelNode : bLangPackage.topLevelNodes) {
        if (topLevelNode instanceof BLangService) {
            BLangService serviceNode = (BLangService) topLevelNode;
            DiagnosticPos servicePos = CommonUtil.toZeroBasedPosition(serviceNode.getPosition());
            List<BLangAnnotationAttachment> annotationAttachments = serviceNode.getAnnotationAttachments();
            if (!annotationAttachments.isEmpty()) {
                DiagnosticPos lastAttachmentPos = CommonUtil.toZeroBasedPosition(annotationAttachments.get(annotationAttachments.size() - 1).getPosition());
                if (lastAttachmentPos.getEndLine() < line && line < servicePos.getEndLine()) {
                    return getServiceNodeDocumentation(serviceNode, lastAttachmentPos.getEndLine() + 1);
                }
            } else if (servicePos.getStartLine() == line) {
                return getServiceNodeDocumentation(serviceNode, line);
            }
        }
    }
    return null;
}
Also used : DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) BLangAnnotationAttachment(org.wso2.ballerinalang.compiler.tree.BLangAnnotationAttachment) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode)

Example 20 with BLangPackage

use of org.wso2.ballerinalang.compiler.tree.BLangPackage 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)

Aggregations

BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)78 Test (org.testng.annotations.Test)29 ArrayList (java.util.ArrayList)28 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)19 Page (org.ballerinalang.docgen.model.Page)18 BLangFunction (org.wso2.ballerinalang.compiler.tree.BLangFunction)16 SymbolEnv (org.wso2.ballerinalang.compiler.semantics.model.SymbolEnv)15 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)15 BLangNode (org.wso2.ballerinalang.compiler.tree.BLangNode)14 IOException (java.io.IOException)13 List (java.util.List)13 Path (java.nio.file.Path)12 Compiler (org.wso2.ballerinalang.compiler.Compiler)12 BLangStruct (org.wso2.ballerinalang.compiler.tree.BLangStruct)12 BLangService (org.wso2.ballerinalang.compiler.tree.BLangService)11 TopLevelNode (org.ballerinalang.model.tree.TopLevelNode)10 BLangConnector (org.wso2.ballerinalang.compiler.tree.BLangConnector)10 BPackageSymbol (org.wso2.ballerinalang.compiler.semantics.model.symbols.BPackageSymbol)9 BLangAction (org.wso2.ballerinalang.compiler.tree.BLangAction)9 BLangEnum (org.wso2.ballerinalang.compiler.tree.BLangEnum)9