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
KtPsiFactoryis 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,markGeneratedshould be false, which saves time and memory.
Constructors¶
KtPsiFactory¶
@JvmOverloads
constructor(project: Project, markGenerated: Boolean = true)
Types¶
CallableBuilder¶
class CallableBuilder(target: KtPsiFactory.CallableBuilder.Target)
ClassHeaderBuilder¶
class 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¶
fun KtPsiFactory.buildDeclaration(build: BuilderByPattern<KtDeclaration>.() -> Unit): KtDeclaration
Builds a declaration using a BuilderByPattern configured by build.
buildDestructuringDeclaration¶
Builds a destructuring declaration using a BuilderByPattern configured by build.
buildExpression¶
fun KtPsiFactory.buildExpression(reformat: Boolean = true, build: BuilderByPattern<KtExpression>.() -> Unit): KtExpression
Builds an expression using a BuilderByPattern configured by build.
buildValueArgumentList¶
fun KtPsiFactory.buildValueArgumentList(build: BuilderByPattern<KtValueArgumentList>.() -> Unit): KtValueArgumentList
Builds a value argument list using a BuilderByPattern configured by build.
creareDelegatedSuperTypeEntry¶
fun creareDelegatedSuperTypeEntry(@NonNls text: String): KtConstructorDelegationCall
Creates a constructor delegation call from the given text (for example, "super(1)" or "this()").
createAnnotationEntry¶
fun createAnnotationEntry(@NonNls text: String): KtAnnotationEntry
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¶
fun createBlockStringTemplateEntry(expression: KtExpression): KtStringTemplateEntryWithExpression
Creates a block string-template entry (${...}) wrapping the given expression.
createCallableReferenceExpression¶
fun createCallableReferenceExpression(@NonNls text: String): KtCallableReferenceExpression?
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¶
fun createCallArguments(@NonNls text: String): KtValueArgumentList
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.
fun createCompanionBlock(@NonNls text: String): KtCompanionBlock
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.
fun createCompanionObject(@NonNls text: String): KtObjectDeclaration
Creates a companion object from the given text (for example, "companion object { ... }").
createConstructorKeyword¶
fun createConstructorKeyword(): PsiElement
Creates a constructor keyword token.
createDeclaration¶
fun <TDeclaration : KtDeclaration> createDeclaration(@NonNls text: String): TDeclaration
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¶
fun createDestructuringDeclaration(@NonNls text: String): KtDestructuringDeclaration
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¶
fun createDestructuringParameter(@NonNls text: String): KtParameter
Creates a destructuring lambda parameter from the given text (for example, "(x, y)").
createDot¶
fun createDot(): PsiElement
Creates a dot (.) token.
createEmptyBody¶
fun createEmptyBody(): KtBlockExpression
Creates an empty function body block ({}).
createEmptyClassBody¶
fun createEmptyClassBody(): KtClassBody
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¶
fun createExpressionIfPossible(@NonNls text: String): KtExpression?
createFile¶
fun createFile(@NonNls text: String): KtFile
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¶
fun createFileAnnotationListWithAnnotation(@NonNls annotationText: String): KtFileAnnotationList
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¶
fun createFunctionTypeParameter(typeReference: KtTypeReference): KtParameter
Creates a function-type parameter whose type is the given typeReference.
createFunctionTypeReceiver¶
fun createFunctionTypeReceiver(typeReference: KtTypeReference): KtFunctionTypeReceiver
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
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¶
fun createLabeledExpression(@NonNls labelName: String): KtLabeledExpression
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¶
fun createLambdaParameterList(@NonNls text: String): KtParameterList
Creates the parameter list of a lambda with the given parameter text.
createLambdaParameterListIfAny¶
fun createLambdaParameterListIfAny(@NonNls text: String): KtParameterList?
Creates the parameter list of a lambda with the given parameter text, or null if the lambda declares none.
createLiteralStringTemplateEntry¶
fun createLiteralStringTemplateEntry(@NonNls literal: String): KtLiteralStringTemplateEntry
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¶
fun createModifierList(modifier: KtModifierKeywordToken): KtModifierList
Creates a modifier list containing the single given modifier keyword.
fun createModifierList(@NonNls text: String): KtModifierList
Creates a modifier list from the given text (a space-separated sequence of modifiers).
createMultiDollarBlockStringTemplateEntry¶
fun createMultiDollarBlockStringTemplateEntry(expression: KtExpression, prefixLength: Int): KtStringTemplateEntryWithExpression
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
prefixLengthis not positive
createMultiDollarSimpleNameStringTemplateEntry¶
fun createMultiDollarSimpleNameStringTemplateEntry(@NonNls name: String, prefixLength: Int): KtSimpleNameStringTemplateEntry
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
prefixLengthis 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
prefixLengthis not positive
createNameIdentifier¶
fun createNameIdentifier(@NonNls name: String): PsiElement
createNameIdentifierIfPossible¶
fun createNameIdentifierIfPossible(@NonNls name: String): PsiElement?
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¶
fun createOperationName(@NonNls name: String): KtSimpleNameExpression
Creates an operation-reference expression for the given operator name (for example, "+").
createPackageDirective¶
fun createPackageDirective(fqName: FqName): KtPackageDirective
Creates a package directive for the given fqName.
createPackageDirectiveIfNeeded¶
fun createPackageDirectiveIfNeeded(fqName: FqName): KtPackageDirective?
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¶
fun createParameterList(@NonNls text: String): KtParameterList
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¶
fun createPrimaryConstructor(@NonNls text: String = ""): KtPrimaryConstructor
Creates a primary constructor from the given text (for example, "constructor(x: Int)"), defaulting to an empty one.
createPrimaryConstructorWithModifiers¶
fun createPrimaryConstructorWithModifiers(@NonNls modifiers: String?): KtPrimaryConstructor
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
fun createProperty(@NonNls text: String): KtProperty
Creates a property from the given full declaration text (for example, "val x: Int = 1").
createPropertyDelegate¶
fun createPropertyDelegate(expression: KtExpression): KtPropertyDelegate
Creates a property delegate (by ...) whose delegate expression is the given expression.
createPropertyGetter¶
fun createPropertyGetter(expression: KtExpression): KtPropertyAccessor
Creates a property getter whose body is the given expression (a block or a single expression).
createPropertySetter¶
fun createPropertySetter(expression: KtExpression): KtPropertyAccessor
Creates a property setter whose body is the given expression (a block or a single expression).
createRawStringTemplate¶
fun createRawStringTemplate(@NonNls content: String): KtStringTemplateExpression
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¶
fun createSecondaryConstructor(@NonNls decl: String): KtSecondaryConstructor
Creates a secondary constructor from the given declaration text decl.
createSemicolon¶
fun createSemicolon(): PsiElement
Creates a semicolon token.
createSimpleName¶
fun createSimpleName(@NonNls name: String): KtSimpleNameExpression
Creates a simple name reference expression for the given name.
createSimpleNameStringTemplateEntry¶
fun createSimpleNameStringTemplateEntry(@NonNls name: String): KtSimpleNameStringTemplateEntry
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¶
fun createStringTemplate(@NonNls content: String): KtStringTemplateExpression
Creates a regular (double-quoted) string template with the given content.
createSuperTypeCallEntry¶
fun createSuperTypeCallEntry(@NonNls text: String): KtSuperTypeCallEntry
Creates a superclass constructor call entry from the given text (for example, "Base(1)").
createSuperTypeEntry¶
fun createSuperTypeEntry(@NonNls text: String): KtSuperTypeEntry
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.
fun createType(typeElement: KtTypeElement): KtTypeReference
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¶
fun createTypeArgument(@NonNls text: String): KtTypeProjection?
Creates a single type argument (projection) from the given text.
createTypeArguments¶
fun createTypeArguments(@NonNls text: String): KtTypeArgumentList
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¶
fun createTypeIfPossible(@NonNls type: String): KtTypeReference?
Creates a type reference from the given type text, or returns null if it cannot be parsed as such.
createTypeParameter¶
fun createTypeParameter(@NonNls text: String): KtTypeParameter
Creates a single type parameter from the given text (for example, "T : Comparable<T>").
createTypeParameterList¶
fun createTypeParameterList(@NonNls text: String): KtTypeParameterList
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
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¶
fun wrapInABlockWrapper(expression: KtExpression): KtBlockExpression
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.