Skip to content

KtPsiFactory

class KtPsiFactory

A factory for creating Kotlin PSI elements programmatically, usually by parsing a snippet of source text.

Most methods follow a createX(text) shape: they build a throwaway KtFile containing the given text and return the requested element from it. Unless noted otherwise, the text must be a syntactically valid form of the requested element, and the method throws if it cannot be produced; ...IfPossible variants return null instead.

The created elements are detached from any real file and are not meant to be analyzed, unless the factory is created with a context via contextual.

Parameters

  • markGenerated: This needs to be set to true if the KtPsiFactory is going to be used for creating elements that are going to be inserted in the user source code (this ensures that the elements will be formatted correctly). In other cases, markGenerated should be false, which saves time and memory.

Constructors

KtPsiFactory

@JvmOverloads
constructor(project: Project, markGenerated: Boolean = true)
constructor(
    project: Project, 
    markGenerated: Boolean = true, 
    eventSystemEnabled: Boolean
)

Types

CallableBuilder

A fluent builder for a function, constructor, or read-only property declaration string. The available steps and their order depend on the Target; call asString to obtain the resulting text, then pass it to the matching create* method.

ClassHeaderBuilder

A fluent builder for a class header string, assembled in a fixed order: modifiers, name, type parameters, base class, and type constraints. Call asString to obtain the resulting header text, then pass it to createClass to build the PSI.

Companion

object Companion

Functions

buildDeclaration

Builds a declaration using a BuilderByPattern configured by build.

buildDestructuringDeclaration

buildExpression

Builds an expression using a BuilderByPattern configured by build.

buildValueArgumentList

Builds a value argument list using a BuilderByPattern configured by build.

creareDelegatedSuperTypeEntry

Creates a constructor delegation call from the given text (for example, "super(1)" or "this()").

createAnnotationEntry

Creates an annotation entry from the given text (for example, "@Suppress(\"x\")").

createAnonymousInitializer

Creates an empty init block.

createArgument

fun createArgument(
    expression: KtExpression?, 
    name: Name? = null, 
    isSpread: Boolean = false, 
    reformat: Boolean = true
): KtValueArgument

Creates a value argument wrapping the given expression, optionally named (name) and/or spread (isSpread).

Parameters

  • reformat: whether to reformat the created argument
fun createArgument(@NonNls text: String): KtValueArgument

Creates a value argument from the given text (for example, "x = 1" or "*array").

createBlock

fun createBlock(@NonNls bodyText: String): KtBlockExpression

Creates a function body block wrapping the given bodyText.

createBlockCodeFragment

fun createBlockCodeFragment(@NonNls text: String, context: PsiElement?): KtBlockCodeFragment

Creates a KtBlockCodeFragment for the given text, resolved in the given context.

createBlockStringTemplateEntry

Creates a block string-template entry (${...}) wrapping the given expression.

createCallableReferenceExpression

Creates an expression from text and returns it if it is a callable reference, or null if it is another kind of expression. Failure to parse an expression is handled as described by createExpression.

createCallArguments

Creates a value argument list from the given parenthesized text (for example, "(1, x = 2)").

createClass

fun createClass(@NonNls text: String): KtClass

Creates a class or interface declaration from the given text.

createClassKeyword

fun createClassKeyword(): PsiElement

Creates a class keyword token.

createColon

fun createColon(): PsiElement

Creates a colon (:) token.

createComma

fun createComma(): PsiElement

Creates a comma token.

createComment

fun createComment(@NonNls text: String): PsiComment

Creates a comment (line or block) from the given text; the text must be a single comment.

createCompanionBlock

Creates an empty companion block.

Creates a companion block from the given text (for example, "companion { ... }"). The text must contain exactly one complete companion block and no other class-body elements.

createCompanionObject

Creates an empty companion object.

Creates a companion object from the given text (for example, "companion object { ... }").

createConstructorKeyword

fun createConstructorKeyword(): PsiElement

Creates a constructor keyword token.

createDeclaration

Creates a top-level declaration from the given text, cast to the expected type TDeclaration. The text must contain exactly one declaration.

createDeclarationByPattern

fun <TDeclaration : KtDeclaration> KtPsiFactory.createDeclarationByPattern(
    @NonNls pattern: String, 
    @NonNls vararg args: Any, 
    reformat: Boolean = true
): TDeclaration

