Search in sources :

Example 1 with Diagnostic

use of org.ballerinalang.util.diagnostic.Diagnostic 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 Diagnostic

use of org.ballerinalang.util.diagnostic.Diagnostic 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 3 with Diagnostic

use of org.ballerinalang.util.diagnostic.Diagnostic in project ballerina by ballerina-lang.

the class BAssertUtil method validateErrorMessageOnly.

/**
 * Validate if given text is contained in the error message.
 *
 * @param result          Result from compilation
 * @param errorIndex      Index of the error in the result
 * @param expectedPartOfErrMsg  Expected part of error message
 */
public static void validateErrorMessageOnly(CompileResult result, int errorIndex, String expectedPartOfErrMsg) {
    Diagnostic diag = result.getDiagnostics()[errorIndex];
    Assert.assertEquals(diag.getKind(), Diagnostic.Kind.ERROR, "incorrect diagnostic type");
    Assert.assertTrue(diag.getMessage().contains(expectedPartOfErrMsg), '\'' + expectedPartOfErrMsg + "' is not contained in error message '" + diag.getMessage() + '\'');
}
Also used : Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic)

Example 4 with Diagnostic

use of org.ballerinalang.util.diagnostic.Diagnostic in project ballerina by ballerina-lang.

the class BAssertUtil method validateError.

/**
 * Assert an error.
 *
 * @param result          Result from compilation
 * @param errorIndex      Index of the error in the result
 * @param expectedErrMsg  Expected error message
 * @param expectedErrLine Expected line number of the error
 * @param expectedErrCol  Expected column number of the error
 */
public static void validateError(CompileResult result, int errorIndex, String expectedErrMsg, int expectedErrLine, int expectedErrCol) {
    Diagnostic diag = result.getDiagnostics()[errorIndex];
    Assert.assertEquals(diag.getKind(), Diagnostic.Kind.ERROR, "incorrect diagnostic type");
    Assert.assertEquals(diag.getMessage(), expectedErrMsg, "incorrect error message:");
    Assert.assertEquals(diag.getPosition().getStartLine(), expectedErrLine, "incorrect line number:");
    Assert.assertEquals(diag.getPosition().getStartColumn(), expectedErrCol, "incorrect column position:");
}
Also used : Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic)

Example 5 with Diagnostic

use of org.ballerinalang.util.diagnostic.Diagnostic in project ballerina by ballerina-lang.

the class BAssertUtil method validateErrorMessageOnly.

/**
 * Validate if at least one in the given list of texts is contained in the error message.
 *
 * @param result          Result from compilation
 * @param errorIndex      Index of the error in the result
 * @param expectedPartsOfErrMsg  Array of expected parts of error message
 */
public static void validateErrorMessageOnly(CompileResult result, int errorIndex, String[] expectedPartsOfErrMsg) {
    Diagnostic diag = result.getDiagnostics()[errorIndex];
    Assert.assertEquals(diag.getKind(), Diagnostic.Kind.ERROR, "incorrect diagnostic type");
    boolean contains = false;
    for (String part : expectedPartsOfErrMsg) {
        if (diag.getMessage().contains(part)) {
            contains = true;
            break;
        }
    }
    Assert.assertTrue(contains, "None of given strings is contained in the error message '" + diag.getMessage() + '\'');
}
Also used : Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic)

Aggregations

Diagnostic (org.ballerinalang.util.diagnostic.Diagnostic)14 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)3 Gson (com.google.gson.Gson)2 JsonArray (com.google.gson.JsonArray)2 JsonElement (com.google.gson.JsonElement)2 JsonObject (com.google.gson.JsonObject)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 BallerinaFile (org.ballerinalang.composer.service.ballerina.parser.service.model.BallerinaFile)2 ProgramFile (org.ballerinalang.util.codegen.ProgramFile)2 Debugger (org.ballerinalang.util.debugger.Debugger)2 Compiler (org.wso2.ballerinalang.compiler.Compiler)2 BLangCompilationUnit (org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit)2 CompilerOptions (org.wso2.ballerinalang.compiler.util.CompilerOptions)2 LogicalPosition (com.intellij.openapi.editor.LogicalPosition)1 TextRange (com.intellij.openapi.util.TextRange)1 PsiElement (com.intellij.psi.PsiElement)1 PsiWhiteSpace (com.intellij.psi.PsiWhiteSpace)1 IOException (java.io.IOException)1 CompilerPlugin (org.ballerinalang.compiler.plugins.CompilerPlugin)1