use of org.ballerinalang.util.diagnostic.Diagnostic in project ballerina by ballerina-lang.
the class BTestRunner method runTest.
/**
* Executes a given set of ballerina program files.
*
* @param sourceRoot source root
* @param sourceFilePaths List of @{@link Path} of ballerina files
* @param groups List of groups to be included/excluded
* @param shouldIncludeGroups flag to specify whether to include or exclude provided groups
*/
public void runTest(String sourceRoot, Path[] sourceFilePaths, List<String> groups, boolean shouldIncludeGroups) {
outStream.println("---------------------------------------------------------------------------");
outStream.println(" T E S T S");
outStream.println("---------------------------------------------------------------------------");
TesterinaRegistry.getInstance().setGroups(groups);
TesterinaRegistry.getInstance().setShouldIncludeGroups(shouldIncludeGroups);
Arrays.stream(sourceFilePaths).forEach(sourcePackage -> {
// compile
CompileResult compileResult = BCompileUtil.compile(sourceRoot == null ? programDirPath.toString() : sourceRoot, sourcePackage.toString(), CompilerPhase.CODE_GEN);
// print errors
for (Diagnostic diagnostic : compileResult.getDiagnostics()) {
errStream.println(diagnostic.getKind() + ": " + diagnostic.getPosition() + " " + diagnostic.getMessage());
}
if (compileResult.getDiagnostics().length > 0) {
throw new BallerinaException("[ERROR] Compilation failed.");
}
// set the debugger
ProgramFile programFile = compileResult.getProgFile();
Debugger debugger = new Debugger(programFile);
programFile.setDebugger(debugger);
TesterinaRegistry.getInstance().addProgramFile(programFile);
// process the compiled files
ServiceLoader<CompilerPlugin> processorServiceLoader = ServiceLoader.load(CompilerPlugin.class);
processorServiceLoader.forEach(plugin -> {
if (plugin instanceof TestAnnotationProcessor) {
try {
((TestAnnotationProcessor) plugin).packageProcessed(programFile);
} catch (Exception e) {
errStream.println("[ERROR] Validation failed. Cause: " + e.getMessage());
throw new BallerinaException(e);
}
}
});
});
// execute the test programs
execute();
// print the report
tReport.printSummary();
}
use of org.ballerinalang.util.diagnostic.Diagnostic in project ballerina by ballerina-lang.
the class BTestUtils method invoke.
/**
* Compile and return the semantic errors.
*
* @param sourceRoot root path of the source packages
* @param packageName name of the package to compile
* @return Semantic errors
*/
// public static CompileResult compile(String sourceRoot, String packageName) {
// try {
// String effectiveSource;
// Path rootPath = Paths.get(BTestUtils.class.getProtectionDomain().getCodeSource()
// .getLocation().toURI().getPath().concat(sourceRoot));
// if (Files.isDirectory(Paths.get(packageName))) {
// String[] pkgParts = packageName.split("\\/");
// List<Name> pkgNameComps = Arrays.stream(pkgParts)
// .map(part -> {
// if (part.equals("")) {
// return Names.EMPTY;
// } else if (part.equals("_")) {
// return Names.EMPTY;
// }
// return new Name(part);
// })
// .collect(Collectors.toList());
// PackageID pkgId = new PackageID(pkgNameComps, Names.DEFAULT_VERSION);
// effectiveSource = pkgId.getName().getValue();
// } else {
// effectiveSource = packageName;
// }
// return compile(rootPath.toString(), effectiveSource, CompilerPhase.CODE_GEN);
// } catch (URISyntaxException e) {
// throw new IllegalArgumentException("error while running test: " + e.getMessage());
// }
// }
// /**
// * Compile and return the semantic errors.
// *
// * @param sourceFilePath Path to source package/file
// * @param compilerPhase Compiler phase
// * @return Semantic errors
// */
// public static CompileResult compile(String sourceFilePath, CompilerPhase compilerPhase) {
// Path sourcePath = Paths.get(sourceFilePath);
// String packageName = sourcePath.getFileName().toString();
// Path sourceRoot = resourceDir.resolve(sourcePath.getParent());
// return compile(sourceRoot.toString(), packageName, compilerPhase);
// }
//
// /**
// * Compile and return the semantic errors.
// *
// * @param sourceRoot root path of the source packages
// * @param packageName name of the package to compile
// * @param compilerPhase Compiler phase
// * @return Semantic errors
// */
// public static CompileResult compile(String sourceRoot, String packageName, CompilerPhase compilerPhase) {
// CompilerContext context = new CompilerContext();
// CompilerOptions options = CompilerOptions.getInstance(context);
// options.put(SOURCE_ROOT, resourceDir.resolve(sourceRoot).toString());
// options.put(COMPILER_PHASE, compilerPhase.toString());
// options.put(PRESERVE_WHITESPACE, "false");
//
// CompileResult comResult = new CompileResult();
//
// // catch errors
// DiagnosticListener listener = comResult::addDiagnostic;
// context.put(DiagnosticListener.class, listener);
//
// // compile
// Compiler compiler = Compiler.getInstance(context);
// compiler.compile(packageName);
// org.wso2.ballerinalang.programfile.ProgramFile programFile = compiler.getCompiledProgram();
// if (programFile != null) {
// comResult.setProgFile(LauncherUtils.getExecutableProgram(programFile));
// }
//
// return comResult;
// }
//
// /**
// * Compile and return the compiled package node.
// *
// * @param sourceFilePath Path to source package/file
// * @return compiled package node
// */
// public static BLangPackage compileAndGetPackage(String sourceFilePath) {
// Path sourcePath = Paths.get(sourceFilePath);
// String packageName = sourcePath.getFileName().toString();
// Path sourceRoot = resourceDir.resolve(sourcePath.getParent());
// CompilerContext context = new CompilerContext();
// CompilerOptions options = CompilerOptions.getInstance(context);
// options.put(SOURCE_ROOT, resourceDir.resolve(sourceRoot).toString());
// options.put(COMPILER_PHASE, CompilerPhase.CODE_GEN.toString());
// options.put(PRESERVE_WHITESPACE, "false");
//
// CompileResult comResult = new CompileResult();
//
// // catch errors
// DiagnosticListener listener = comResult::addDiagnostic;
// context.put(DiagnosticListener.class, listener);
//
// // compile
// Compiler compiler = Compiler.getInstance(context);
// compiler.compile(packageName);
// BLangPackage compiledPkg = (BLangPackage) compiler.getAST();
//
// return compiledPkg;
// }
/**
* Invoke a ballerina function.
*
* @param compileResult CompileResult instance
* @param packageName Name of the package to invoke
* @param functionName Name of the function to invoke
* @param args Input parameters for the function
* @return return values of the function
*/
public static BValue[] invoke(CompileResult compileResult, String packageName, String functionName, BValue[] args) {
if (compileResult.getErrorCount() > 0) {
String msg = "";
for (Diagnostic diagnostic : compileResult.getDiagnostics()) {
msg += diagnostic.getMessage() + "\n";
}
throw new IllegalStateException("compilation contains errors.. " + msg);
}
ProgramFile programFile = compileResult.getProgFile();
Debugger debugger = new Debugger(programFile);
programFile.setDebugger(debugger);
return BLangFunctions.invokeEntrypointCallable(programFile, packageName, functionName, args);
}
use of org.ballerinalang.util.diagnostic.Diagnostic in project ballerina by ballerina-lang.
the class BTestUtils method validateError.
/**
* Compile and run a ballerina file.
*
* @param sourceFilePath Path to the ballerina file.
*/
// public static void run(String sourceFilePath) {
// // TODO: improve. How to get the output
// CompileResult result = compile(sourceFilePath);
// ProgramFile programFile = result.getProgFile();
// Debugger debugger = new Debugger(programFile);
// programFile.setDebugger(debugger);
//
// // If there is no main or service entry point, throw an error
// if (!programFile.isMainEPAvailable() && !programFile.isServiceEPAvailable()) {
// throw new RuntimeException("main function not found in '" + programFile.getProgramFilePath() + "'");
// }
//
// if (programFile.isMainEPAvailable()) {
// LauncherUtils.runMain(programFile, new String[0]);
// } else {
// LauncherUtils.runServices(programFile);
// }
// }
/**
* 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.getMessage(), expectedErrMsg, "incorrect error message:");
Assert.assertEquals(diag.getPosition().getStartLine(), expectedErrLine, "incorrect line number:");
Assert.assertEquals(diag.getPosition().getStartColumn(), expectedErrCol, "incorrect column position:");
}
use of org.ballerinalang.util.diagnostic.Diagnostic 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;
}
Aggregations