Creates a declaration from the given pattern with placeholders substituted by args. See createByPattern.

createDestructuringDeclaration

Creates a destructuring declaration from the given text (for example, "val (x, y) = pair").

createDestructuringDeclarationByPattern

fun KtPsiFactory.createDestructuringDeclarationByPattern(
    @NonNls pattern: String, 
    @NonNls vararg args: Any, 
    reformat: Boolean = true
): KtDestructuringDeclaration

Creates a destructuring declaration from the given pattern with placeholders substituted by args. See createByPattern.

createDestructuringParameter

Creates a destructuring lambda parameter from the given text (for example, "(x, y)").

createDot

fun createDot(): PsiElement

Creates a dot (.) token.

createEmptyBody

Creates an empty function body block ({}).

createEmptyClassBody

Creates an empty class body ({}).

createEmptyModifierList

Creates an empty modifier list.

createEnumEntry

fun createEnumEntry(@NonNls text: String): KtEnumEntry

Creates an enum entry from the given text (for example, "RED" or "RED(0xFF0000)").

createEnumEntryInitializerList

Creates an enum entry initializer list holding a single set of constructor arguments.

createEQ

fun createEQ(): PsiElement

Creates an equals (=) token.

createExpression

fun createExpression(@NonNls text: String): KtExpression

Creates an expression from the given text. Throws if no expression can be parsed. When JVM assertions are enabled, also fails if the parsed expression's text does not match text exactly; use createExpressionIfPossible for unconditional validation and a null result on failure.

createExpressionByPattern

fun KtPsiFactory.createExpressionByPattern(
    @NonNls pattern: String, 
    @NonNls vararg args: Any, 
    reformat: Boolean = true
): KtExpression

Creates an expression from the given pattern with $0, $1, … placeholders substituted by args. See createByPattern.

createExpressionCodeFragment

fun createExpressionCodeFragment(@NonNls text: String, context: PsiElement?): KtExpressionCodeFragment

Creates a KtExpressionCodeFragment for the given text, resolved in the given context.

createExpressionIfPossible

Creates an expression from the given text, or returns null if the text cannot be parsed as a single expression whose text matches text exactly.

createFile

fun createFile(@NonNls text: String): KtFile

Creates a KtFile with the given text and a dummy file name.

fun createFile(@NonNls fileName: String, @NonNls text: String): KtFile

Creates a KtFile with the given fileName and text. If this factory has a context, the file is marked analyzable in that context; otherwise it is marked as do-not-analyze.

createFileAnnotation

fun createFileAnnotation(@NonNls annotationText: String): KtAnnotationEntry

Creates a file-level annotation entry from the given annotationText (without the @file: prefix).

createFileAnnotationListWithAnnotation

Creates a file annotation list containing a single @file: annotation from the given annotationText.

createFunction

fun createFunction(@NonNls funDecl: String): KtNamedFunction

Creates a named function from the given declaration text funDecl.

createFunctionTypeParameter

Creates a function-type parameter whose type is the given typeReference.

createFunctionTypeReceiver

Creates a function-type receiver (the T. in T.() -> R) wrapping the given typeReference.

createIdentifier

fun createIdentifier(@NonNls name: String): PsiElement

Creates a bare identifier token for the given name.

createIf

fun createIf(
    condition: KtExpression, 
    thenExpr: KtExpression, 
    elseExpr: KtExpression? = null
): KtIfExpression

Creates an if expression with the given condition, thenExpr, and optional elseExpr.

createImportDirective

fun createImportDirective(importPath: ImportPath): KtImportDirective

Creates an import directive for the given importPath (including its all-under flag and alias).

Throws

IllegalArgumentException

if the import path is empty (the root package)

createLabeledExpression

Creates a labeled expression from a label labelName such as "loop"; the resulting expression is loop@ 1.

createLambdaExpression

fun createLambdaExpression(@NonNls parameters: String, @NonNls body: String): KtLambdaExpression

Creates a lambda expression with the given parameters and body text.

createLambdaParameterList

Creates the parameter list of a lambda with the given parameter text.

createLambdaParameterListIfAny

Creates the parameter list of a lambda with the given parameter text, or null if the lambda declares none.

