Android Extensions refactoring

This commit is contained in:
Yan Zhulanow
2015-08-18 16:31:26 +03:00
parent 2de4de4a1e
commit ad10340bd7
29 changed files with 254 additions and 241 deletions
@@ -1 +1 @@
org.jetbrains.kotlin.android.AndroidCommandLineProcessor
org.jetbrains.kotlin.android.synthetic.AndroidCommandLineProcessor
@@ -1 +1 @@
org.jetbrains.kotlin.android.AndroidComponentRegistrar
org.jetbrains.kotlin.android.synthetic.AndroidComponentRegistrar
@@ -14,14 +14,13 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.android
package org.jetbrains.kotlin.android.synthetic
import com.intellij.mock.MockProject
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.project.Project
import com.intellij.psi.impl.PsiTreeChangePreprocessor
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.android.synthetic.codegen.AndroidExpressionCodegenExtension
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
import org.jetbrains.kotlin.compiler.plugin.CliOption
import org.jetbrains.kotlin.compiler.plugin.CliOptionProcessingException
@@ -30,7 +29,10 @@ import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.CompilerConfigurationKey
import org.jetbrains.kotlin.extensions.ExternalDeclarationsProvider
import org.jetbrains.kotlin.lang.resolve.android.*
import org.jetbrains.kotlin.android.synthetic.res.AndroidLayoutXmlFileManager
import org.jetbrains.kotlin.android.synthetic.res.SyntheticFileGenerator
import org.jetbrains.kotlin.android.synthetic.res.CliAndroidLayoutXmlFileManager
import org.jetbrains.kotlin.android.synthetic.res.CliSyntheticFileGenerator
import org.jetbrains.kotlin.psi.JetFile
public object AndroidConfigurationKeys {
@@ -68,8 +70,8 @@ public class AndroidCommandLineProcessor : CommandLineProcessor {
public class CliAndroidDeclarationsProvider(private val project: Project) : ExternalDeclarationsProvider {
override fun getExternalDeclarations(moduleInfo: ModuleInfo?): Collection<JetFile> {
val parser = ServiceManager.getService(project, javaClass<AndroidUIXmlProcessor>())
return parser.parseToPsi() ?: listOf()
val parser = ServiceManager.getService(project, javaClass<SyntheticFileGenerator>())
return parser.getSyntheticFiles() ?: listOf()
}
}
@@ -81,11 +83,10 @@ public class AndroidComponentRegistrar : ComponentRegistrar {
val supportV4 = configuration.get(AndroidConfigurationKeys.SUPPORT_V4) ?: "false"
if (androidResPath != null && androidManifest != null) {
val xmlProcessor = CliAndroidUIXmlProcessor(project, androidManifest, androidResPath)
if (supportV4 == "true") xmlProcessor.supportV4 = true
val xmlProcessor = CliSyntheticFileGenerator(project, androidManifest, androidResPath, supportV4 == "true")
project.registerService(javaClass<AndroidUIXmlProcessor>(), xmlProcessor)
project.registerService(javaClass<AndroidResourceManager>(), CliAndroidResourceManager(project, androidManifest, androidResPath))
project.registerService(javaClass<SyntheticFileGenerator>(), xmlProcessor)
project.registerService(javaClass<AndroidLayoutXmlFileManager>(), CliAndroidLayoutXmlFileManager(project, androidManifest, androidResPath))
ExternalDeclarationsProvider.registerExtension(project, CliAndroidDeclarationsProvider(project))
ExpressionCodegenExtension.registerExtension(project, AndroidExpressionCodegenExtension())
@@ -14,9 +14,12 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.android.synthetic.res.AndroidFragment
import org.jetbrains.kotlin.android.synthetic.res.AndroidResource
import org.jetbrains.kotlin.android.synthetic.res.AndroidWidget
import org.jetbrains.kotlin.lexer.JetKeywordToken
import org.jetbrains.kotlin.lexer.JetTokens
@@ -14,17 +14,12 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiElement
import com.intellij.openapi.project.Project
import com.intellij.openapi.components.ServiceManager
import com.intellij.psi.PsiField
import com.intellij.psi.PsiClass
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Computable
import com.intellij.openapi.module.ModuleServiceManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
fun isAndroidSyntheticFile(f: PsiFile?): Boolean {
return f?.getUserData(AndroidConst.ANDROID_USER_PACKAGE) != null
@@ -32,6 +27,6 @@ fun isAndroidSyntheticFile(f: PsiFile?): Boolean {
public fun isAndroidSyntheticElement(element: PsiElement?): Boolean {
return isAndroidSyntheticFile(ApplicationManager.getApplication().runReadAction(Computable {
element?.getContainingFile()
element?.containingFile
}))
}
@@ -14,10 +14,10 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic
import org.xml.sax.helpers.DefaultHandler
import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler
import java.util.HashMap
class AndroidXmlHandler(private val elementCallback: (String, String) -> Unit) : DefaultHandler() {
@@ -14,11 +14,10 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic
import java.util.ArrayList
open class Context(val buffer: StringBuffer = StringBuffer(), private var indentDepth: Int = 0) {
open class InvalidIndent(num: Int) : RuntimeException("Indentation level < 0: $num")
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic
interface KotlinWriter {
fun toStringBuffer(): StringBuffer
@@ -14,29 +14,24 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.android
package org.jetbrains.kotlin.android.synthetic.codegen
import org.jetbrains.kotlin.codegen.ClassBuilder
import org.jetbrains.kotlin.codegen.ClassBuilderMode
import org.jetbrains.kotlin.codegen.FunctionCodegen
import org.jetbrains.kotlin.codegen.StackValue
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.JetTypeMapper
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.lang.resolve.android.AndroidConst
import org.jetbrains.kotlin.android.synthetic.AndroidConst
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaClassDescriptor
import org.jetbrains.kotlin.psi.JetClassOrObject
import org.jetbrains.kotlin.psi.JetFile
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor
import org.jetbrains.kotlin.resolve.scopes.receivers.ClassReceiver
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.types.Flexibility
import org.jetbrains.kotlin.types.lowerIfFlexible
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_PRIVATE
@@ -14,21 +14,20 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic.res
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiElement
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.openapi.util.*
import com.intellij.openapi.vfs.impl.*
import com.intellij.openapi.vfs.*
import com.intellij.openapi.components.*
import com.intellij.openapi.extensions.*
import com.intellij.openapi.module.*
import org.jetbrains.kotlin.psi.JetProperty
import java.util.*
public abstract class AndroidResourceManager(val project: Project) {
public abstract class AndroidLayoutXmlFileManager(val project: Project) {
public abstract val androidModuleInfo: AndroidModuleInfo?
@@ -42,9 +41,9 @@ public abstract class AndroidResourceManager(val project: Project) {
fun VirtualFile.getAllChildren(): List<VirtualFile> {
val allChildren = arrayListOf<VirtualFile>()
val currentChildren = getChildren() ?: emptyArray()
val currentChildren = children ?: emptyArray()
for (child in currentChildren) {
if (child.isDirectory()) {
if (child.isDirectory) {
allChildren.addAll(child.getAllChildren())
}
else {
@@ -57,20 +56,27 @@ public abstract class AndroidResourceManager(val project: Project) {
val resDirectories = info.resDirectories.map { fileManager.findFileByUrl("file://$it") }
val allChildren = resDirectories.flatMap { it?.getAllChildren() ?: listOf() }
return allChildren
.filter { it.getParent().getName().startsWith("layout") && it.getName().toLowerCase().endsWith(".xml") }
.map { psiManager.findFile(it) }
.filterNotNull()
.groupBy { it.getName().substringBeforeLast('.') }
.mapValues { it.getValue().sortBy { it.getParent()!!.getName().length() } }
val allLayoutFiles = allChildren.filter { it.parent.name.startsWith("layout") && it.name.toLowerCase().endsWith(".xml") }
val allLayoutPsiFiles = allLayoutFiles.fold(ArrayList<PsiFile>(allLayoutFiles.size())) { list, file ->
val psiFile = psiManager.findFile(file)
if (psiFile != null && psiFile.parent != null) {
list += psiFile
}
list
}
val layoutNameToXmls = allLayoutPsiFiles
.groupBy { it.name.substringBeforeLast('.') }
.mapValues { it.getValue().sortBy { it.parent!!.name.length() } }
return layoutNameToXmls
}
companion object {
public fun getInstance(module: Module): AndroidResourceManager {
val service = ModuleServiceManager.getService(module, javaClass<AndroidResourceManager>())
return service ?: module.getComponent(javaClass<AndroidResourceManager>())!!
public fun getInstance(module: Module): AndroidLayoutXmlFileManager {
val service = ModuleServiceManager.getService(module, javaClass<AndroidLayoutXmlFileManager>())
return service ?: module.getComponent(javaClass<AndroidLayoutXmlFileManager>())!!
}
}
}
@@ -14,9 +14,10 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic.res
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.android.synthetic.toMap
import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler
import java.io.File
@@ -24,11 +25,11 @@ import java.io.FileInputStream
import javax.xml.parsers.SAXParser
import javax.xml.parsers.SAXParserFactory
public class CliAndroidResourceManager(
public class CliAndroidLayoutXmlFileManager(
project: Project,
private val manifestPath: String,
private val resDirectories: List<String>
) : AndroidResourceManager(project) {
) : AndroidLayoutXmlFileManager(project) {
override val androidModuleInfo by lazy {
AndroidModuleInfo(getApplicationPackage(manifestPath), resDirectories)
@@ -60,7 +61,7 @@ public class CliAndroidResourceManager(
return applicationPackage
}
catch (e: Exception) {
throw AndroidUIXmlProcessor.NoAndroidManifestFound()
throw SyntheticFileGenerator.NoAndroidManifestFound()
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic.res
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
@@ -22,33 +22,41 @@ import com.intellij.psi.PsiFile
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider.Result
import java.io.ByteArrayInputStream
import org.jetbrains.kotlin.android.synthetic.AndroidXmlHandler
import org.jetbrains.kotlin.android.synthetic.parseAndroidResource
import kotlin.properties.Delegates
public class CliAndroidUIXmlProcessor(
public class CliSyntheticFileGenerator(
project: Project,
private val manifestPath: String,
private val resDirectories: List<String>
) : AndroidUIXmlProcessor(project) {
private val resDirectories: List<String>,
private val supportV4: Boolean
) : SyntheticFileGenerator(project) {
override val resourceManager: CliAndroidResourceManager by lazy {
CliAndroidResourceManager(project, manifestPath, resDirectories)
override fun supportV4(): Boolean {
return supportV4
}
override val layoutXmlFileManager: CliAndroidLayoutXmlFileManager by Delegates.lazy {
CliAndroidLayoutXmlFileManager(project, manifestPath, resDirectories)
}
override val cachedSources: CachedValue<List<AndroidSyntheticFile>> by lazy {
cachedValue {
Result.create(parse(), ModificationTracker.NEVER_CHANGED)
Result.create(generateSyntheticFiles(), ModificationTracker.NEVER_CHANGED)
}
}
override fun parseLayout(files: List<PsiFile>): List<AndroidResource> {
override fun extractLayoutResources(files: List<PsiFile>): List<AndroidResource> {
val resources = arrayListOf<AndroidResource>()
val handler = AndroidXmlHandler { id, widgetType -> resources.add(parseAndroidResource(id, widgetType)) }
try {
for (file in files) {
val inputStream = ByteArrayInputStream(file.virtualFile.contentsToByteArray())
resourceManager.saxParser.parse(inputStream, handler)
val inputStream = ByteArrayInputStream(file.getVirtualFile().contentsToByteArray())
layoutXmlFileManager.saxParser.parse(inputStream, handler)
}
return removeDuplicates(resources)
return filterDuplicates(resources)
}
catch (e: Throwable) {
LOG.error(e)
@@ -14,39 +14,38 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic.res
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager
import com.intellij.testFramework.LightVirtualFile
import org.jetbrains.kotlin.android.synthetic.AndroidConst
import org.jetbrains.kotlin.android.synthetic.KotlinStringWriter
import org.jetbrains.kotlin.android.synthetic.escapeAndroidIdentifier
import org.jetbrains.kotlin.psi.JetFile
import org.jetbrains.kotlin.types.Flexibility
public class AndroidSyntheticFile(val name: String, val contents: String)
public abstract class AndroidUIXmlProcessor(protected val project: Project) {
public abstract class SyntheticFileGenerator(protected val project: Project) {
public class NoAndroidManifestFound : Exception("No android manifest file found in project root")
protected val LOG: Logger = Logger.getInstance(javaClass)
public abstract val resourceManager: AndroidResourceManager
public abstract val layoutXmlFileManager: AndroidLayoutXmlFileManager
protected abstract val cachedSources: CachedValue<List<AndroidSyntheticFile>>
//MAKE CONSTANT (or abstract)
var supportV4 = false
private val cachedJetFiles: CachedValue<List<JetFile>> by lazy {
cachedValue {
val psiManager = PsiManager.getInstance(project)
val applicationPackage = resourceManager.androidModuleInfo?.applicationPackage
val applicationPackage = layoutXmlFileManager.androidModuleInfo?.applicationPackage
val jetFiles = cachedSources.value.mapIndexed { index, syntheticFile ->
val fileName = AndroidConst.SYNTHETIC_FILENAME_PREFIX + syntheticFile.name + ".kt"
@@ -62,15 +61,18 @@ public abstract class AndroidUIXmlProcessor(protected val project: Project) {
}
}
public fun parse(generateCommonFiles: Boolean = true): List<AndroidSyntheticFile> {
protected abstract fun supportV4(): Boolean
public fun generateSyntheticFiles(generateCommonFiles: Boolean = true): List<AndroidSyntheticFile> {
val commonFiles = if (generateCommonFiles) {
val clearCacheFile = renderSyntheticFile("clearCache") {
val renderSyntheticFile = renderSyntheticFile("clearCache") {
writePackage(AndroidConst.SYNTHETIC_PACKAGE)
writeAndroidImports()
writeClearCacheFunction(AndroidConst.ACTIVITY_FQNAME)
writeClearCacheFunction(AndroidConst.FRAGMENT_FQNAME)
if (supportV4) writeClearCacheFunction(AndroidConst.SUPPORT_FRAGMENT_FQNAME)
if (supportV4()) writeClearCacheFunction(AndroidConst.SUPPORT_FRAGMENT_FQNAME)
}
val clearCacheFile = renderSyntheticFile
listOf(clearCacheFile,
FLEXIBLE_TYPE_FILE,
@@ -79,9 +81,9 @@ public abstract class AndroidUIXmlProcessor(protected val project: Project) {
FAKE_SUPPORT_V4_WIDGET_FILE)
} else listOf()
return resourceManager.getLayoutXmlFiles().flatMap { entry ->
return layoutXmlFileManager.getLayoutXmlFiles().flatMap { entry ->
val files = entry.getValue()
val resources = parseLayout(files)
val resources = extractLayoutResources(files)
val layoutName = files[0].name.substringBefore('.')
@@ -92,15 +94,15 @@ public abstract class AndroidUIXmlProcessor(protected val project: Project) {
}.filterNotNull() + commonFiles
}
public fun parseToPsi(): List<JetFile>? = cachedJetFiles.value
public fun getSyntheticFiles(): List<JetFile>? = cachedJetFiles.value
protected abstract fun parseLayout(files: List<PsiFile>): List<AndroidResource>
protected abstract fun extractLayoutResources(files: List<PsiFile>): List<AndroidResource>
private fun renderMainLayoutFile(layoutName: String, resources: List<AndroidResource>): AndroidSyntheticFile {
return renderLayoutFile(layoutName + AndroidConst.LAYOUT_POSTFIX,
escapeAndroidIdentifier(layoutName), resources) {
val properties = it.mainProperties.toArrayList()
if (supportV4) properties.addAll(it.mainPropertiesForSupportV4)
if (supportV4()) properties.addAll(it.mainPropertiesForSupportV4)
properties
}
}
@@ -153,7 +155,7 @@ public abstract class AndroidUIXmlProcessor(protected val project: Project) {
writeText("public fun $receiver.${AndroidConst.CLEAR_FUNCTION_NAME}() {}\n")
}
protected fun <T> cachedValue(result: () -> CachedValueProvider.Result<T>): CachedValue<T> {
protected fun <T> cachedValue(result: () -> Result<T>): CachedValue<T> {
return CachedValuesManager.getManager(project).createCachedValue(result, false)
}
@@ -161,7 +163,7 @@ public abstract class AndroidUIXmlProcessor(protected val project: Project) {
return fqName.startsWith(AndroidConst.SUPPORT_V4_PACKAGE)
}
protected fun removeDuplicates(resources: List<AndroidResource>): List<AndroidResource> {
protected fun filterDuplicates(resources: List<AndroidResource>): List<AndroidResource> {
val resourceMap = linkedMapOf<String, AndroidResource>()
val resourcesToExclude = hashSetOf<String>()
@@ -14,7 +14,9 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.lang.resolve.android
package org.jetbrains.kotlin.android.synthetic.res
import org.jetbrains.kotlin.android.synthetic.AndroidConst
public data class AndroidModuleInfo(val applicationPackage: String, resDirectories: List<String>) {
val resDirectories = resDirectories.sort()
@@ -40,7 +42,7 @@ public class AndroidWidget(id: String, override val className: String) : Android
val MAIN_PROPERTIES_SUPPORT_V4 = listOf(AndroidConst.SUPPORT_FRAGMENT_FQNAME to "getView().findViewById(0)")
val VIEW_PROPERTIES = listOf("android.view.View" to "findViewById(0)")
val VIEW_PROPERTIES = listOf(AndroidConst.VIEW_FQNAME to "findViewById(0)")
}
override val mainProperties = MAIN_PROPERTIES