Search in sources :

Example 1 with BLangCompilationUnit

use of org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit 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 2 with BLangCompilationUnit

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

the class Parser method generateCompilationUnit.

private CompilationUnitNode generateCompilationUnit(PackageSourceEntry sourceEntry) {
    try {
        int prevErrCount = dlog.errorCount;
        BDiagnosticSource diagnosticSrc = getDiagnosticSource(sourceEntry);
        String entryName = sourceEntry.getEntryName();
        BLangCompilationUnit compUnit = (BLangCompilationUnit) TreeBuilder.createCompilationUnit();
        compUnit.setName(sourceEntry.getEntryName());
        compUnit.pos = new DiagnosticPos(diagnosticSrc, 1, 1, 1, 1);
        ANTLRInputStream ais = new ANTLRInputStream(new ByteArrayInputStream(sourceEntry.getCode()));
        ais.name = entryName;
        BallerinaLexer lexer = new BallerinaLexer(ais);
        lexer.removeErrorListeners();
        lexer.addErrorListener(new BallerinaParserErrorListener(context, diagnosticSrc));
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        BallerinaParser parser = new BallerinaParser(tokenStream);
        parser.setErrorHandler(getErrorStrategy(diagnosticSrc));
        parser.addParseListener(newListener(tokenStream, compUnit, diagnosticSrc));
        parser.compilationUnit();
        return compUnit;
    } catch (IOException e) {
        throw new RuntimeException("Error in populating package model: " + e.getMessage(), e);
    }
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) BDiagnosticSource(org.wso2.ballerinalang.compiler.util.diagnotic.BDiagnosticSource) IOException(java.io.IOException) BallerinaParser(org.wso2.ballerinalang.compiler.parser.antlr4.BallerinaParser) DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) ByteArrayInputStream(java.io.ByteArrayInputStream) BallerinaParserErrorListener(org.wso2.ballerinalang.compiler.parser.antlr4.BallerinaParserErrorListener) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit) BallerinaLexer(org.wso2.ballerinalang.compiler.parser.antlr4.BallerinaLexer) ANTLRInputStream(org.antlr.v4.runtime.ANTLRInputStream)

Example 3 with BLangCompilationUnit

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

the class SwaggerConverterUtils method generateSwaggerDefinitions.

/**
 * This method will generate ballerina string from swagger definition. Since ballerina service definition is super
 * set of swagger definition we will take both swagger and ballerina definition and merge swagger changes to
 * ballerina definition selectively to prevent data loss
 *
 * @param ballerinaSource ballerina definition to be process as ballerina definition
 * @param serviceName service name
 * @return String representation of converted ballerina source
 * @throws IOException when error occur while processing input swagger and ballerina definitions.
 */
public static String generateSwaggerDefinitions(String ballerinaSource, String serviceName) throws IOException {
    // Get the ballerina model using the ballerina source code.
    BFile balFile = new BFile();
    balFile.setContent(ballerinaSource);
    BLangCompilationUnit topCompilationUnit = SwaggerConverterUtils.getTopLevelNodeFromBallerinaFile(balFile);
    String httpAlias = getAlias(topCompilationUnit, Constants.BALLERINA_HTTP_PACKAGE_NAME);
    String swaggerAlias = getAlias(topCompilationUnit, Constants.SWAGGER_PACKAGE_NAME);
    SwaggerServiceMapper swaggerServiceMapper = new SwaggerServiceMapper(httpAlias, swaggerAlias);
    String swaggerSource = StringUtils.EMPTY;
    for (TopLevelNode topLevelNode : topCompilationUnit.getTopLevelNodes()) {
        if (topLevelNode instanceof BLangService) {
            ServiceNode serviceDefinition = (ServiceNode) topLevelNode;
            // Generate swagger string for the mentioned service name.
            if (StringUtils.isNotBlank(serviceName)) {
                if (serviceDefinition.getName().getValue().equals(serviceName)) {
                    Swagger swaggerDefinition = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition);
                    swaggerSource = swaggerServiceMapper.generateSwaggerString(swaggerDefinition);
                    break;
                }
            } else {
                // If no service name mentioned, then generate swagger definition for the first service.
                Swagger swaggerDefinition = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition);
                swaggerSource = swaggerServiceMapper.generateSwaggerString(swaggerDefinition);
                break;
            }
        }
    }
    return swaggerSource;
}
Also used : ServiceNode(org.ballerinalang.model.tree.ServiceNode) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) Swagger(io.swagger.models.Swagger) BFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BFile) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode)

Example 4 with BLangCompilationUnit

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

the class SwaggerConverterUtils method generateOAS3Definitions.

/**
 * This method will generate open API 3.X specification for given ballerina service. Since we will need to
 * support both swagger 2.0 and OAS 3.0 it was implemented to convert to swagger by default and convert it
 * to OAS on demand.
 *
 * @param ballerinaSource ballerina source to be converted to swagger/OAS definition
 * @param serviceName specific service name within ballerina source that need to map OAS
 * @return Generated OAS3 string output.
 * @throws IOException When error occurs while converting, parsing input source.
 */
