### YAML AST Alternative Pattern Example Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md Demonstrates the use of alternative patterns in YAML for AST matching, allowing for any of the specified rules to be matched. Includes an example of how to specify optional alternatives. ```yaml alternatives: # Match any of these patterns - rule: classMethod - rule: functionDeclaration optional: true # Entire alternative is optional ``` -------------------------------- ### Basic Kotlin Code Parsing with Code-to-Knowledge-Graph Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/README.md This Java example demonstrates the basic usage of the Code-to-Knowledge-Graph library. It shows how to create a parser using a factory method, parse a project directory, and then print the number of nodes and connections in the generated graph. ```java import software.bevel.code_to_knowledge_graph.FactoriesKt; String projectPath = "/path/to/your/project"; Parser parser = FactoriesKt.createVsCodeParser(projectPath); Graphlike graph = parser.parse(List.of(projectPath)); System.out.println("Nodes: " + graph.getNodes().size()); System.out.println("Connections: " + graph.getConnections().getAllConnections().size()); ``` -------------------------------- ### YAML AST Node Pattern Example Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md Illustrates a specific node pattern in YAML for matching AST elements like function declarations. It shows how to define rules, captures, optionality, and child alternatives. ```yaml rule: functionDeclaration # Matches specific AST node type captures: # Optional List of names to reference matched rules - funcNode # Reference this node as "funcNode" optional: true # Optional property, that specifies if matching this rule and its children is optional notchildren: # Set of rules types that must NOT be present children: # Required child patterns - rule: identifier captures: - funcName - alternatives: - rule: classMethod - rule: functionDeclaration ``` -------------------------------- ### MinHash for Code Similarity Detection (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This example demonstrates how to use MinHash to detect similarity between code snippets. It involves creating a MinHasher, hashing multiple code strings, and then calculating the Jaccard similarity between the resulting hashes. ```kotlin import software.bevel.code_to_knowledge_graph.providers.MinHasher val hasher = MinHasher() val code1 = """ fun processUser(user: User) { val name = user.name val email = user.email return UserDto(name, email) } """.trimIndent() val code2 = """ fun processCustomer(customer: Customer) { val name = customer.name val email = customer.email return CustomerDto(name, email) } """.trimIndent() val code3 = """ fun calculateTotal(items: List): Double { return items.sumOf { it.price } } """.trimIndent() val hash1 = hasher.hash(code1) val hash2 = hasher.hash(code2) val hash3 = hasher.hash(code3) val similarity12 = hasher.similarity(hash1, hash2) val similarity13 = hasher.similarity(hash1, hash3) println("Similarity between code1 and code2: $${(similarity12 * 100).toInt()}% \nSimilarity between code1 and code3: $${(similarity13 * 100).toInt()}% ") ``` -------------------------------- ### Define Predicates for Conditional Matching in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This YAML snippet defines predicates used to enforce conditions for a match to be valid. It shows examples of checking if a capture exists ('exists' predicate) and verifying if the values of two captures are equal ('equals' predicate). ```yaml predicates: - function: exists # Check if capture exists capture: "@returnType" - function: equals # Check if values of captures are equal capture1: "@type1" capture2: "@type2" ``` -------------------------------- ### Create VS Code Parser and Parse Entire Project (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This snippet demonstrates how to create a VS Code parser instance for a given project path and then use it to parse the entire project. The result is a graph structure containing nodes and connections representing code entities and their relationships. It requires the 'code_to_knowledge_graph' and 'graph_domain' libraries. ```kotlin import software.bevel.code_to_knowledge_graph.createVsCodeParser import software.bevel.graph_domain.graph.Graphlike val projectPath = "/path/to/your/project" val parser = createVsCodeParser(projectPath) // Parse the entire project val graph: Graphlike = parser.parse(listOf(projectPath)) println("Nodes: ${graph.nodes.size}") println("Connections: ${graph.connections.getAllConnections().size}") // Access parsed entities graph.nodes.values.forEach { println("${it.nodeType}: ${it.id} in ${it.filePath}") } ``` -------------------------------- ### Gitignore-Aware File Walking (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This snippet shows how to traverse project files while respecting ignore patterns defined in .gitignore and .bevelignore files. It utilizes GitignoreAwareFileWalker and CachedIoFileHandler for efficient and aware file system traversal. ```kotlin import software.bevel.code_to_knowledge_graph.providers.GitignoreAwareFileWalker import software.bevel.code_to_knowledge_graph.providers.CachedIoFileHandler import software.bevel.code_to_knowledge_graph.vscode.languageSpecs.GeneralLanguageSpecification val fileHandler = CachedIoFileHandler() val languageSpec = GeneralLanguageSpecification(fileHandler, nodeBuilder, tokenizer) val fileWalker = GitignoreAwareFileWalker(languageSpec, fileHandler) // Walk directory respecting .gitignore and .bevelignore val projectPath = "/path/to/project" val files = fileWalker.walk(projectPath) println("Found $${files.size} parseable files:") files.take(10).forEach { file -> println(" - $file") } ``` -------------------------------- ### Argument Connection Equivalent using Base Converters Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This YAML snippet demonstrates the equivalent configuration of the 'argument-connection' macro converter using base 'connection' converter. It explicitly defines the source and target nodes, connection type, and predicates. ```yaml # This macro: # function: argument-connection # callerCapture: "@methodCall" # argumentCapture: "@argument" # positionAstRule: "@methodCall" # Is equivalent to: function: connection fromNode: "@methodCall.splitDotAndGetLast" toNode: "@argument" connectionType: CALLED_WITH positionAstRule: "@methodCall" predicates: - function: exists capture: "@methodCall" ``` -------------------------------- ### Node With Parent Converter: Create Node and Connect to Parent Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This macro converter creates a new node and automatically establishes a connection to its parent node, typically a DEFINES connection. It simplifies node creation by handling both node definition and its relationship to a parent in a single step. ```yaml function: node-with-parent nodeName: "@childNode" # Name for the new node nodeType: FUNCTION # Type of the node (NodeType enum) parent: "@parentNode" # Optional, defaults to "@parentNode.node" representingAndPositionAstRule: "@nodeForPosition" # Optional, AST node for position ``` -------------------------------- ### Argument Connection Converter: Connect Arguments and Callers Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This macro converter automatically creates connections for function arguments and their callers, specifically a CALLED_WITH connection. It simplifies the process by automatically determining the 'from' node and adding an existence predicate for the caller capture. ```yaml function: argument-connection callerCapture: "@methodCall" # The node calling the method argumentCapture: "@argument" # The argument being passed positionAstRule: "@methodCall" # Optional, AST node for position info ``` -------------------------------- ### Node With Parent Equivalent using Base Converters Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This YAML snippet shows how the 'node-with-parent' macro converter can be replicated using a combination of 'node' and 'connection' base converters. It explicitly defines the creation of the child node and the subsequent connection to its parent. ```yaml # This macro: # function: node-with-parent # nodeName: "@childNode" # nodeType: FUNCTION # parent: "@parentNode" # representingAndPositionAstRule: "@nodeForPosition" # Is equivalent to: - function: node nodeName: "@childNode" nodeType: FUNCTION representingParseTreeNode: "@nodeForPosition" - function: connection fromNode: "@parentNode" toNode: "@childNode" connectionType: DEFINES positionAstRule: "@nodeForPosition" ``` -------------------------------- ### Capture Basic Type Parameters in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern captures basic type parameters, focusing on their identifier (name) and optional type bounds. It's foundational for representing generic types and constraints. ```yaml # Basic type parameter type: typeParameter children: - type: identifier # Parameter name - type: typeBound # Optional bounds optional: true ``` -------------------------------- ### Capture Import Declarations in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern describes how to match import declarations and extract the import path and any optional alias. It handles specific imports and provides a foundation for managing wildcard imports separately. ```yaml type: importDeclaration children: - type: identifier # Import path - type: alias # Optional alias optional: true ``` -------------------------------- ### Parse Specific Files and Build Graph Incrementally (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This code demonstrates parsing specific files within a project and building a graph incrementally. It utilizes a VS Code parser to process a list of file paths, returning a GraphBuilder that can be used to construct the graph. The snippet also shows how to filter nodes by type, such as identifying all classes. ```kotlin import software.bevel.code_to_knowledge_graph.createVsCodeParser import software.bevel.graph_domain.graph.builder.GraphBuilder val parser = createVsCodeParser("/path/to/project") // Parse specific files val files = listOf( "/path/to/project/src/Main.kt", "/path/to/project/src/Utils.kt" ) val graphBuilder: GraphBuilder = parser.parseFiles(files) val graph = graphBuilder.build() // Filter nodes by type val classes = graph.nodes.values.filter { it.nodeType == NodeType.Class } classes.forEach { println("Class: ${it.simpleName} at ${it.filePath}:${it.nameLocation.start.line}") } ``` -------------------------------- ### File Handling with Caching in Kotlin Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt Demonstrates efficient file reading operations with an integrated caching mechanism using CachedIoFileHandler. Supports reading entire files, specific ranges, lines, and checking file existence. This is useful for performance-critical applications dealing with frequent file access. ```kotlin import software.bevel.code_to_knowledge_graph.providers.CachedIoFileHandler import software.bevel.file_system_domain.LCRange import software.bevel.file_system_domain.LCPosition val fileHandler = CachedIoFileHandler() // Read entire file (cached) val content = fileHandler.readString("/path/to/file.kt") // Read specific range from file val range = LCRange( start = LCPosition(line = 10, column = 0), end = LCPosition(line = 20, column = 50) ) val snippet = fileHandler.readString("/path/to/file.kt", range) // Read lines val lines = fileHandler.readLines("/path/to/file.kt") println("File has ${lines.size} lines") // Check file existence if (fileHandler.exists("/path/to/config.properties")) { val config = fileHandler.readString("/path/to/config.properties") } ``` -------------------------------- ### Capture Package Declarations in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern defines how to match package declarations and extract the package path. It's used for organizing code into a hierarchical structure within the knowledge graph. ```yaml type: packageDeclaration children: - type: identifier # Package path ``` -------------------------------- ### Create Connection Parser and Analyze Relationships (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This code demonstrates how to create a connection parser to analyze relationships between code entities using LSP capabilities. It shows how to find inbound connections (e.g., who calls a function) and outbound connections (e.g., what a function calls or inherits from). Requires the 'code_to_knowledge_graph' and 'graph_domain' libraries. ```kotlin import software.bevel.code_to_knowledge_graph.createVsCodeConnectionParser import software.bevel.code_to_knowledge_graph.createVsCodeParser import software.bevel.graph_domain.graph.ConnectionType val projectPath = "/path/to/project" val parser = createVsCodeParser(projectPath) val graph = parser.parse(listOf(projectPath)) val connectionParser = createVsCodeConnectionParser(projectPath) // Find inbound connections (who calls this node?) val targetNode = graph.nodes.values.first { it.simpleName == "myFunction" } val inboundConnections = connectionParser.createInboundConnectionsForNodes(targetNode.id, graph = graph) inboundConnections.forEach { println("${it.sourceNodeName} -> ${it.targetNodeName} (${it.connectionType})") } // Find outbound connections (what does this node call?) val sourceNode = graph.nodes.values.first { it.nodeType == NodeType.Class } val outboundConnections = connectionParser.createOutboundConnectionsForNodes(sourceNode.id, graph = graph) outboundConnections.forEach { when (it.connectionType) { ConnectionType.INHERITS_FROM -> println("${it.sourceNodeName} inherits from ${it.targetNodeName}") ConnectionType.USES -> println("${it.sourceNodeName} uses ${it.targetNodeName}") else -> println("${it.sourceNodeName} -> ${it.targetNodeName}") } } ``` -------------------------------- ### YAML AST Query Pattern Definition Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md Defines the structure for matching Abstract Syntax Tree (AST) patterns in YAML queries. It includes rules, captures, child patterns, and predicates for generating knowledge graph elements. ```yaml patterns: - pattern: # A single pattern to match in the AST rule: string # The AST rule to match captures: # List of names to reference matched rules - captureName children: # Child patterns that must be present in this exact order - rule: string captures: - childCaptureName optional: boolean # Whether this child pattern is optional notChildren: # Set of rules types that must NOT be present - excludedType predicates: # Conditions that must be satisfied - function: exists/equals/... capture: captureName converters: # Actions to generate graph elements - function: node/connection/import # Converter-specific parameters ``` -------------------------------- ### Graph Merging for Multiple Code Sources in Kotlin Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt Demonstrates how to merge knowledge graphs from different parsing strategies or projects. This is useful for combining analyses of main projects with libraries or modules, providing a unified view of code relationships. It uses GraphMergingServiceImpl for combining node descriptions and connections. ```kotlin import software.bevel.code_to_knowledge_graph.providers.GraphMergingServiceImpl import software.bevel.code_to_knowledge_graph.providers.MinHasher import software.bevel.code_to_knowledge_graph.providers.CachedIoFileHandler val mergeService = GraphMergingServiceImpl(MinHasher(), CachedIoFileHandler()) // Parse main project val mainParser = createVsCodeParser("/path/to/main-project") val mainGraph = mainParser.parse(listOf("/path/to/main-project")) // Parse library val libParser = createVsCodeParser("/path/to/library") val libGraph = libParser.parse(listOf("/path/to/library")) // Merge graphs val mergedGraph = mergeService.mergeNodeDescriptionsAndConnectionsFromOtherIntoCurrentGraph( otherGraph = libGraph, currentGraph = mainGraph, projectPath = "/path/to/main-project" ) println("Merged graph contains ${mergedGraph.nodes.size} nodes") println("Total connections: ${mergedGraph.connections.getAllConnections().size}") ``` -------------------------------- ### Referencing Captures and Properties in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This YAML snippet illustrates how to reference defined captures and access their properties using dot notation. It shows concatenation of capture values and mixing literals with captures, along with optional capture referencing using the '?' suffix. ```yaml nodeName: "@parentNode.node + '.' + @funcName" # Example with optional capture: optionalValue: "@returnType?" ``` -------------------------------- ### Capture Property Declarations in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern illustrates how to capture property declarations, including their names, optional types, and optional initial values. It's designed to handle properties within different scopes, such as class-level or local variables. ```yaml type: propertyDeclaration children: - type: identifier # Property name - type: type # Property type (optional) optional: true - type: initializer # Initial value (optional) optional: true ``` -------------------------------- ### Finding Parent-Child Relationships in Code Hierarchy (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This snippet illustrates how to navigate the hierarchy of code definitions. It shows how to find all members (methods, properties) belonging to a specific class and how to determine the parent package of a class. ```kotlin import software.bevel.graph_domain.graph.NodeType import software.bevel.graph_domain.graph.FullyQualifiedNodeBuilder // Find all members of a class val myClass = graph.nodes.values.first { it.simpleName == "MyClass" && it.nodeType == NodeType.Class } val classMembers = graph.nodes.values.filter { if (it is FullyQualifiedNodeBuilder) { it.definingNodeName == myClass.id } else false } println("Class ${myClass.simpleName} contains:") classMembers.forEach { member -> println(" - ${member.nodeType}: ${member.simpleName}") } // Find the parent package of a class if (myClass is FullyQualifiedNodeBuilder) { val parentPackage = graph.nodes[myClass.definingNodeName] println("${myClass.simpleName} is defined in ${parentPackage?.id}") } ``` -------------------------------- ### Gradle Dependency for Code-to-Knowledge-Graph Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/README.md This snippet shows how to add the Code-to-Knowledge-Graph library as a dependency in a Gradle project. It specifies the library group, artifact ID, and version for implementation. ```kotlin dependencies { implementation("software.bevel:code-to-knowledge-graph:1.1.3") } ``` -------------------------------- ### Capture Annotations and Decorators in AST Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern matches annotation or decorator nodes, capturing their names and optional arguments. This allows for representing metadata associated with code elements. ```yaml type: annotation children: - type: identifier # Annotation name - type: argumentList # Annotation parameters optional: true ``` -------------------------------- ### Analyzing Code Relationships: Dependencies and Callers (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This code demonstrates how to analyze relationships between code entities. It shows how to find all classes a specific class depends on (USES connection) and how to identify all functions that call a target function. ```kotlin import software.bevel.graph_domain.graph.ConnectionType import software.bevel.graph_domain.graph.NodeType // Find all classes a specific class depends on val targetClass = graph.nodes.values.first { it.simpleName == "UserService" } val dependencies = graph.connections.getAllConnections().filter { it.sourceNodeName == targetClass.id && it.connectionType == ConnectionType.USES } dependencies.forEach { dep -> val dependsOn = graph.nodes[dep.targetNodeName] println("${targetClass.simpleName} uses ${dependsOn?.simpleName} at line ${dep.location.start.line}") } // Find all callers of a function val targetFunction = graph.nodes.values.first { it.simpleName == "processData" && it.nodeType == NodeType.Function } val callers = graph.connections.getAllConnections().filter { it.targetNodeName == targetFunction.id && it.connectionType == ConnectionType.USES } println("Function ${targetFunction.simpleName} is called by:") callers.forEach { val callingNode = graph.nodes[it.sourceNodeName] println(" - ${callingNode?.simpleName} at ${it.filePath}:${it.location.start.line}") } ``` -------------------------------- ### Node Converter: Create Graph Nodes from AST Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md The Node Converter creates nodes in the knowledge graph from matched AST patterns. It allows specifying the node name, type, and optionally linking it to a specific parse tree node. Predicates can be used to define optional conditions for node creation. ```yaml function: node nodeName: "@parentNode.node + '.' + @funcName" # Fully qualified name nodeType: FUNCTION # Must match NodeType enum representingParseTreeNode: "@capturedNode" # Optional, save the node as related to specific AST node, stead of @currentNode, which matches to the root node that is matched by the pattern predicates: # Optional conditions - function: exists capture: "@someCapture" ``` -------------------------------- ### Accessing Node Builder Properties via Captures in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This YAML snippet demonstrates accessing properties of node builder objects using capture references. It specifically shows how to retrieve the 'name' property of a node, and also illustrates mixing string literals with capture values for concatenation. ```yaml "@capture.node" = "@capture.node.name" # Get node's name "@class.node + '.' + @method.label + \"1234\"" # Concatenate values "'prefix.' + @capture.node" # Mix literals and captures ``` -------------------------------- ### Import Converter: Track Imports and Dependencies Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md The Import Converter is used to track import statements and module dependencies within the code. It captures alias and path information, which can vary between programming languages. Optional predicates can be applied. ```yaml function: import importData: # Map of import data, can differ from programming language to programming language alias: "@aliasCapture" # Example data: Import alias path: "@pathCapture" # Example data: Import path predicates: # Optional conditions - function: exists capture: "@someCapture" ``` -------------------------------- ### Custom Language Specification for VS Code Parsers in Kotlin Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt Illustrates how to extend language support by defining custom language specifications. This allows for tailored parsing rules, default package names, and specific file ending checks, enhancing flexibility for diverse programming languages. It leverages GeneralLanguageSpecification and RegexIdentifierTokenizer. ```kotlin import software.bevel.code_to_knowledge_graph.vscode.languageSpecs.GeneralLanguageSpecification import software.bevel.code_to_knowledge_graph.providers.MinHasher import software.bevel.code_to_knowledge_graph.vscode.data.VsCodeNodeBuilder val fileHandler = CachedIoFileHandler() val minHasher = MinHasher() val nodeBuilder = VsCodeNodeBuilder(fileHandler, minHasher) val tokenizer = RegexIdentifierTokenizer() val customLangSpec = GeneralLanguageSpecification( fileHandler, nodeBuilder, tokenizer, allowedFileEndings = setOf("kt", "java", "py") ) // Override default package name val kotlinSpec = object : GeneralLanguageSpecification(fileHandler, nodeBuilder, tokenizer) { override val defaultPackageName = "kotlin.root" override fun checkFileEndings(fileName: String): Boolean { return fileName.endsWith(".kt") } } val parser = createVsCodeParser( projectPath, languageSpecification = kotlinSpec ) ``` -------------------------------- ### Create Graph Updater for Incremental Updates (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This snippet shows how to create a graph updater for handling incremental updates to a codebase without re-parsing the entire project. It demonstrates initial parsing, re-parsing modified files, adding new files, and deleting files, updating the graph accordingly. This is useful for real-time analysis. ```kotlin import software.bevel.code_to_knowledge_graph.createVsCodeGraphUpdater import software.bevel.graph_domain.graph.Graph val projectPath = "/path/to/project" val updater = createVsCodeGraphUpdater(projectPath) // Initial parse val initialGraph = updater.parser.parse(listOf(projectPath)) // File was modified val modifiedFiles = listOf("/path/to/project/src/Modified.kt") val updatedGraph = updater.reparseFiles(modifiedFiles, initialGraph) // File was added val newFiles = listOf("/path/to/project/src/NewFile.kt") val graphWithNewFiles = updater.addFiles(newFiles, updatedGraph) // File was deleted val deletedFiles = listOf("/path/to/project/src/OldFile.kt") val finalGraph = updater.deleteFiles(deletedFiles, graphWithNewFiles) println("Updated graph has ${finalGraph.nodes.size} nodes") ``` -------------------------------- ### Connection Converter: Create Edges Between Graph Nodes Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md The Connection Converter establishes edges between nodes in the knowledge graph. It defines the source and target nodes, the type of connection, and optionally fallback types if nodes are not found. An AST rule can be specified for saving the position of the code. ```yaml function: connection fromNode: "@source" # Source node name fromFallbackType: CLASS # Optional, fallback type if node not found toNode: "@target" # Target node name toFallbackType: FUNCTION # Optional, fallback type if node not found connectionType: DEFINES # Must match ConnectionType enum positionAstRule: "@nodeForPosition" # AST node for saving position where code starts and ends predicates: # Optional conditions - function: exists capture: "@someCapture" ``` -------------------------------- ### Querying Graph Nodes by Type and Name (Kotlin) Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt This snippet shows how to query nodes within a parsed code graph. It demonstrates filtering nodes by type (e.g., Function, Class) and by their simple name. It also illustrates how to retrieve inheritance relationships between classes. ```kotlin import software.bevel.graph_domain.graph.NodeType import software.bevel.graph_domain.graph.ConnectionType val graph = parser.parse(listOf(projectPath)) // Find all functions in a specific file val functionsInFile = graph.nodes.values.filter { it.nodeType == NodeType.Function && it.filePath == "src/Main.kt" } // Find nodes by simple name val nodesByName = graph.nodes.values.filter { it.simpleName == "MyClass" } // Find classes that inherit from others val inheritanceConnections = graph.connections.getAllConnections().filter { it.connectionType == ConnectionType.INHERITS_FROM } inheritanceConnections.forEach { conn -> val child = graph.nodes[conn.sourceNodeName] val parent = graph.nodes[conn.targetNodeName] println("${child?.simpleName} extends ${parent?.simpleName}") } ``` -------------------------------- ### Custom Communication Interface for VS Code Integration in Kotlin Source: https://context7.com/bevel-software/code-to-knowledge-graph/llms.txt Shows how to integrate the code-to-knowledge-graph toolkit with custom VS Code extensions or servers. It establishes a communication channel using RestCommunicationInterfaceCreator and JavaNetReactorMonoWebClient, enabling the parser to interact with external services on a specified port. ```kotlin import software.bevel.file_system_domain.web.LocalCommunicationInterface import software.bevel.networking.RestCommunicationInterfaceCreator import software.bevel.networking.web_client.JavaNetReactorMonoWebClient // Create custom communication channel val port = "3000" val commsChannel = RestCommunicationInterfaceCreator( JavaNetReactorMonoWebClient(), port ).create() val parser = createVsCodeParser( projectPath = "/path/to/project", commsChannel = commsChannel ) // Parser will communicate with VS Code extension on port 3000 val graph = parser.parse(listOf("/path/to/project")) ``` -------------------------------- ### Capture Function Declarations in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern defines how to match and extract information about function declarations. It focuses on identifying the function's name, parameters, return type, and receiver type for methods defined outside their parent class. ```yaml type: functionDeclaration children: - type: identifier # Function name - type: parameters # Parameter list - type: returnType # Return type ``` -------------------------------- ### Capture Type Constraints in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern captures specific type constraints, linking a constraint type to the type parameter it applies to. This is crucial for defining the boundaries and requirements of generic types. ```yaml # Type constraints type: typeConstraints children: - type: typeConstraint children: - type: type # Constraint type - type: identifier # Type parameter ``` -------------------------------- ### Capture Function Overloading Signatures in AST Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern identifies function declarations, capturing their names, parameter lists, and optional return types. This is used to distinguish between overloaded functions in a knowledge graph. ```yaml type: functionDeclaration children: - type: identifier # Function name - type: parameterList # Parameter types for disambiguation - type: returnType optional: true ``` -------------------------------- ### Define Named Captures in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This YAML snippet demonstrates how to define named captures for AST nodes within a rule. Captures allow referencing specific nodes for later use in predicates and converters. If no captures are specified, the node's rule or type is used as the default capture name. ```yaml rule: functionDeclaration captures: - funcNode # Reference this node as "@funcNode" ``` -------------------------------- ### Accessing Parse Tree Node Properties via Captures in YAML Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/queries.md This YAML snippet shows how to access properties of parse tree nodes using capture references. It covers retrieving the node's label (source code), rule/type name, and a hash code for unique identification, particularly useful for anonymous nodes like lambdas. ```yaml "@capture" = "@capture.label" # Get node's label = source code it represents "@capture.rule" # Get node's rule/type name "@capture.hashCode" # Get node code's hash code ``` -------------------------------- ### Capture Class Inheritance in AST Source: https://github.com/bevel-software/code-to-knowledge-graph/blob/main/docs/programming_constructs.md This pattern captures class declarations and their inheritance clauses, identifying base classes or interfaces. It's crucial for building type hierarchies in a knowledge graph. ```yaml type: classDeclaration children: - type: identifier # Class name - type: inheritanceClause children: - type: supertype # Base class/interface ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.