Search in sources :

Example 66 with BLangPackage

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

the class DefinitionUtil method getDefinitionPosition.

/**
 * Get definition position for the given definition context.
 *
 * @param definitionContext   context of the definition.
 * @param lSPackageCache package context for language server.
 * @return position
 */
public static List<Location> getDefinitionPosition(TextDocumentServiceContext definitionContext, LSPackageCache lSPackageCache) {
    List<Location> contents = new ArrayList<>();
    if (definitionContext.get(NodeContextKeys.SYMBOL_KIND_OF_NODE_KEY) == null) {
        return contents;
    }
    String nodeKind = definitionContext.get(NodeContextKeys.SYMBOL_KIND_OF_NODE_KEY);
    BLangPackage bLangPackage = getPackageOfTheOwner(definitionContext.get(NodeContextKeys.NODE_OWNER_PACKAGE_KEY), definitionContext, lSPackageCache);
    BLangNode bLangNode = null;
    switch(nodeKind) {
        case ContextConstants.FUNCTION:
            bLangNode = bLangPackage.functions.stream().filter(function -> function.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.STRUCT:
            bLangNode = bLangPackage.structs.stream().filter(struct -> struct.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.OBJECT:
            bLangNode = bLangPackage.objects.stream().filter(object -> object.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.ENUM:
            bLangNode = bLangPackage.enums.stream().filter(enm -> enm.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            // Fixing the position issue with enum node.
            bLangNode.getPosition().eLine = bLangNode.getPosition().sLine;
            bLangNode.getPosition().eCol = bLangNode.getPosition().sCol;
            break;
        case ContextConstants.CONNECTOR:
            bLangNode = bLangPackage.connectors.stream().filter(bConnector -> bConnector.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.ACTION:
            bLangNode = bLangPackage.connectors.stream().filter(bConnector -> bConnector.name.getValue().equals(((BLangInvocation) definitionContext.get(NodeContextKeys.PREVIOUSLY_VISITED_NODE_KEY)).symbol.owner.name.getValue())).flatMap(connector -> connector.actions.stream()).filter(bAction -> bAction.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.TRANSFORMER:
            bLangNode = bLangPackage.transformers.stream().filter(bTransformer -> bTransformer.name.getValue().equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            break;
        case ContextConstants.ENDPOINT:
            bLangNode = bLangPackage.globalEndpoints.stream().filter(globalEndpoint -> globalEndpoint.name.value.equals(definitionContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangNode == null) {
                DefinitionTreeVisitor definitionTreeVisitor = new DefinitionTreeVisitor(definitionContext);
                definitionContext.get(NodeContextKeys.NODE_STACK_KEY).pop().accept(definitionTreeVisitor);
                if (definitionContext.get(NodeContextKeys.NODE_KEY) != null) {
                    bLangNode = definitionContext.get(NodeContextKeys.NODE_KEY);
                }
            }
            break;
        case ContextConstants.VARIABLE:
            bLangNode = bLangPackage.globalVars.stream().filter(globalVar -> globalVar.name.getValue().equals(definitionContext.get(NodeContextKeys.VAR_NAME_OF_NODE_KEY))).findAny().orElse(null);
            // BLangNode is null only when node at the cursor position is a local variable.
            if (bLangNode == null) {
                DefinitionTreeVisitor definitionTreeVisitor = new DefinitionTreeVisitor(definitionContext);
                definitionContext.get(NodeContextKeys.NODE_STACK_KEY).pop().accept(definitionTreeVisitor);
                if (definitionContext.get(NodeContextKeys.NODE_KEY) != null) {
                    bLangNode = definitionContext.get(NodeContextKeys.NODE_KEY);
                    break;
                }
            }
            break;
        default:
            break;
    }
    if (bLangNode == null) {
        return contents;
    }
    Location l = new Location();
    TextDocumentPositionParams position = definitionContext.get(DocumentServiceKeys.POSITION_KEY);
    Path parentPath = CommonUtil.getPath(new LSDocument(position.getTextDocument().getUri())).getParent();
    if (parentPath != null) {
        String fileName = bLangNode.getPosition().getSource().getCompilationUnitName();
        Path filePath = Paths.get(CommonUtil.getPackageURI(definitionContext.get(NodeContextKeys.PACKAGE_OF_NODE_KEY).name.getValue(), parentPath.toString(), definitionContext.get(NodeContextKeys.PACKAGE_OF_NODE_KEY).name.getValue()), fileName);
        l.setUri(filePath.toUri().toString());
        Range r = new Range();
        // Subtract 1 to convert the token lines and char positions to zero based indexing
        r.setStart(new Position(bLangNode.getPosition().getStartLine() - 1, bLangNode.getPosition().getStartColumn() - 1));
        r.setEnd(new Position(bLangNode.getPosition().getEndLine() - 1, bLangNode.getPosition().getEndColumn() - 1));
        l.setRange(r);
        contents.add(l);
    }
    return contents;
}
Also used : CommonUtil(org.ballerinalang.langserver.common.utils.CommonUtil) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) TextDocumentServiceContext(org.ballerinalang.langserver.TextDocumentServiceContext) TextDocumentPositionParams(org.eclipse.lsp4j.TextDocumentPositionParams) PackageID(org.ballerinalang.model.elements.PackageID) Range(org.eclipse.lsp4j.Range) LSPackageCache(org.ballerinalang.langserver.LSPackageCache) NodeContextKeys(org.ballerinalang.langserver.common.constants.NodeContextKeys) ArrayList(java.util.ArrayList) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) DefinitionTreeVisitor(org.ballerinalang.langserver.definition.DefinitionTreeVisitor) LSDocument(org.ballerinalang.langserver.common.LSDocument) List(java.util.List) Paths(java.nio.file.Paths) ContextConstants(org.ballerinalang.langserver.common.constants.ContextConstants) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) Location(org.eclipse.lsp4j.Location) Position(org.eclipse.lsp4j.Position) Path(java.nio.file.Path) DocumentServiceKeys(org.ballerinalang.langserver.DocumentServiceKeys) Path(java.nio.file.Path) Position(org.eclipse.lsp4j.Position) ArrayList(java.util.ArrayList) Range(org.eclipse.lsp4j.Range) DefinitionTreeVisitor(org.ballerinalang.langserver.definition.DefinitionTreeVisitor) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) LSDocument(org.ballerinalang.langserver.common.LSDocument) TextDocumentPositionParams(org.eclipse.lsp4j.TextDocumentPositionParams) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) Location(org.eclipse.lsp4j.Location)

Example 67 with BLangPackage

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

the class TextDocumentFormatUtil method getAST.

/**
 * Get the AST for the current text document's content.
 *
 * @param params          Document Formatting parameters
 * @param documentManager Workspace document manager instance
 * @param context         Document formatting context
 * @return {@link JsonObject}   AST as a Json Object
 */
public static JsonObject getAST(DocumentFormattingParams params, WorkspaceDocumentManager documentManager, TextDocumentServiceContext context) {
    String documentUri = params.getTextDocument().getUri();
    String[] uriParts = documentUri.split(Pattern.quote(File.separator));
    String fileName = uriParts[uriParts.length - 1];
    final BLangPackage bLangPackage = TextDocumentServiceUtil.getBLangPackage(context, documentManager, true, LSCustomErrorStrategy.class, false).get(0);
    context.put(DocumentServiceKeys.CURRENT_PACKAGE_NAME_KEY, bLangPackage.symbol.getName().getValue());
    final List<Diagnostic> diagnostics = new ArrayList<>();
    JsonArray errors = new JsonArray();
    JsonObject result = new JsonObject();
    result.add("errors", errors);
    Gson gson = new Gson();
    JsonElement diagnosticsJson = gson.toJsonTree(diagnostics);
    result.add("diagnostics", diagnosticsJson);
    BLangCompilationUnit compilationUnit = bLangPackage.getCompilationUnits().stream().filter(compUnit -> fileName.equals(compUnit.getName())).findFirst().orElseGet(null);
    JsonElement modelElement = CommonUtil.generateJSON(compilationUnit, new HashMap<>());
    result.add("model", modelElement);
    return result;
}
Also used : ArrayList(java.util.ArrayList) 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) LSCustomErrorStrategy(org.ballerinalang.langserver.common.LSCustomErrorStrategy) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit)

Example 68 with BLangPackage

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

the class HoverUtil method getHoverInformation.

/**
 * Get the hover information for the given hover context.
 *
 * @param bLangPackage resolved bLangPackage for the hover context.
 * @param hoverContext context of the hover.
 * @return hover content.
 */
public static Hover getHoverInformation(BLangPackage bLangPackage, TextDocumentServiceContext hoverContext) {
    Hover hover;
    switch(hoverContext.get(NodeContextKeys.SYMBOL_KIND_OF_NODE_PARENT_KEY)) {
        case ContextConstants.FUNCTION:
            BLangFunction bLangFunction = bLangPackage.functions.stream().filter(function -> function.name.getValue().equals(hoverContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangFunction != null) {
                if (bLangFunction.docAttachments.size() > 0) {
                    hover = getDocumentationContent(bLangFunction.docAttachments);
                } else {
                    hover = getAnnotationContent(bLangFunction.annAttachments);
                }
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        case ContextConstants.STRUCT:
            BLangStruct bLangStruct = bLangPackage.structs.stream().filter(struct -> struct.name.getValue().equals(hoverContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangStruct != null) {
                if (bLangStruct.docAttachments.size() > 0) {
                    hover = getDocumentationContent(bLangStruct.docAttachments);
                } else {
                    hover = getAnnotationContent(bLangStruct.annAttachments);
                }
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        case ContextConstants.OBJECT:
            BLangObject bLangObject = bLangPackage.objects.stream().filter(object -> object.name.getValue().equals(hoverContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangObject != null) {
                if (bLangObject.docAttachments.size() > 0) {
                    hover = getDocumentationContent(bLangObject.docAttachments);
                } else {
                    hover = getAnnotationContent(bLangObject.annAttachments);
                }
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        case ContextConstants.ENUM:
            BLangEnum bLangEnum = bLangPackage.enums.stream().filter(bEnum -> bEnum.name.getValue().equals(hoverContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangEnum != null) {
                if (bLangEnum.docAttachments.size() > 0) {
                    hover = getDocumentationContent(bLangEnum.docAttachments);
                } else {
                    hover = getAnnotationContent(bLangEnum.annAttachments);
                }
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        case ContextConstants.TRANSFORMER:
            BLangTransformer bLangTransformer = bLangPackage.transformers.stream().filter(bTransformer -> bTransformer.name.getValue().equals(hoverContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangTransformer != null) {
                if (bLangTransformer.docAttachments.size() > 0) {
                    hover = getDocumentationContent(bLangTransformer.docAttachments);
                } else {
                    hover = getAnnotationContent(bLangTransformer.annAttachments);
                }
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        case ContextConstants.CONNECTOR:
            BLangConnector bLangConnector = bLangPackage.connectors.stream().filter(bConnector -> bConnector.name.getValue().equals(hoverContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangConnector != null) {
                if (bLangConnector.docAttachments.size() > 0) {
                    hover = getDocumentationContent(bLangConnector.docAttachments);
                } else {
                    hover = getAnnotationContent(bLangConnector.annAttachments);
                }
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        case ContextConstants.ACTION:
            BLangAction bLangAction = bLangPackage.connectors.stream().filter(bConnector -> bConnector.name.getValue().equals(((BLangInvocation) hoverContext.get(NodeContextKeys.PREVIOUSLY_VISITED_NODE_KEY)).symbol.owner.name.getValue())).flatMap(connector -> connector.actions.stream()).filter(bAction -> bAction.name.getValue().equals(hoverContext.get(NodeContextKeys.NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangAction != null) {
                if (bLangAction.docAttachments.size() > 0) {
                    hover = getDocumentationContent(bLangAction.docAttachments);
                } else {
                    hover = getAnnotationContent(bLangAction.annAttachments);
                }
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        case ContextConstants.ENDPOINT:
            BLangEndpoint bLangEndpoint = bLangPackage.globalEndpoints.stream().filter(globalEndpoint -> globalEndpoint.name.value.equals(hoverContext.get(NodeContextKeys.VAR_NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangEndpoint != null) {
                hover = getAnnotationContent(bLangEndpoint.annAttachments);
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        case ContextConstants.VARIABLE:
            BLangVariable bLangVariable = bLangPackage.globalVars.stream().filter(globalVar -> globalVar.name.getValue().equals(hoverContext.get(NodeContextKeys.VAR_NAME_OF_NODE_KEY))).findAny().orElse(null);
            if (bLangVariable != null) {
                if (bLangVariable.docAttachments.size() > 0) {
                    hover = getDocumentationContent(bLangVariable.docAttachments);
                } else {
                    hover = getAnnotationContent(bLangVariable.annAttachments);
                }
            } else {
                hover = getDefaultHoverObject();
            }
            break;
        default:
            hover = new Hover();
            List<Either<String, MarkedString>> contents = new ArrayList<>();
            contents.add(Either.forLeft(""));
            hover.setContents(contents);
            break;
    }
    return hover;
}
Also used : BLangTransformer(org.wso2.ballerinalang.compiler.tree.BLangTransformer) BLangVariable(org.wso2.ballerinalang.compiler.tree.BLangVariable) HashMap(java.util.HashMap) BLangRecordLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral) Hover(org.eclipse.lsp4j.Hover) NodeContextKeys(org.ballerinalang.langserver.common.constants.NodeContextKeys) ArrayList(java.util.ArrayList) PositionTreeVisitor(org.ballerinalang.langserver.common.position.PositionTreeVisitor) ContextConstants(org.ballerinalang.langserver.common.constants.ContextConstants) Map(java.util.Map) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) Position(org.eclipse.lsp4j.Position) DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) DocumentServiceKeys(org.ballerinalang.langserver.DocumentServiceKeys) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) TextDocumentServiceContext(org.ballerinalang.langserver.TextDocumentServiceContext) BLangObject(org.wso2.ballerinalang.compiler.tree.BLangObject) MarkedString(org.eclipse.lsp4j.MarkedString) LSPackageCache(org.ballerinalang.langserver.LSPackageCache) BLangDocumentation(org.wso2.ballerinalang.compiler.tree.BLangDocumentation) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) BLangAnnotationAttachment(org.wso2.ballerinalang.compiler.tree.BLangAnnotationAttachment) BLangTransformer(org.wso2.ballerinalang.compiler.tree.BLangTransformer) List(java.util.List) BLangEnum(org.wso2.ballerinalang.compiler.tree.BLangEnum) BLangLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangLiteral) BLangInvocation(org.wso2.ballerinalang.compiler.tree.expressions.BLangInvocation) BLangConnector(org.wso2.ballerinalang.compiler.tree.BLangConnector) BLangDocumentationAttribute(org.wso2.ballerinalang.compiler.tree.expressions.BLangDocumentationAttribute) BLangEndpoint(org.wso2.ballerinalang.compiler.tree.BLangEndpoint) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) BLangAction(org.wso2.ballerinalang.compiler.tree.BLangAction) BLangEndpoint(org.wso2.ballerinalang.compiler.tree.BLangEndpoint) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) ArrayList(java.util.ArrayList) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) BLangEnum(org.wso2.ballerinalang.compiler.tree.BLangEnum) BLangVariable(org.wso2.ballerinalang.compiler.tree.BLangVariable) BLangAction(org.wso2.ballerinalang.compiler.tree.BLangAction) BLangObject(org.wso2.ballerinalang.compiler.tree.BLangObject) Hover(org.eclipse.lsp4j.Hover) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) BLangConnector(org.wso2.ballerinalang.compiler.tree.BLangConnector)

Example 69 with BLangPackage

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

the class Generator method generatePageForPrimitives.

/**
 * Generate the page for primitive types.
 * @param balPackage The ballerina.builtin package.
 * @param packages List of available packages.
 * @return A page model for the primitive types.
 */
public static Page generatePageForPrimitives(BLangPackage balPackage, List<Link> packages) {
    ArrayList<Documentable> primitiveTypes = new ArrayList<>();
    // Check for functions in the package
    if (balPackage.getFunctions().size() > 0) {
        for (BLangFunction function : balPackage.getFunctions()) {
            if (function.getFlags().contains(Flag.PUBLIC) && function.getReceiver() != null) {
                TypeNode langType = function.getReceiver().getTypeNode();
                if (!(langType instanceof BLangUserDefinedType)) {
                    // Check for primitives in ballerina.builtin
                    Optional<PrimitiveTypeDoc> existingPrimitiveType = primitiveTypes.stream().filter((doc) -> doc instanceof PrimitiveTypeDoc && (((PrimitiveTypeDoc) doc)).name.equals(langType.toString())).map(doc -> (PrimitiveTypeDoc) doc).findFirst();
                    PrimitiveTypeDoc primitiveTypeDoc;
                    if (existingPrimitiveType.isPresent()) {
                        primitiveTypeDoc = existingPrimitiveType.get();
                    } else {
                        primitiveTypeDoc = new PrimitiveTypeDoc(langType.toString(), new ArrayList<>());
                        primitiveTypes.add(primitiveTypeDoc);
                    }
                    primitiveTypeDoc.children.add(createDocForNode(function));
                }
            }
        }
    }
    // Create the links to select which page or package is active
    List<Link> links = new ArrayList<>();
    for (Link pkgLink : packages) {
        if (BallerinaDocConstants.PRIMITIVE_TYPES_PAGE_NAME.equals(pkgLink.caption.value)) {
            links.add(new Link(pkgLink.caption, pkgLink.href, true));
        } else {
            links.add(new Link(pkgLink.caption, pkgLink.href, false));
        }
    }
    StaticCaption primitivesPageHeading = new StaticCaption(BallerinaDocConstants.PRIMITIVE_TYPES_PAGE_NAME);
    return new Page(primitivesPageHeading, primitiveTypes, links);
}
Also used : AnnotationDoc(org.ballerinalang.docgen.model.AnnotationDoc) AnnotatableNode(org.ballerinalang.model.tree.AnnotatableNode) BLangUserDefinedType(org.wso2.ballerinalang.compiler.tree.types.BLangUserDefinedType) Link(org.ballerinalang.docgen.model.Link) BLangVariable(org.wso2.ballerinalang.compiler.tree.BLangVariable) BLangAnnotation(org.wso2.ballerinalang.compiler.tree.BLangAnnotation) Field(org.ballerinalang.docgen.model.Field) BLangRecordLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral) ArrayList(java.util.ArrayList) Page(org.ballerinalang.docgen.model.Page) Flag(org.ballerinalang.model.elements.Flag) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) EnumNode(org.ballerinalang.model.tree.EnumNode) BStructType(org.wso2.ballerinalang.compiler.semantics.model.types.BStructType) BLangExpression(org.wso2.ballerinalang.compiler.tree.expressions.BLangExpression) FunctionDoc(org.ballerinalang.docgen.model.FunctionDoc) ConnectorDoc(org.ballerinalang.docgen.model.ConnectorDoc) EnumDoc(org.ballerinalang.docgen.model.EnumDoc) TypeNode(org.ballerinalang.model.tree.types.TypeNode) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) BLangAnnotAttribute(org.wso2.ballerinalang.compiler.tree.BLangAnnotAttribute) AnnotationAttachmentNode(org.ballerinalang.model.tree.AnnotationAttachmentNode) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) ActionDoc(org.ballerinalang.docgen.model.ActionDoc) StaticCaption(org.ballerinalang.docgen.model.StaticCaption) List(java.util.List) BLangEnum(org.wso2.ballerinalang.compiler.tree.BLangEnum) Variable(org.ballerinalang.docgen.model.Variable) NodeKind(org.ballerinalang.model.tree.NodeKind) BLangConnector(org.wso2.ballerinalang.compiler.tree.BLangConnector) PackageName(org.ballerinalang.docgen.model.PackageName) Optional(java.util.Optional) Documentable(org.ballerinalang.docgen.model.Documentable) GlobalVariableDoc(org.ballerinalang.docgen.model.GlobalVariableDoc) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) BallerinaDocConstants(org.ballerinalang.docgen.docs.BallerinaDocConstants) PrimitiveTypeDoc(org.ballerinalang.docgen.model.PrimitiveTypeDoc) StructDoc(org.ballerinalang.docgen.model.StructDoc) BLangAction(org.wso2.ballerinalang.compiler.tree.BLangAction) BLangType(org.wso2.ballerinalang.compiler.tree.types.BLangType) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) ArrayList(java.util.ArrayList) Page(org.ballerinalang.docgen.model.Page) StaticCaption(org.ballerinalang.docgen.model.StaticCaption) Documentable(org.ballerinalang.docgen.model.Documentable) TypeNode(org.ballerinalang.model.tree.types.TypeNode) BLangUserDefinedType(org.wso2.ballerinalang.compiler.tree.types.BLangUserDefinedType) PrimitiveTypeDoc(org.ballerinalang.docgen.model.PrimitiveTypeDoc) Link(org.ballerinalang.docgen.model.Link)

Example 70 with BLangPackage

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

the class BallerinaDocGenerator method generateApiDocs.

/**
 * API to generate Ballerina API documentation.
 *
 * @param output        path to the output directory where the API documentation will be written to.
 * @param packageFilter comma separated list of package names to be filtered from the documentation.
 * @param isNative      whether the given packages are native or not.
 * @param sources       either the path to the directories where Ballerina source files reside or a
 *                      path to a Ballerina file which does not belong to a package.
 */
public static void generateApiDocs(String output, String packageFilter, boolean isNative, String... sources) {
    out.println("docerina: API documentation generation for sources - " + Arrays.toString(sources));
    for (String source : sources) {
        source = source.trim();
        try {
            Map<String, BLangPackage> docsMap;
            if (source.endsWith(".bal")) {
                Path sourceFilePath = Paths.get(source);
                Path parentDir = sourceFilePath.getParent();
                Path fileName = sourceFilePath.getFileName();
                if (fileName == null) {
                    log.warn("Skipping the source generation for invalid path: " + sourceFilePath);
                    continue;
                }
                if (parentDir == null) {
                    parentDir = Paths.get(".");
                }
                docsMap = generatePackageDocsFromBallerina(parentDir.toString(), fileName, packageFilter, isNative);
            } else {
                Path dirPath = Paths.get(source);
                // TODO fix this properly
                // TODO Temporary fix that creates .ballerina to create project structure
                Path projectFolder = dirPath.resolve(ProjectDirConstants.DOT_BALLERINA_DIR_NAME);
                Files.createDirectory(projectFolder);
                Path sourceRootPath = LauncherUtils.getSourceRootPath(dirPath.toString());
                docsMap = generatePackageDocsFromBallerina(sourceRootPath.toString(), dirPath, packageFilter, isNative);
            }
            if (docsMap.size() == 0) {
                out.println("docerina: no package definitions found!");
                return;
            }
            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("Generating HTML API documentation...");
            }
            String userDir = System.getProperty("user.dir");
            // If output directory is empty
            if (output == null) {
                output = System.getProperty(BallerinaDocConstants.HTML_OUTPUT_PATH_KEY, userDir + File.separator + "api-docs" + File.separator + "html");
            }
            // Create output directories
            Files.createDirectories(Paths.get(output));
            // Sort packages by package path
            List<BLangPackage> packageList = new ArrayList<>(docsMap.values());
            packageList.sort(Comparator.comparing(pkg -> pkg.packageID.toString()));
            // Iterate over the packages to generate the pages
            List<String> packageNames = new ArrayList<>(docsMap.keySet());
            // Sort the package names
            Collections.sort(packageNames);
            List<Link> packageNameList = PackageName.convertList(packageNames);
            if (packageNames.contains("ballerina.builtin")) {
                StaticCaption primitivesLinkName = new StaticCaption(BallerinaDocConstants.PRIMITIVE_TYPES_PAGE_NAME);
                packageNameList.add(0, new Link(primitivesLinkName, BallerinaDocConstants.PRIMITIVE_TYPES_PAGE_HREF, false));
            }
            // Generate pages for the packages
            String packageTemplateName = System.getProperty(BallerinaDocConstants.PACKAGE_TEMPLATE_NAME_KEY, "page");
            for (BLangPackage bLangPackage : packageList) {
                // Sort functions, connectors, structs, type mappers and annotationDefs
                bLangPackage.getFunctions().sort(Comparator.comparing(f -> (f.getReceiver() == null ? "" : f.getReceiver().getName()) + f.getName().getValue()));
                bLangPackage.getConnectors().sort(Comparator.comparing(c -> c.getName().getValue()));
                bLangPackage.getStructs().sort(Comparator.comparing(s -> s.getName().getValue()));
                bLangPackage.getAnnotations().sort(Comparator.comparing(a -> a.getName().getValue()));
                bLangPackage.getEnums().sort(Comparator.comparing(a -> a.getName().getValue()));
                // Sort connector actions
                if ((bLangPackage.getConnectors() != null) && (bLangPackage.getConnectors().size() > 0)) {
                    bLangPackage.getConnectors().forEach(connector -> connector.getActions().sort(Comparator.comparing(a -> a.getName().getValue())));
                }
                String packagePath = refinePackagePath(bLangPackage);
                Page page = Generator.generatePage(bLangPackage, packageNameList);
                String filePath = output + File.separator + packagePath + HTML;
                Writer.writeHtmlDocument(page, packageTemplateName, filePath);
                if ("ballerina.builtin".equals(packagePath)) {
                    Page primitivesPage = Generator.generatePageForPrimitives(bLangPackage, packageNameList);
                    String primitivesFilePath = output + File.separator + "primitive-types" + HTML;
                    Writer.writeHtmlDocument(primitivesPage, packageTemplateName, primitivesFilePath);
                }
            }
            // Generate the index file with the list of all packages
            String indexTemplateName = System.getProperty(BallerinaDocConstants.PACKAGE_TEMPLATE_NAME_KEY, "index");
            String indexFilePath = output + File.separator + "index" + HTML;
            Writer.writeHtmlDocument(packageNameList, indexTemplateName, indexFilePath);
            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("Copying HTML theme...");
            }
            BallerinaDocUtils.copyResources("docerina-theme", output);
        } catch (IOException e) {
            out.println(String.format("docerina: API documentation generation failed for %s: %s", source, e.getMessage()));
            log.error(String.format("API documentation generation failed for %s", source), e);
        }
    }
    try {
        String zipPath = System.getProperty(BallerinaDocConstants.OUTPUT_ZIP_PATH);
        if (zipPath != null) {
            BallerinaDocUtils.packageToZipFile(output, zipPath);
        }
    } catch (IOException e) {
        out.println(String.format("docerina: API documentation zip packaging failed for %s: %s", output, e.getMessage()));
        log.error(String.format("API documentation zip packaging failed for %s", output), e);
    }
}
Also used : Path(java.nio.file.Path) ProjectDirConstants(org.wso2.ballerinalang.compiler.util.ProjectDirConstants) Arrays(java.util.Arrays) Link(org.ballerinalang.docgen.model.Link) Generator(org.ballerinalang.docgen.Generator) LoggerFactory(org.slf4j.LoggerFactory) Compiler(org.wso2.ballerinalang.compiler.Compiler) PackageLoader(org.wso2.ballerinalang.compiler.PackageLoader) ArrayList(java.util.ArrayList) Page(org.ballerinalang.docgen.model.Page) Writer(org.ballerinalang.docgen.Writer) Map(java.util.Map) Names(org.wso2.ballerinalang.compiler.util.Names) Path(java.nio.file.Path) LauncherUtils(org.ballerinalang.launcher.LauncherUtils) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) PrintStream(java.io.PrintStream) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Files(java.nio.file.Files) CompilerPhase(org.ballerinalang.compiler.CompilerPhase) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) CodeAnalyzer(org.wso2.ballerinalang.compiler.semantics.analyzer.CodeAnalyzer) File(java.io.File) SemanticAnalyzer(org.wso2.ballerinalang.compiler.semantics.analyzer.SemanticAnalyzer) FileVisitResult(java.nio.file.FileVisitResult) BallerinaDocUtils(org.ballerinalang.docgen.docs.utils.BallerinaDocUtils) StaticCaption(org.ballerinalang.docgen.model.StaticCaption) List(java.util.List) Paths(java.nio.file.Paths) StringJoiner(java.util.StringJoiner) PackageName(org.ballerinalang.docgen.model.PackageName) CompilerOptionName(org.ballerinalang.compiler.CompilerOptionName) Comparator(java.util.Comparator) CompilerOptions(org.wso2.ballerinalang.compiler.util.CompilerOptions) Collections(java.util.Collections) SymbolTable(org.wso2.ballerinalang.compiler.semantics.model.SymbolTable) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) ArrayList(java.util.ArrayList) Page(org.ballerinalang.docgen.model.Page) IOException(java.io.IOException) StaticCaption(org.ballerinalang.docgen.model.StaticCaption) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) Link(org.ballerinalang.docgen.model.Link)

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