createLiteralStringTemplateEntry

Creates a literal (plain text) string-template entry for the given literal text.

createLoopParameter

fun createLoopParameter(@NonNls text: String): KtParameter

Creates a for-loop parameter from the given text.

createModifier

fun createModifier(modifier: KtModifierKeywordToken): PsiElement

Creates a single modifier keyword token.

createModifierList

Creates a modifier list containing the single given modifier keyword.

Creates a modifier list from the given text (a space-separated sequence of modifiers).

createMultiDollarBlockStringTemplateEntry

Creates a block string-template entry (${...}) wrapping the given expression, for a string template whose interpolation prefix is prefixLength dollar signs (for example, $${...} when prefixLength is 2).

Throws

IllegalStateException

if prefixLength is not positive

createMultiDollarSimpleNameStringTemplateEntry

Creates a simple-name string-template entry ($name) for the given name, for a string template whose interpolation prefix is prefixLength dollar signs (for example, $$name when prefixLength is 2).

Throws

IllegalStateException

if prefixLength is not positive

createMultiDollarStringTemplate

fun createMultiDollarStringTemplate(
    @NonNls content: String, 
    prefixLength: Int, 
    forceMultiQuoted: Boolean = false
): KtStringTemplateExpression

Creates a string template with the given content whose interpolation prefix is prefixLength dollar signs. A raw (triple-quoted) template is used when content spans multiple lines or forceMultiQuoted is true, and a regular (double-quoted) one otherwise.

Throws

IllegalStateException

if prefixLength is not positive

createNameIdentifier

fun createNameIdentifier(@NonNls name: String): PsiElement

Creates a name identifier token for the given name. Throws if name is not a valid identifier.

createNameIdentifierIfPossible

fun createNameIdentifierIfPossible(@NonNls name: String): PsiElement?

Creates a name identifier token for the given name, or returns null if name is not a valid identifier.

createNewLine

fun createNewLine(): PsiElement

Creates a whitespace element containing a single line break.

fun createNewLine(lineBreaks: Int): PsiElement

Creates a whitespace element containing lineBreaks line breaks.

createObject

fun createObject(@NonNls text: String): KtObjectDeclaration

Creates an object declaration from the given text.

createOperationName

Creates an operation-reference expression for the given operator name (for example, "+").

createPackageDirective

Creates a package directive for the given fqName.

createPackageDirectiveIfNeeded

Creates a package directive for the given fqName, or returns null for the root package.

createParameter

fun createParameter(@NonNls text: String): KtParameter

Creates a value parameter from the given text (for example, "x: Int = 0").

createParameterList

Creates a parameter list from the given parenthesized text (for example, "(x: Int, y: Int)").

createPhysicalFile

fun createPhysicalFile(@NonNls fileName: String, @NonNls text: String): KtFile

Creates a physical (event-system-enabled) KtFile with the given fileName and text. Unlike createFile, the resulting file participates in the PSI event system and supports light classes.

createPrimaryConstructor

Creates a primary constructor from the given text (for example, "constructor(x: Int)"), defaulting to an empty one.

createPrimaryConstructorWithModifiers

Creates an empty primary constructor carrying the given modifiers.

createProperty

fun createProperty(
    @NonNls modifiers: String?, 
    @NonNls name: String, 
    @NonNls type: String?, 
    isVar: Boolean, 
    @NonNls initializer: String?
): KtProperty

Creates a property from its parts: optional modifiers, name, optional type, mutability (isVar), and optional initializer.

fun createProperty(
    @NonNls name: String, 
    @NonNls type: String?, 
    isVar: Boolean, 
    @NonNls initializer: String?
): KtProperty

Creates a property from its parts, without modifiers.

fun createProperty(
    @NonNls name: String, 
    @NonNls type: String?, 
    isVar: Boolean
): KtProperty

Creates a property with the given name and optional type and no initializer.

fun createProperty(@NonNls text: String): KtProperty

Creates a property from the given full declaration text (for example, "val x: Int = 1").

createPropertyDelegate

Creates a property delegate (by ...) whose delegate expression is the given expression.

createPropertyGetter

Creates a property getter whose body is the given expression (a block or a single expression).

createPropertySetter

