Search in sources :

Example 1 with BallerinaFile

use of org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile 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 BallerinaFile

use of org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile 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 BallerinaFile

use of org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile in project ballerina by ballerina-lang.

the class ParserUtils method compileFragment.

/**
 * Return a compilation unit for a given text.
 *
 * @param content
 * @return
 */
public static BLangCompilationUnit compileFragment(String content) {
    Path unsaved = Paths.get(untitledProject.toString(), UNTITLED_BAL);
    synchronized (ParserUtils.class) {
        // Since we use the same file name for all the fragment passes we need to make sure following -
        // does not run parallelly.
        documentManager.openFile(unsaved, content);
        BallerinaFile model = compile(content, unsaved, CompilerPhase.DEFINE);
        documentManager.closeFile(unsaved);
        if (model.getBLangPackage() != null) {
            return model.getBLangPackage().getCompilationUnits().stream().filter(compUnit -> UNTITLED_BAL.equals(compUnit.getName())).findFirst().get();
        }
    }
    return null;
}
Also used : Path(java.nio.file.Path) BallerinaFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile)

Example 4 with BallerinaFile

use of org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile in project ballerina by ballerina-lang.

the class ParserUtils method getBallerinaFile.

/**
 * Returns an object which contains Ballerina model and Diagnostic information.
 *
 * @param fileName - File name
 * @param context  - CompilerContext
 * @return BallerinaFile - Object which contains Ballerina model and Diagnostic information
 */
private static BallerinaFile getBallerinaFile(Path packagePath, String fileName, CompilerContext context) {
    List<Diagnostic> diagnostics = new ArrayList<>();
    ComposerDiagnosticListener composerDiagnosticListener = new ComposerDiagnosticListener(diagnostics);
    context.put(DiagnosticListener.class, composerDiagnosticListener);
    BallerinaFile ballerinaFile = new BallerinaFile();
    CompilerOptions options = CompilerOptions.getInstance(context);
    options.put(PROJECT_DIR, packagePath.toString());
    options.put(COMPILER_PHASE, CompilerPhase.DEFINE.toString());
    options.put(PRESERVE_WHITESPACE, "true");
    context.put(SourceDirectory.class, new FileSystemProjectDirectory(packagePath));
    Compiler compiler = Compiler.getInstance(context);
    // compile
    try {
        ballerinaFile.setBLangPackage(compiler.compile(fileName));
    } catch (Exception ex) {
        BDiagnostic catastrophic = new BDiagnostic();
        catastrophic.msg = "Failed in the runtime parse/analyze. " + ex.getMessage();
        diagnostics.add(catastrophic);
    }
    ballerinaFile.setDiagnostics(diagnostics);
    return ballerinaFile;
}
Also used : Compiler(org.wso2.ballerinalang.compiler.Compiler) FileSystemProjectDirectory(org.wso2.ballerinalang.compiler.FileSystemProjectDirectory) BallerinaFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile) ArrayList(java.util.ArrayList) CompilerOptions(org.wso2.ballerinalang.compiler.util.CompilerOptions) Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic) BDiagnostic(org.wso2.ballerinalang.compiler.util.diagnotic.BDiagnostic) BDiagnostic(org.wso2.ballerinalang.compiler.util.diagnotic.BDiagnostic) IOException(java.io.IOException)

Example 5 with BallerinaFile

use of org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile 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

BallerinaFile (org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile)5 IOException (java.io.IOException)3 Path (java.nio.file.Path)3 Diagnostic (org.ballerinalang.util.diagnostic.Diagnostic)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 ModelPackage (org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage)2 Compiler (org.wso2.ballerinalang.compiler.Compiler)2 BLangCompilationUnit (org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit)2 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)2 BDiagnostic (org.wso2.ballerinalang.compiler.util.diagnotic.BDiagnostic)2 Gson (com.google.gson.Gson)1 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 Swagger (io.swagger.models.Swagger)1 Yaml (io.swagger.v3.core.util.Yaml)1 SwaggerConverter (io.swagger.v3.parser.converter.SwaggerConverter)1 Files (java.nio.file.Files)1 Paths (java.nio.file.Paths)1