### Generate GPG Key (Bash) Source: https://github.com/strumenta/starlasu-kotlin/blob/main/README.md This command installs GnuPG and generates a new GPG key, which is necessary for signing releases. It guides the user through the key generation process and exports the secret key for use with Gradle. ```bash brew install gnupg gpg --gen-key gpg --keyring secring.gpg --export-secret-keys > ~/.gnupg/secring.gpg ``` -------------------------------- ### Debug AST Visualization with Starlasu Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Demonstrates the basic usage of debugPrint() for visualizing AST structures in Starlasu Kotlin. It shows how to print the AST directly and provides an example of the expected output format, including nested declarations and parameters. ```kotlin import com.strumenta.starlasu.model.* // Simple debug print println(ast.debugPrint()) // Output: // CompilationUnit { // declarations = [ // FunctionDeclaration { // name = greet // parameters = [ // Parameter { // name = name // type = [ // TypeReference { // typeName = String // } // ] // } // ] // ... ``` -------------------------------- ### Define AST Node Classes in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Demonstrates how to define custom AST node classes by extending the `Node` class and defining properties as constructor parameters. Properties are automatically discovered via reflection. Includes an example of creating an AST programmatically and assigning parent references. ```kotlin import com.strumenta.starlasu.model.* // Define AST node classes by extending Node data class CompilationUnit( val declarations: MutableList = mutableListOf() ) : Node() sealed class Declaration : Node() data class FunctionDeclaration( override val name: String, val parameters: MutableList = mutableListOf(), val body: Block? = null ) : Declaration(), Named data class Parameter( override val name: String, val type: TypeReference ) : Node(), Named data class TypeReference( val typeName: String ) : Node() data class Block( val statements: MutableList = mutableListOf() ) : Node() sealed class Statement : Node() data class ReturnStatement( val expression: Expression? = null ) : Statement() sealed class Expression : Node() data class IntLiteral(val value: Int) : Expression() data class StringLiteral(val value: String) : Expression() data class Identifier(override val name: String) : Expression(), Named // Create AST programmatically val ast = CompilationUnit( declarations = mutableListOf( FunctionDeclaration( name = "greet", parameters = mutableListOf( Parameter("name", TypeReference("String")) ), body = Block( statements = mutableListOf( ReturnStatement(StringLiteral("Hello")) ) ) ) ) ) // Assign parent references throughout the tree ast.assignParents() // Access node properties println(ast.nodeType) // "com.example.CompilationUnit" println(ast.properties.map { it.name }) // ["declarations"] ``` -------------------------------- ### Parse Tree to AST Transformation with ParseTreeToASTTransformer in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Explains the use of ParseTreeToASTTransformer, a specialization of ASTTransformer for converting ANTLR parse trees to ASTs. It automatically handles source position tracking and allows for registering rules for ANTLR parse tree contexts. Includes examples for unwrapping child rules. ```kotlin import com.strumenta.starlasu.mapping.* import com.strumenta.starlasu.transformation.* import org.antlr.v4.runtime.ParserRuleContext // Assuming ANTLR-generated parser classes // class MyLangParser : Parser { ... } // class ExpressionContext : ParserRuleContext { ... } val ptToAstTransformer = ParseTreeToASTTransformer() // Register rules for parse tree contexts // ptToAstTransformer.registerRule(MyLangParser.ExpressionContext::class) { ctx -> // when { // ctx.PLUS() != null -> BinaryOp( // "+", // ptToAstTransformer.transform(ctx.left) as TargetExpr, // ptToAstTransformer.transform(ctx.right) as TargetExpr // ) // ctx.NUMBER() != null -> NumberLiteral(ctx.NUMBER().text.toInt()) // else -> null // } // } // For wrapper rules that just delegate to a single child // ptToAstTransformer.registerRuleUnwrappingChild(MyLangParser.PrimaryContext::class) // Transform with context val context = TransformationContext() // val ast = ptToAstTransformer.transform(parseTree, context) // Position is automatically assigned from parse tree // println(ast?.position) // Position from source code ``` -------------------------------- ### Publish Release with Gradle (Bash) Source: https://github.com/strumenta/starlasu-kotlin/blob/main/README.md This command initiates the release process using Gradle. It automates the steps involved in versioning, building, and publishing a new release of the Starlasu Kotlin library to Maven Central. ```bash ./gradlew release ``` -------------------------------- ### Track Source Code Positions with Starlasu in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Demonstrates how to use Starlasu's `Point` and `Position` classes to track source code locations. It covers creating points, positions, associating them with sources, extracting text at a position, and performing containment checks. Utility functions for position creation and point arithmetic are also shown. ```kotlin import com.strumenta.starlasu.model.* // Create points (1-based lines, 0-based columns) val start = Point(1, 0) // Line 1, Column 0 val end = Point(1, 10) // Line 1, Column 10 // Create a position val pos = Position(start, end) println(pos.start.line) // 1 println(pos.end.column) // 10 // Utility function for creating positions val quickPos = pos(1, 0, 3, 15) // startLine, startCol, endLine, endCol // Associate position with source val fileSource = FileSource(java.io.File("example.txt")) val posWithSource = Position(start, end, fileSource) // Extract text at position from source code val code = "function greet(name) { return 'Hello' }" val textAtPos = pos(1, 0, 1, 8).text(code) // "function" // Create node with position val node = IntLiteral(42).withPosition(pos(1, 0, 1, 2)) println(node.position) // Position(start=Line 1, Column 0, end=Line 1, Column 2) // Check containment val outerPos = pos(1, 0, 10, 50) val innerPos = pos(2, 5, 3, 10) println(outerPos.contains(innerPos)) // true println(outerPos.overlaps(innerPos)) // true // Point arithmetic val point = Point(1, 5) val newPoint = point + 10 // Point(1, 15) val afterText = point + "hello\nworld" // Point(2, 5) - advances through text // Line position helper val linePos = linePosition(5, "var x = 10") // Full line 5 position ``` -------------------------------- ### Format Code with ktlint (Bash) Source: https://github.com/strumenta/starlasu-kotlin/blob/main/README.md This command uses Gradle to format your Kotlin code according to the ktlint standard. This ensures consistent code style across the project, improving readability and maintainability. ```bash ./gradlew ktlintFormat ``` -------------------------------- ### Code Generation with PrinterOutput in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Demonstrates how to use the PrinterOutput class for managing indentation, printing lists with custom separators, and handling conditional printing within AST code generation. ```kotlin import com.strumenta.starlasu.codegen.* // PrinterOutput is used within ASTCodeGenerator class AdvancedGenerator : ASTCodeGenerator() { override fun registerRecordPrinters() { recordPrinter { ast -> // Print with prefix/postfix print(ast.name, prefix = "def ", postfix = "(") // Print list with custom separator printList(ast.parameters, separator = ", ") { param -> print(param) } print(")") // Print list with prefix/postfix printList("(", ast.parameters, ")", printEvenIfEmpty = true) // Conditional printing printFlag(ast.body != null, " ") // Indentation control println(" {") indent() ast.body?.statements?.forEach { print(it); println() } dedent() println("}") // Ensure space before next token ensureSpace() // Print one of multiple alternatives // printOneOf(ast.shortForm, ast.longForm) } recordPrinter { ast -> // Associate generated position with AST node associate(ast) { print(ast.name) print(": ") print(ast.type.typeName) } // ast.destination now contains the position in generated code } } } ``` -------------------------------- ### Configure Sonatype Credentials (Gradle Properties) Source: https://github.com/strumenta/starlasu-kotlin/blob/main/README.md This snippet shows how to configure Sonatype credentials in the `gradle.properties` file. These credentials are required for publishing releases to Maven Central, allowing the build system to authenticate with the repository. ```properties ossrhTokenUsername=your_username ossrhTokenPassword=your_password ``` -------------------------------- ### Configuring Starlasu Kotlin Debug Printing Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Illustrates how to customize the output of debugPrint() in Starlasu Kotlin using DebugPrintConfiguration. This includes options to skip empty collections, skip null values, force showing positions, set indentation, and hide specific properties like 'origin'. ```kotlin val config = DebugPrintConfiguration( skipEmptyCollections = true, skipNull = true, forceShowPosition = true, indentBlock = " " ) config.hide.add("origin") // Hide specific properties println(ast.debugPrint(configuration = config)) ``` -------------------------------- ### Validation and Issue Reporting in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Shows how to create and use the `Issue` class in Starlasu for reporting lexical, syntactic, semantic, and translation errors with severity and position information. ```kotlin import com.strumenta.starlasu.validation.* import com.strumenta.starlasu.model.* // Create issues of different types val lexicalError = Issue.lexical( message = "Invalid character '@'", severity = IssueSeverity.ERROR, position = pos(1, 5, 1, 6) ) val syntaxError = Issue.syntactic( message = "Expected ';' at end of statement", severity = IssueSeverity.ERROR, position = pos(3, 20, 3, 20) ) val semanticWarning = Issue.semantic( message = "Variable 'x' is never used", severity = IssueSeverity.WARNING, position = pos(2, 4, 2, 5) ) val translationInfo = Issue.translation( message = "Converted deprecated syntax", severity = IssueSeverity.INFO ) // Check issue severity println(lexicalError.severity == IssueSeverity.ERROR) // true println(semanticWarning.type == IssueType.SEMANTIC) // true // ParsingResult contains issues // val result = parser.parse(code) // val hasErrors = result.issues.any { it.severity == IssueSeverity.ERROR } // val errorMessages = result.issues.filter { it.severity == IssueSeverity.ERROR } // .map { "${it.position}: ${it.message}" } ``` -------------------------------- ### AST Traversal and Navigation in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Illustrates various AST traversal and navigation methods provided by Starlasu. This includes depth-first, post-order, ancestor traversal, collecting nodes by type, and accessing siblings. Requires `assignParents()` to be called for ancestor-based navigation. ```kotlin import com.strumenta.starlasu.traversing.* import com.strumenta.starlasu.model.* // Depth-first traversal of entire tree ast.walk().forEach { node -> println("Visiting: ${node.simpleNodeType}") } // Post-order (leaves-first) traversal ast.walkLeavesFirst().forEach { node -> println("Leaves-first: ${node.simpleNodeType}") } // Get all descendants (excluding self) val allDescendants = ast.walkDescendants().toList() // Find all nodes of a specific type val allFunctions = ast.collectByType(FunctionDeclaration::class.java) val allExpressions = ast.searchByType(Expression::class.java).toList() // Walk only direct children ast.walkChildren().forEach { child -> println("Direct child: ${child.simpleNodeType}") } // Get children with their containment names ast.walkChildrenByContainment().forEach { (name, child) -> println("$name -> ${child.simpleNodeType}") } // Navigate to ancestors (requires assignParents() called first) val someNode: ASTNode = allFunctions.first().parameters.first() someNode.walkAncestors().forEach { ancestor -> println("Ancestor: ${ancestor.simpleNodeType}") } // Find nearest ancestor of specific type val containingFunction = someNode.findAncestorOfType(FunctionDeclaration::class.java) // Access siblings val nextSib = someNode.nextSibling val prevSib = someNode.previousSibling // FastWalker for repeated traversals (caches children) val fastWalker = FastWalker(ast) repeat(100) { fastWalker.walk().count() // Faster on subsequent iterations } ``` -------------------------------- ### Add Starlasu Kotlin Dependency (Gradle) Source: https://github.com/strumenta/starlasu-kotlin/blob/main/README.md This snippet shows how to add the Starlasu Kotlin core library as a dependency to your Gradle project. It specifies the artifact ID and version, ensuring that the necessary components for AST manipulation are available. ```gradle dependencies { implementation "com.strumenta.starlasu:starlasu-core:1.7.x" } ``` -------------------------------- ### Resolve Symbolic References with Starlasu in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Illustrates Starlasu's `ReferenceByName` for handling symbolic references to named nodes. It shows how to create unresolved and resolved references, resolve them from a list of candidates (with case-insensitivity option), and use them within an Abstract Syntax Tree (AST). ```kotlin import com.strumenta.starlasu.model.* // Define named nodes data class VariableDeclaration( override val name: String, val initialValue: Expression? = null ) : Statement(), Named data class VariableReference( val ref: ReferenceByName ) : Expression() // Create unresolved reference val varRef = ReferenceByName("myVar") println(varRef.resolved) // false println(varRef.toString()) // "Ref(myVar)[Unsolved]" // Create resolved reference val varDecl = VariableDeclaration("myVar", IntLiteral(10)) val resolvedRef = ReferenceByName("myVar", varDecl) println(resolvedRef.resolved) // true println(resolvedRef.referred) // VariableDeclaration instance // Resolve reference from candidates val candidates = listOf( VariableDeclaration("foo"), VariableDeclaration("myVar"), VariableDeclaration("bar") ) val unresolvedRef = ReferenceByName("myVar") val success = unresolvedRef.tryToResolve(candidates) println(success) // true println(unresolvedRef.referred?.name) // "myVar" // Case-insensitive resolution val caseRef = ReferenceByName("MYVAR") caseRef.tryToResolve(candidates, caseInsensitive = true) println(caseRef.resolved) // true // Use in AST data class AssignmentStatement( val target: ReferenceByName, val value: Expression ) : Statement() val assignment = AssignmentStatement( target = ReferenceByName("counter"), value = IntLiteral(0) ) ``` -------------------------------- ### AST Node Processing and Modification in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Illustrates Starlasu utilities for processing AST nodes, including in-place modification, transforming children, replacing nodes, and managing list insertions/removals. ```kotlin import com.strumenta.starlasu.model.* // Process all nodes with an operation ast.processNodes { node -> println("Processing: ${node.simpleNodeType}") } // Process nodes of specific type ast.processNodesOfType(Expression::class.java) { expr -> println("Found expression: $expr") } // Process node properties ast.processProperties { prop -> println("Property: ${prop.name} = ${prop.value}") } // Transform children in place ast.transformChildren { child -> when (child) { is IntLiteral -> IntLiteral(child.value * 2) else -> child } } // Replace a node with another val oldNode = (ast.declarations[0] as FunctionDeclaration) val newNode = FunctionDeclaration("newFunction", mutableListOf(), null) oldNode.replaceWith(newNode) // Replace with multiple nodes (in MutableList) val statements = (ast.declarations[0] as FunctionDeclaration).body?.statements statements?.get(0)?.replaceWithSeveral(listOf( ReturnStatement(IntLiteral(1)), ReturnStatement(IntLiteral(2)) )) // Insert nodes before/after val targetStatement = statements?.get(0) targetStatement?.addSeveralBefore(listOf(ReturnStatement(IntLiteral(0)))) targetStatement?.addSeveralAfter(listOf(ReturnStatement(IntLiteral(99)))) // Remove node from list statements?.get(0)?.removeFromList() // Find containing property val containingProp = someNode.containingProperty() val indexInParent = someNode.indexInContainingProperty() ``` -------------------------------- ### AST Transformation with ASTTransformer in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Demonstrates how to use ASTTransformer for tree-to-tree transformations. It involves defining source and target AST nodes, registering transformation rules for each node type, and optionally configuring child transformations and finalizers. Supports fault-tolerant transformations with different modes. ```kotlin import com.strumenta.starlasu.transformation.* import com.strumenta.starlasu.model.* // Source AST nodes (e.g., from a simpler representation) data class SimpleExpr(val op: String, val left: Any?, val right: Any?) : Node() data class SimpleNum(val value: Int) : Node() // Target AST nodes sealed class TargetExpr : Node() data class BinaryOp(val operator: String, var left: TargetExpr?, var right: TargetExpr?) : TargetExpr() data class NumberLiteral(val value: Int) : TargetExpr() // Create transformer val transformer = ASTTransformer() // Register transformation rules transformer.registerRule(SimpleNum::class) { source -> NumberLiteral(source.value) } transformer.registerRule(SimpleExpr::class) { source, context, tf -> BinaryOp( operator = source.op, left = tf.transform(source.left, context) as? TargetExpr, right = tf.transform(source.right, context) as? TargetExpr ) } // Transform AST val sourceAst = SimpleExpr( "+", SimpleNum(1), SimpleExpr("*", SimpleNum(2), SimpleNum(3)) ) val targetAst = transformer.transform(sourceAst) as BinaryOp println(targetAst.operator) // "+" println((targetAst.left as NumberLiteral).value) // 1 // Configure child transformations transformer.registerRule(SimpleExpr::class, BinaryOp::class) .withChild(BinaryOp::left) { (it as? SimpleExpr)?.left ?: it } .withChild(BinaryOp::right) { (it as? SimpleExpr)?.right ?: it } .withFinalizer { node -> node.assignParents() } // Fault-tolerant transformation val strictTransformer = ASTTransformer(faultTolerance = FaultTolerance.STRICT) val looseTransformer = ASTTransformer(faultTolerance = FaultTolerance.LOOSE) ``` -------------------------------- ### Manage Scopes with Starlasu in Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Explains Starlasu's `Scope` class for hierarchical symbol tables. It demonstrates creating scope hierarchies, defining and resolving symbols within scopes (including type-aware lookup and handling nested scopes), and using case-insensitive scopes. A DSL-style scope creation is also presented. ```kotlin import com.strumenta.starlasu.semantics.* import com.strumenta.starlasu.model.* // Create a scope hierarchy val globalScope = Scope() val functionScope = Scope(parent = globalScope) val blockScope = Scope(parent = functionScope) // Define symbols in scopes globalScope.define(VariableDeclaration("globalVar")) functionScope.define(Parameter("param1", TypeReference("Int"))) blockScope.define(VariableDeclaration("localVar")) // Resolve symbols - searches up the scope chain val found = blockScope.resolve("globalVar") println(found?.name) // "globalVar" // Resolve with type filter val paramOnly = blockScope.resolve("param1", Parameter::class) println(paramOnly?.name) // "param1" // Symbol not found returns null val notFound = blockScope.resolve("nonExistent") println(notFound) // null // Case-insensitive scope val caseInsensitiveScope = Scope(ignoreCase = true) caseInsensitiveScope.define(VariableDeclaration("MyVariable")) val resolved = caseInsensitiveScope.resolve("myvariable") println(resolved?.name) // "MyVariable" // DSL-style scope creation val myScope = scope(ignoreCase = false) { define(VariableDeclaration("x")) define(VariableDeclaration("y")) parent = globalScope } ``` -------------------------------- ### Integrate ANTLR Parser with Starlasu Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Extend StarlasuParser to integrate ANTLR lexing, parsing, and AST transformation. This involves providing implementations for creating ANTLR lexer and parser instances, and configuring the AST transformer with rules for mapping parse tree contexts to AST nodes. It supports parsing from strings or files and provides access to parsing results and timing information. ```kotlin import com.strumenta.starlasu.parsing.* import com.strumenta.starlasu.transformation.* import org.antlr.v4.runtime.* // Example parser implementation (requires ANTLR grammar) /* abstract class MyLanguageParser : StarlasuParser< CompilationUnit, // Root AST type MyLangParser, // ANTLR parser type MyLangParser.FileContext, // Root parse tree type StarlasuANTLRToken // Token type >(ANTLRTokenFactory()) { override fun createANTLRLexer(charStream: CharStream): Lexer { return MyLangLexer(charStream) } override fun createANTLRParser(tokenStream: TokenStream): MyLangParser { return MyLangParser(tokenStream) } override fun setupASTTransformer(): ASTTransformer { return ParseTreeToASTTransformer().apply { registerRule(MyLangParser.FileContext::class) { ctx -> CompilationUnit( declarations = ctx.declaration().map { transform(it) as Declaration }.toMutableList() ) } // ... more rules } } } */ // Using the parser // val parser = MyLanguageParser() // Parse from string // val result: ParsingResult = parser.parse("function foo() {}") // println(result.isCorrect) // true if no errors // println(result.issues) // List of parsing issues // println(result.root) // The AST root node // Parse from file // val fileResult = parser.parse(File("source.mylang")) // Access timing information // println(result.time) // Total parsing time in ms // println(result.firstStage?.lexingTime) // Lexing time // First stage only (parse tree without AST) // val parseTreeResult = parser.parseFirstStage("source code") // println(parseTreeResult.root) // ParserRuleContext ``` -------------------------------- ### Generate Code from AST with Starlasu Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Utilize ASTCodeGenerator to transform Abstract Syntax Trees (ASTs) back into source code. This involves defining specific NodePrinter functions for each AST node type to control how they are represented in the output. The generated code can be printed to the console or written to a file. ```kotlin import com.strumenta.starlasu.codegen.* import com.strumenta.starlasu.model.Node import java.io.File class MyCodeGenerator : ASTCodeGenerator() { override fun registerRecordPrinters() { recordPrinter { ast -> ast.declarations.forEach { decl -> print(decl) println() } } recordPrinter { ast -> print("function ") print(ast.name) print("(") printList(ast.parameters, ", ") print(") ") print(ast.body) } recordPrinter { ast -> print(ast.name) print(": ") print(ast.type.typeName) } recordPrinter { ast -> println("{") indent() ast.statements.forEach { stmt -> print(stmt) println() } dedent() print("}") } recordPrinter { ast -> print("return") ast.expression?.let { print(" ") print(it) } print(";") } recordPrinter { ast -> print(ast.value) } recordPrinter { ast -> print("\"${ast.value}\"") } } } // Generate code val generator = MyCodeGenerator() val generatedCode = generator.printToString(ast) println(generatedCode) // Output: // function greet(name: String) { // return "Hello"; // } // Write to file generator.printToFile(ast, File("output.txt")) ``` -------------------------------- ### Debug Printing Parsing Results in Starlasu Kotlin Source: https://context7.com/strumenta/starlasu-kotlin/llms.txt Shows how to apply debug printing to the result of a parsing operation in Starlasu Kotlin. This snippet assumes a 'parser' object that has a 'parse' method, and it prints the debug representation of the parsing result. ```kotlin // Debug print parsing result // val result = parser.parse(code) // println(result.debugPrint()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.