Creates a property setter whose body is the given expression (a block or a single expression).

createRawStringTemplate

Creates a raw (triple-quoted) string template with the given content.

createReplSnippet

fun createReplSnippet(@NonNls text: String): KtScript

Creates a REPL snippet KtScript from the specified text content.

createSecondaryConstructor

Creates a secondary constructor from the given declaration text decl.

createSemicolon

fun createSemicolon(): PsiElement

Creates a semicolon token.

createSimpleName

Creates a simple name reference expression for the given name.

createSimpleNameStringTemplateEntry

Creates a simple-name string-template entry ($name) for the given name.

createSingleStatementBlock

fun createSingleStatementBlock(
    statement: KtExpression, 
    @NonNls prevComment: String? = null, 
    @NonNls nextComment: String? = null
): KtBlockExpression

Creates a block containing the single given statement, optionally preceded by prevComment and followed by nextComment.

createStar

fun createStar(): PsiElement

Creates a * (star projection) token.

createStringTemplate

Creates a regular (double-quoted) string template with the given content.

createSuperTypeCallEntry

Creates a superclass constructor call entry from the given text (for example, "Base(1)").

createSuperTypeEntry

Creates a plain supertype entry from the given text (for example, an interface name "Runnable").

createThisExpression

Creates a this expression.

fun createThisExpression(@NonNls qualifier: String): KtThisExpression

Creates a labeled this expression (this@qualifier).

createType

fun createType(@NonNls type: String): KtTypeReference

Creates a type reference from the given type text. Throws if the text cannot be parsed as a type whose text matches type exactly; use createTypeIfPossible to get null instead.

Creates a type reference wrapping the given typeElement.

createTypeAlias

fun createTypeAlias(
    @NonNls name: String, 
    typeParameters: List<String>, 
    typeElement: KtTypeElement
): KtTypeAlias

Creates a type alias with the given name and typeParameters, aliasing the given typeElement.

fun createTypeAlias(
    @NonNls name: String, 
    typeParameters: List<String>, 
    @NonNls body: String
): KtTypeAlias

Creates a type alias with the given name and typeParameters, aliasing the type in body.

createTypeArgument

Creates a single type argument (projection) from the given text.

createTypeArguments

Creates a type argument list from the given angle-bracketed text (for example, "<Int, String>").

createTypeCodeFragment

fun createTypeCodeFragment(@NonNls text: String, context: PsiElement?): KtTypeCodeFragment

Creates a KtTypeCodeFragment for the given text, resolved in the given context.

createTypeIfPossible

Creates a type reference from the given type text, or returns null if it cannot be parsed as such.

createTypeParameter

Creates a single type parameter from the given text (for example, "T : Comparable<T>").

createTypeParameterList

Creates a type parameter list from the given angle-bracketed text (for example, "<T, R>").

createValKeyword

fun createValKeyword(): PsiElement

Creates a val keyword token.

createValueArgumentListByPattern

fun KtPsiFactory.createValueArgumentListByPattern(
    @NonNls pattern: String, 
    @NonNls vararg args: Any, 
    reformat: Boolean = true
): KtValueArgumentList

Creates a value argument list from the given pattern with placeholders substituted by args. See createByPattern.

createVarKeyword

fun createVarKeyword(): PsiElement

Creates a var keyword token.

createWhenCondition

fun createWhenCondition(@NonNls conditionText: String): KtWhenCondition

Creates a when condition from the given conditionText (for example, "in 1..10" or "is String").

createWhenEntry

fun createWhenEntry(@NonNls entryText: String): KtWhenEntry

Creates a when entry from the given entryText (for example, "1 -> \"one\""). Throws if the produced entry's text does not match entryText.

createWhiteSpace

fun createWhiteSpace(): PsiElement

Creates a single-space whitespace element.

fun createWhiteSpace(@NonNls text: String): PsiElement

Creates a whitespace element with the exact given text.

createWhitespaceAndArrow

fun createWhitespaceAndArrow(): Pair<PsiElement, PsiElement>

Creates a whitespace-then-arrow pair; the returned pair holds the first and last elements of that range.

wrapInABlockWrapper

Wraps the given expression in a synthetic single-statement block. If expression is already a block, it is returned unchanged. Intended for internal compiler use.