cretz / kastree

Simple Kotlin Source AST and Syntax Parsing, Editing, and Writing
MIT License
236 stars 52 forks source link

add ScriptInitializer #26

Closed NikkyAI closed 1 month ago

NikkyAI commented 5 years ago

also add the default gradle wrapper

this is something tht came out of trying to kastree with kotlin-scripting the KtFIle can be gotten during the evaluation of scripts and passed to the following function to convert:

   open fun convertScript(v: KtFile): Node.Script {
        val ktScript = v.declarations.firstIsInstanceOrNull<KtScript>()!!
        return Node.Script(
            anns = convertAnnotationSets(v),
            pkg = v.packageDirective?.takeIf { it.packageNames.isNotEmpty() }?.let(::convertPackage),
            imports = v.importDirectives.map(::convertImport),
            exprs = ktScript.blockExpression.statements.map(::convertExpr)
        ).map(v)
    }

i noticed later that kastree does not keep offset data andas such its useless for highlighting code, i still hope this might be useful

impatient commented 5 years ago

@NikkyAI When you say offset are you talking about being able to determine line/column? Does this help? https://github.com/cretz/kastree/issues/16

You could also change the WithExtras to add a way to get the PSI element, which looks to have the data n the text range.

open class WithPSILookup : Converter.WithExtras() {

    val nodeToPsiMap = mutableMapOf<Node, PsiElement>()

    operator fun get(n:Node) : PsiElement? = nodeToPsiMap[n]

    override fun onNode(node: Node, elem: PsiElement) {
        nodeToPsiMap[node] = elem
        super.onNode(node, elem)
    }

}

With the above you should be able to do:

extrasMap[node]?.textRange or you might want textRangeInParent

cretz commented 5 years ago

@NikkyAI - Thanks! Will look when I can, not using this (or Kotlin) much lately. Also have been avoiding committing gradle wrapper a bit.

@impatient - I suggest an identity map there (well, maybe not, but hash code calc at many levels deep may be expensive), but another option is each Node has a tag field that you can set w/ offset or PSI info or whatever.