/** * Visit each top-level node and add it to the package node. * * @param pkgNode current package node * @param compUnit current compilation unit */ private void populateCompilationUnit(BLangPackage pkgNode, BLangCompilationUnit compUnit) { compUnit.getTopLevelNodes().forEach(node -> addTopLevelNode(pkgNode, node)); }
@Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("'" + this.getName() + "' -> Top Level Elements:-\n"); this.getTopLevelNodes().stream().forEach(e -> builder.append("\t" + e + "\n")); return builder.toString(); }
public static CompilationUnitNode createCompilationUnit() { return new BLangCompilationUnit(); }
private String generateHash(BLangCompilationUnit compUnit, String basePath) { return compUnit.getPosition().getSource().pkgID.toString() + "$" + basePath + "$" + compUnit.getName(); }
/** * Get the TopLevel nodes of the current file. * * @param pkgNode Current Package node * @param ctx Service Operation context * @return {@link List} List of Top Level Nodes */ public static List<TopLevelNode> getCurrentFileTopLevelNodes(BLangPackage pkgNode, LSContext ctx) { String relativeFilePath = ctx.get(DocumentServiceKeys.RELATIVE_FILE_PATH_KEY); BLangCompilationUnit filteredCUnit = pkgNode.compUnits.stream() .filter(cUnit -> cUnit.getPosition().getSource().cUnitName.replace("/", FILE_SEPARATOR).equals(relativeFilePath)) .findAny().orElse(null); List<TopLevelNode> topLevelNodes = filteredCUnit == null ? new ArrayList<>() : new ArrayList<>(filteredCUnit.getTopLevelNodes()); // Filter out the lambda functions from the top level nodes return topLevelNodes.stream() .filter(topLevelNode -> !(topLevelNode instanceof BLangFunction && ((BLangFunction) topLevelNode).flagSet.contains(Flag.LAMBDA)) && !(topLevelNode instanceof BLangSimpleVariable && ((BLangSimpleVariable) topLevelNode).flagSet.contains(Flag.SERVICE))) .collect(Collectors.toList()); }
@Override public CompletableFuture<List<? extends SymbolInformation>> symbol(WorkspaceSymbolParams params) { List<SymbolInformation> symbols = new ArrayList<>(); LSServiceOperationContext symbolsContext = new LSServiceOperationContext(); Map<String, Object[]> compUnits = new HashMap<>(); this.workspaceDocumentManager.getAllFilePaths().forEach(path -> { symbolsContext.put(DocumentServiceKeys.SYMBOL_LIST_KEY, symbols); symbolsContext.put(DocumentServiceKeys.FILE_URI_KEY, path.toUri().toString()); List<BLangPackage> bLangPackage = lsCompiler.getBLangPackages(symbolsContext, workspaceDocumentManager, false, LSCustomErrorStrategy.class, true); if (bLangPackage != null) { bLangPackage.forEach(aPackage -> aPackage.compUnits.forEach(compUnit -> { String unitName = compUnit.getName(); String sourceRoot = LSCompilerUtil.getSourceRoot(path); String basePath = sourceRoot + File.separator + compUnit.getPosition().src.getPackageName(); String hash = generateHash(compUnit, basePath); compUnits.put(hash, new Object[]{ new File(basePath + File.separator + unitName).toURI(), compUnit}); })); } }); compUnits.values().forEach(compilationUnit -> { symbolsContext.put(DocumentServiceKeys.SYMBOL_LIST_KEY, symbols); symbolsContext.put(DocumentServiceKeys.FILE_URI_KEY, compilationUnit[0].toString()); symbolsContext.put(DocumentServiceKeys.SYMBOL_QUERY, params.getQuery()); SymbolFindingVisitor visitor = new SymbolFindingVisitor(symbolsContext); ((BLangCompilationUnit) compilationUnit[1]).accept(visitor); }); return CompletableFuture.completedFuture(symbols); }
private static JsonElement getJsonModel(String source) throws LSCompilerException, JSONGenerationException { BallerinaFile model = LSCompiler.compileContent(source, CompilerPhase.DEFINE); Optional<BLangCompilationUnit> compilationUnit = model.getBLangPackage() .map(b -> b.getCompilationUnits().stream().filter( compUnit -> LSCompilerUtil.UNTITLED_BAL.equals(compUnit.getName()) ).findFirst().orElse(null)); return TextDocumentFormatUtil.generateJSON(compilationUnit.orElse(null), new HashMap<>(), new HashMap<>()); }
private JsonElement getTreeForContent(LSContext context) throws LSCompilerException, JSONGenerationException { BLangPackage bLangPackage = context.get(DocumentServiceKeys.CURRENT_BLANG_PACKAGE_CONTEXT_KEY); CompilerContext compilerContext = context.get(DocumentServiceKeys.COMPILER_CONTEXT_KEY); SymbolFindVisitor symbolFindVisitor = new SymbolFindVisitor(compilerContext); if (bLangPackage.symbol != null) { symbolFindVisitor.visit(bLangPackage); Map<BLangNode, List<SymbolMetaInfo>> symbolMetaInfoMap = symbolFindVisitor.getVisibleSymbolsMap(); String relativeFilePath = context.get(DocumentServiceKeys.RELATIVE_FILE_PATH_KEY); BLangCompilationUnit compilationUnit = bLangPackage.getCompilationUnits().stream() .filter(cUnit -> cUnit.getPosition().getSource().cUnitName.replace("/", CommonUtil.FILE_SEPARATOR) .equals(relativeFilePath)) .findFirst() .orElse(null); JsonElement jsonAST = TextDocumentFormatUtil.generateJSON(compilationUnit, new HashMap<>(), symbolMetaInfoMap); FormattingSourceGen.build(jsonAST.getAsJsonObject(), "CompilationUnit"); return jsonAST; } return null; }
private CompilationUnitNode generateCompilationUnit(CompilerInput sourceEntry, PackageID packageID) { try { BDiagnosticSource diagnosticSrc = getDiagnosticSource(sourceEntry, packageID); 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 reading module: " + e.getMessage(), e); } }
@Override public void visit(BLangCompilationUnit compUnit) { compUnit.getTopLevelNodes().stream() .filter(CommonUtil.checkInvalidTypesDefs()) .forEach(node -> ((BLangNode) node).accept(this)); }
public AbstractTestTemplate(BLangPackage builtTestFile, BiConsumer<Integer, Integer> focusLineAcceptor) { this.focusLineAcceptor = focusLineAcceptor; this.builtTestFile = builtTestFile; this.imports = new ArrayList<>(); if (builtTestFile != null) { builtTestFile.testablePkgs.forEach(testablePkg -> testablePkg.getCompilationUnits().forEach( unit -> unit.getTopLevelNodes().forEach(node -> { //TODO: a dirty hack to retrieve imports of a test package, remove this when fixed if (node instanceof BLangImportPackage) { BLangImportPackage pkg = (BLangImportPackage) node; String orgName = pkg.orgName.value; String alias = pkg.alias.value; this.imports.add(new ImmutablePair<>(orgName, alias)); } }) )); } }
/** * Gets the alias for a given module from a bLang file root node. * * @param topCompilationUnit The root node. * @param packageName The module name. * @return The alias. */ private static String getAlias(BLangCompilationUnit topCompilationUnit, String packageName) { for (TopLevelNode topLevelNode : topCompilationUnit.getTopLevelNodes()) { if (topLevelNode instanceof BLangImportPackage) { BLangImportPackage importPackage = (BLangImportPackage) topLevelNode; String packagePath = importPackage.getPackageName().stream().map(BLangIdentifier::getValue).collect (Collectors.joining(".")); packagePath = importPackage.getOrgName().toString() + '/' + packagePath; if (packageName.equals(packagePath)) { return importPackage.getAlias().getValue(); } } } return null; } }
servicePkgs.addAll(compilationUnit.getTopLevelNodes().stream() .filter(topLevelNode -> topLevelNode instanceof ServiceNode) .collect(Collectors.toList()));
importPkgs.addAll(bLangCompilationUnit.getTopLevelNodes().stream() .filter(topLevelNode -> topLevelNode instanceof ImportPackageNode) .collect(Collectors.toList()));
private static Swagger getSwagger(Swagger swagger, SwaggerServiceMapper swaggerServiceMapper, String serviceName, BLangCompilationUnit topCompilationUnit, List<BLangSimpleVariable> endpoints) { for (TopLevelNode topLevelNode : topCompilationUnit.getTopLevelNodes()) { if (topLevelNode instanceof BLangSimpleVariable && ((BLangSimpleVariable) topLevelNode).getFlags().contains(Flag.LISTENER)) { endpoints.add((BLangSimpleVariable) topLevelNode); } if (topLevelNode instanceof BLangService) { BLangService serviceDefinition = (BLangService) topLevelNode; swagger = new SwaggerEndpointMapper() .convertBoundEndpointsToSwagger(endpoints, serviceDefinition, swagger); // Generate swagger string for the mentioned service name. if (StringUtils.isNotBlank(serviceName)) { if (serviceDefinition.getName().getValue().equals(serviceName)) { swagger = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition, swagger); break; } } else { // If no service name mentioned, then generate swagger definition for the first service. swagger = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition, swagger); break; } } } return swagger; }