public static String generateOAS3Definitions(String ballerinaSource, String serviceName) throws IOException {
    // Get the ballerina model using the ballerina source code.
    BFile balFile = new BFile();
    balFile.setContent(ballerinaSource);
    // Create empty swagger object.
    Swagger swaggerDefinition = new Swagger();
    BLangCompilationUnit topCompilationUnit = SwaggerConverterUtils.getTopLevelNodeFromBallerinaFile(balFile);
    String httpAlias = getAlias(topCompilationUnit, Constants.BALLERINA_HTTP_PACKAGE_NAME);
    String swaggerAlias = getAlias(topCompilationUnit, Constants.SWAGGER_PACKAGE_NAME);
    SwaggerServiceMapper swaggerServiceMapper = new SwaggerServiceMapper(httpAlias, swaggerAlias);
    String swaggerSource = StringUtils.EMPTY;
    for (TopLevelNode topLevelNode : topCompilationUnit.getTopLevelNodes()) {
        if (topLevelNode instanceof BLangService) {
            ServiceNode serviceDefinition = (ServiceNode) topLevelNode;
            // Generate swagger string for the mentioned service name.
            if (StringUtils.isNotBlank(serviceName)) {
                if (serviceDefinition.getName().getValue().equals(serviceName)) {
                    swaggerDefinition = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition);
                    break;
                }
            } else {
                // If no service name mentioned, then generate swagger definition for the first service.
                swaggerDefinition = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition);
                break;
            }
        }
    }
    swaggerSource = swaggerServiceMapper.generateSwaggerString(swaggerDefinition);
    SwaggerConverter converter = new SwaggerConverter();
    return Yaml.pretty(converter.readContents(swaggerSource, null, null).getOpenAPI());
}
Also used : ServiceNode(org.ballerinalang.model.tree.ServiceNode) Swagger(io.swagger.models.Swagger) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) SwaggerConverter(io.swagger.v3.parser.converter.SwaggerConverter) BFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BFile) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode)

Example 5 with BLangCompilationUnit

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

the class SwaggerConverterUtils method getTopLevelNodeFromBallerinaFile.

/**
 * Generate ballerina fine from the String definition.
 *
 * @param bFile ballerina string definition
 * @return ballerina file created from ballerina string definition
 * @throws IOException IO exception
 */
public static BLangCompilationUnit getTopLevelNodeFromBallerinaFile(BFile bFile) throws IOException {
    String filePath = bFile.getFilePath();
    String fileName = bFile.getFileName();
    String content = bFile.getContent();
    Path fileRoot = Paths.get(filePath);
    org.wso2.ballerinalang.compiler.tree.BLangPackage model;
    // Sometimes we are getting Ballerina content without a file in the file-system.
    if (!Files.exists(Paths.get(filePath, fileName))) {
        BallerinaFile ballerinaFile = ParserUtils.getBallerinaFileForContent(fileRoot, fileName, content, CompilerPhase.CODE_ANALYZE);
        model = ballerinaFile.getBLangPackage();
    } else {
        BallerinaFile ballerinaFile = ParserUtils.getBallerinaFile(filePath, fileName);
        model = ballerinaFile.getBLangPackage();
    }
    final Map<String, ModelPackage> modelPackage = new HashMap<>();
    ParserUtils.loadPackageMap(Constants.CURRENT_PACKAGE_NAME, model, modelPackage);
    Optional<BLangCompilationUnit> compilationUnit = model.getCompilationUnits().stream().filter(compUnit -> fileName.equals(compUnit.getName())).findFirst();
    return compilationUnit.orElse(null);
}
Also used : Path(java.nio.file.Path) Constants(org.ballerinalang.ballerina.swagger.convertor.Constants) SwaggerConverter(io.swagger.v3.parser.converter.SwaggerConverter) Files(java.nio.file.Files) Yaml(io.swagger.v3.core.util.Yaml) CompilerPhase(org.ballerinalang.compiler.CompilerPhase) Swagger(io.swagger.models.Swagger) BFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BFile) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) IOException(java.io.IOException) HashMap(java.util.HashMap) BLangIdentifier(org.wso2.ballerinalang.compiler.tree.BLangIdentifier) StringUtils(org.apache.commons.lang3.StringUtils) ParserUtils(org.ballerinalang.composer.service.ballerina.parser.service.util.ParserUtils) Collectors(java.util.stream.Collectors) ServiceNode(org.ballerinalang.model.tree.ServiceNode) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) BLangImportPackage(org.wso2.ballerinalang.compiler.tree.BLangImportPackage) Paths(java.nio.file.Paths) Map(java.util.Map) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit) Optional(java.util.Optional) Path(java.nio.file.Path) BallerinaFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile) BallerinaFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile) HashMap(java.util.HashMap) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit)

Aggregations

BLangCompilationUnit (org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit)9 TopLevelNode (org.ballerinalang.model.tree.TopLevelNode)5 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)4 JsonObject (com.google.gson.JsonObject)3 Swagger (io.swagger.models.Swagger)3 Path (java.nio.file.Path)3 HashMap (java.util.HashMap)3 BFile (org.ballerinalang.composer.service.ballerina.parser.service.model.BFile)3 ServiceNode (org.ballerinalang.model.tree.ServiceNode)3 BLangService (org.wso2.ballerinalang.compiler.tree.BLangService)3 Gson (com.google.gson.Gson)2 JsonArray (com.google.gson.JsonArray)2 JsonElement (com.google.gson.JsonElement)2 SwaggerConverter (io.swagger.v3.parser.converter.SwaggerConverter)2 IOException (java.io.IOException)2 Paths (java.nio.file.Paths)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 Optional (java.util.Optional)2 BallerinaFile (org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile)2