use of org.wso2.ballerinalang.compiler.tree.BLangPackage 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;
}
use of org.wso2.ballerinalang.compiler.tree.BLangPackage in project ballerina by ballerina-lang.
the class CommandExecutor method executeAddAllDocumentation.
/**
* Generate workspace edit for generating doc comments for all top level nodes and resources.
* @param context Workspace Service Context
*/
private static void executeAddAllDocumentation(WorkspaceServiceContext context) {
String documentUri = "";
VersionedTextDocumentIdentifier textDocumentIdentifier = new VersionedTextDocumentIdentifier();
for (Object arg : context.get(ExecuteCommandKeys.COMMAND_ARGUMENTS_KEY)) {
if (((LinkedTreeMap) arg).get(ARG_KEY).equals(CommandConstants.ARG_KEY_DOC_URI)) {
documentUri = (String) ((LinkedTreeMap) arg).get(ARG_VALUE);
textDocumentIdentifier.setUri(documentUri);
context.put(DocumentServiceKeys.FILE_URI_KEY, documentUri);
}
}
BLangPackage bLangPackage = TextDocumentServiceUtil.getBLangPackage(context, context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY), false, LSCustomErrorStrategy.class, false).get(0);
String fileContent = context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY).getFileContent(Paths.get(URI.create(documentUri)));
String[] contentComponents = fileContent.split(System.lineSeparator());
List<TextEdit> textEdits = new ArrayList<>();
bLangPackage.topLevelNodes.forEach(topLevelNode -> {
CommandUtil.DocAttachmentInfo docAttachmentInfo = getDocumentEditForNode(topLevelNode);
if (docAttachmentInfo != null) {
textEdits.add(getTextEdit(docAttachmentInfo, contentComponents));
}
if (topLevelNode instanceof BLangService) {
((BLangService) topLevelNode).getResources().forEach(bLangResource -> {
CommandUtil.DocAttachmentInfo resourceInfo = getDocumentEditForNode(bLangResource);
if (resourceInfo != null) {
textEdits.add(getTextEdit(resourceInfo, contentComponents));
}
});
}
});
TextDocumentEdit textDocumentEdit = new TextDocumentEdit(textDocumentIdentifier, textEdits);
applyWorkspaceEdit(Collections.singletonList(textDocumentEdit), context.get(ExecuteCommandKeys.LANGUAGE_SERVER_KEY).getClient());
}
use of org.wso2.ballerinalang.compiler.tree.BLangPackage in project ballerina by ballerina-lang.
the class CommandUtil method getStructDocumentationByPosition.
/**
* Get the Documentation attachment for the struct definition.
* @param bLangPackage BLangPackage built
* @param line Start line of the struct in the source
* @return {@link String} Documentation attachment for the struct
*/
static DocAttachmentInfo getStructDocumentationByPosition(BLangPackage bLangPackage, int line) {
for (TopLevelNode topLevelNode : bLangPackage.topLevelNodes) {
if (topLevelNode instanceof BLangStruct) {
BLangStruct structNode = (BLangStruct) topLevelNode;
DiagnosticPos structPos = CommonUtil.toZeroBasedPosition(structNode.getPosition());
int structStart = structPos.getStartLine();
if (structStart == line) {
return getStructNodeDocumentation(structNode, line);
}
}
}
return null;
}
use of org.wso2.ballerinalang.compiler.tree.BLangPackage in project ballerina by ballerina-lang.
the class CommandUtil method getServiceDocumentationByPosition.
/**
* Get the Documentation attachment for the service.
* @param bLangPackage BLangPackage built
* @param line Start line of the service in the source
* @return {@link String} Documentation attachment for the service
*/
static DocAttachmentInfo getServiceDocumentationByPosition(BLangPackage bLangPackage, int line) {
// TODO: Currently resource position is invalid and we use the annotation attachment positions.
for (TopLevelNode topLevelNode : bLangPackage.topLevelNodes) {
if (topLevelNode instanceof BLangService) {
BLangService serviceNode = (BLangService) topLevelNode;
DiagnosticPos servicePos = CommonUtil.toZeroBasedPosition(serviceNode.getPosition());
List<BLangAnnotationAttachment> annotationAttachments = serviceNode.getAnnotationAttachments();
if (!annotationAttachments.isEmpty()) {
DiagnosticPos lastAttachmentPos = CommonUtil.toZeroBasedPosition(annotationAttachments.get(annotationAttachments.size() - 1).getPosition());
if (lastAttachmentPos.getEndLine() < line && line < servicePos.getEndLine()) {
return getServiceNodeDocumentation(serviceNode, lastAttachmentPos.getEndLine() + 1);
}
} else if (servicePos.getStartLine() == line) {
return getServiceNodeDocumentation(serviceNode, line);
}
}
}
return null;
}
use of org.wso2.ballerinalang.compiler.tree.BLangPackage 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;
}
Aggregations