NameAllocator

class NameAllocator

Assigns Swift identifier names to avoid collisions, keywords, and invalid characters. To use, first create an instance and allocate all of the names that you need. Typically this is a mix of user-supplied names and constants:

val nameAllocator = NameAllocator()
for (property in properties) {
nameAllocator.newName(property.name, property)
}
nameAllocator.newName("sb", "string builder")

Pass a unique tag object to each allocation. The tag scopes the name, and can be used to look up the allocated name later. Typically the tag is the object that is being named. In the above example we use property for the user-supplied property names, and "string builder" for our constant string builder.

Once we've allocated names we can use them when generating code:

val builder = FunctionSpec.getterBuilder()
.returns(DeclaredTypeName.STRING)

builder.addStatement(#"var %N = """#, nameAllocator.get("string builder"))

for (property in properties) {
builder.addStatement(#"%N += "\(%N)"#, nameAllocator.get("string builder"), nameAllocator.get(property))
}
builder.addStatement("return %N", nameAllocator.get("string builder"))

return PropertySpec.builder("description", DeclaredTypeName.STRING)
.getter(builder.build())
.build()

The above code generates unique names if presented with conflicts. Given user-supplied properties with names ab and sb this generates the following:

var description: String {
var sb_ = ""
sb_ += "\(ab)"
sb_ += "\(sb)"
return sb_
}

The underscore is appended to sb to avoid conflicting with the user-supplied sb property. Underscores are also prefixed for names that start with a digit, and used to replace name-unsafe characters like space or dash.

When dealing with multiple independent inner scopes, use a copy of the NameAllocator used for the outer scope to further refine name allocation for a specific inner scope.

Constructors

NameAllocator
Link copied to clipboard
fun NameAllocator()

Functions

copy
Link copied to clipboard
fun copy(): NameAllocator
Create a deep copy of this NameAllocator.
equals
Link copied to clipboard
open operator fun equals(other: Any?): Boolean
get
Link copied to clipboard
operator fun get(tag: Any): String
Retrieve a name created with NameAllocator.newName.
hashCode
Link copied to clipboard
open fun hashCode(): Int
newName
Link copied to clipboard
fun newName(suggestion: String, tag: Any = UUID.randomUUID().toString()): String
Return a new name using suggestion that will not be a Swift identifier or clash with other names.
toString
Link copied to clipboard
open fun toString(): String