summaryrefslogtreecommitdiff
path: root/android/run/testSrc/com/android/tools/idea/run/deployment/liveedit/BasicCompileTest.kt
blob: 32e28d2029b119a647ecf0ac67c1b05daae53dfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.tools.idea.run.deployment.liveedit

import com.android.tools.idea.run.deployment.liveedit.analysis.createKtFile
import com.android.tools.idea.run.deployment.liveedit.analysis.directApiCompileByteArray
import com.android.tools.idea.run.deployment.liveedit.analysis.directApiCompileIr
import com.android.tools.idea.run.deployment.liveedit.analysis.disableLiveEdit
import com.android.tools.idea.run.deployment.liveedit.analysis.enableLiveEdit
import com.android.tools.idea.run.deployment.liveedit.analysis.initialCache
import com.android.tools.idea.run.deployment.liveedit.analysis.modifyKtFile
import com.android.tools.idea.testing.AndroidProjectRule
import org.jetbrains.kotlin.idea.base.plugin.KotlinPluginModeProvider
import org.jetbrains.kotlin.psi.KtFile
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import kotlin.test.assertContains
import kotlin.test.assertEquals
import kotlin.test.fail

@RunWith(JUnit4::class)
class BasicCompileTest {
  @get:Rule
  var projectRule = AndroidProjectRule.inMemory().withKotlin()

  @Before
  fun setUp() {
    setUpComposeInProjectFixture(projectRule)
    disableLiveEdit()

    // Create mocks for the kotlin.jvm to avoid having to bring in the whole dependency
    projectRule.fixture.configureByText("JvmName.kt", "package kotlin.jvm\n" +
                                                      "@Target(AnnotationTarget.FILE)\n" +
                                                      "public annotation class JvmName(val name: String)\n")

    projectRule.fixture.configureByText("JvmMultifileClass.kt", "package kotlin.jvm\n" +
                                                                "@Target(AnnotationTarget.FILE)\n" +
                                                                "public annotation class JvmMultifileClass()")
  }

  @After
  fun tearDown() {
    enableLiveEdit()
  }

  @Test
  fun simpleChange() {
    val file = projectRule.createKtFile("A.kt", """
      fun foo() = ""
      fun bar() = 1 
    """)

    val cache = projectRule.initialCache(listOf(file))
    projectRule.modifyKtFile(file, """
      fun foo() = "I am foo"
      fun bar() = 1 
    """)

    var output = compile(file, cache)
    val returnedValue = invokeStatic("foo", loadClass(output))
    Assert.assertEquals("I am foo", returnedValue)

    // Replace the return value of foo.
    projectRule.modifyKtFile(file, """
      fun foo() = "I am not foo"
      fun bar() = 1 
    """)

    // Re-compile A.kt like how live edit work.
    output = compile(file, cache)
    var leReturnedValue = invokeStatic("foo", loadClass(output))
    Assert.assertEquals("I am not foo", leReturnedValue)
  }

  @Test
  fun recoverableErrors() {
    // Step 1: Error Free
    val file = projectRule.createKtFile("RecoverableError.kt", """
        fun recoverableError() { "a".toString() }
      """)

    val cache = projectRule.initialCache(listOf(file))

    // Step 2: Introduce recoverable syntax errors
    projectRule.modifyKtFile(file, """
        fun recoverableError() { "a".toString() } }
      """)

    try {
      compile(file, cache)
      Assert.fail("RecoverableError.kt contains a lexical error and should not be updated by Live Edit")
    } catch (e: LiveEditUpdateException) {
      Assert.assertEquals("Expecting a top level declaration", e.message)
    }

    // Step 3: Fix syntax error
    projectRule.modifyKtFile(file, """
        fun recoverableError() { "a".toString() }
      """)

    // Should not have compiler errors.
    compile(file, cache)
  }

  @Test
  fun inlineTarget() {
    val inlined = projectRule.createKtFile("InlineTarget.kt", "inline fun it1() = \"I am foo\"")
    val file = projectRule.createKtFile("CallInlineTarget.kt", "fun callInlineTarget() = \"\"")

    val cache = projectRule.initialCache(listOf(inlined, file))
    projectRule.modifyKtFile(file, "fun callInlineTarget() = it1()")

    val output = compile(file, cache)
    val returnedValue = invokeStatic("callInlineTarget", loadClass(output))
    Assert.assertEquals("I am foo", returnedValue)
  }

  @Test
  fun lambdaChange() {
    val file = projectRule.createKtFile("HasLambda.kt", """
      fun hasLambda() : String {
        var capture = "x"
        var lambda = { capture = "a" }
        lambda()
        return capture
      }
    """)

    val cache = projectRule.initialCache(listOf(file))
    projectRule.modifyKtFile(file, """
        fun hasLambda() : String {
          var capture = "z"
          var lambda = { capture = "y" }
          lambda()
          return capture
        }
      """)
    val output = compile(file, cache)
    Assert.assertEquals(1, output.supportClassesMap.size)
    val returnedValue = invokeStatic("hasLambda", loadClass(output))
    Assert.assertEquals("y", returnedValue)
  }

  @Test
  fun samChange() {
    val file = projectRule.createKtFile("HasSAM.kt", """
      fun interface A {
        fun go(): Int
      }
      fun hasSam(): Int {
        var test = A { 100 }
        return test.go()
      }
    """)
    val cache = MutableIrClassCache()
    val apk = projectRule.directApiCompileIr(file)
    val compiler = LiveEditCompiler(projectRule.project, cache, object: ApkClassProvider {
      override fun getClass(ktFile: KtFile, className: String) = apk[className]
    })
    val state = getPsiValidationState(file)
    val output = compile(listOf(LiveEditCompilerInput(file, state)), compiler)
    Assert.assertEquals(1, output.supportClassesMap.size)
    // Can't test invocation of the method since the functional interface "A" is not loaded.
  }

  @Test
  fun genericSamChange() {
    val file = projectRule.createKtFile("ModifyFieldValue.kt", """
      fun interface Observer<T> {
        fun onChanged(value: T)
      }

      class Watchable<T> {
        fun <T> callObserver(value: T, o: Observer<T>) {
          o.onChanged(value)
        }
      }

      fun main() {
        val x = Watchable<String>()
        x.callObserver("hello") { println(it) }
      }
    """)
    val cache = projectRule.initialCache(listOf(file))

    projectRule.modifyKtFile(file, """
      fun interface Observer<T> {
        fun onChanged(value: T)
      }

      class Watchable<T> {
        fun <T> callObserver(value: T, o: Observer<T>) {
          o.onChanged(value)
        }
      }

      fun main() {
        val x = Watchable<String>()
        x.callObserver("hello") { println("value: " + it) }
      }
    """)

    val output = compile(file, cache)
    Assert.assertEquals(1, output.supportClassesMap.size)
  }

  @Test
  fun noNewClasses() {
    val file = projectRule.createKtFile("Test.kt", """
      class A {}
      class B {}
    """)
    val cache = projectRule.initialCache(listOf(file))
    projectRule.modifyKtFile(file, """
      class A {}
      class B {}
      class C {}
    """.trimIndent())
    val exception = Assert.assertThrows(LiveEditUpdateException::class.java) {
      compile(file, cache)
    }
    assertEquals(LiveEditUpdateException.Error.UNSUPPORTED_SRC_CHANGE_USER_CLASS_ADDED, exception.error)
    assertEquals(exception.details, "added new class C in Test.kt")
  }

  @Test
  fun crossFileReference() {
    projectRule.createKtFile("A.kt", "fun foo() = \"\"")
    val fileCallA = projectRule.createKtFile("CallA.kt", "fun callA() = foo()")
    val cache = MutableIrClassCache()
    val apk = projectRule.directApiCompileIr(fileCallA)
    val compiler = LiveEditCompiler(projectRule.project, cache, object: ApkClassProvider {
      override fun getClass(ktFile: KtFile, className: String) = apk[className]
    })
    val state = getPsiValidationState(fileCallA)
    compile(listOf(LiveEditCompilerInput(fileCallA, state)), compiler)
  }

  @Test
  fun internalVar() {
    val file = projectRule.createKtFile("HasInternalVar.kt", """
      internal var x = 0
      fun getNum() = x
    """)
    val cache = projectRule.initialCache(listOf(file))

    projectRule.modifyKtFile(file, """
     internal var x = 0
     fun getNum() = x + 1
    """)

    val output = compile(file, cache)
    Assert.assertTrue(output.classesMap["HasInternalVarKt"]!!.isNotEmpty())
    val returnedValue = invokeStatic("getNum", loadClass(output))
    Assert.assertEquals(1, returnedValue)
  }

  @Test
  fun publicInlineFunction() {
    try {
      val file = projectRule.createKtFile("HasPublicInline.kt", "public inline fun publicInlineFun() = 1")
      val cache = projectRule.initialCache(listOf(file))
      projectRule.modifyKtFile(file, "public inline fun publicInlineFun() = 2")
      compile(file, cache)
      Assert.fail("Expecting an exception thrown.")
    }
    catch (e: LiveEditUpdateException) {
      Assert.assertEquals(LiveEditUpdateException.Error.NON_PRIVATE_INLINE_FUNCTION, e.error)
    }
  }

  @Test
  fun renamedFile() {
    val file = projectRule.createKtFile("RenamedFile.kt", """
      @file:kotlin.jvm.JvmName("CustomJvmName")
      @file:kotlin.jvm.JvmMultifileClass
      fun T() {}
    """)

    val cache = projectRule.initialCache(listOf(file))

    projectRule.modifyKtFile(file, """
      @file:kotlin.jvm.JvmName("CustomJvmName")
      @file:kotlin.jvm.JvmMultifileClass
      fun T() { val x = 0 }
    """)

    val output = compile(file, cache)
    Assert.assertNotNull(output.irClasses.singleOrNull { it.name == "CustomJvmName" }) // CustomJvmName.class doesn't change
    Assert.assertTrue(output.classesMap["CustomJvmName__RenamedFileKt"]!!.isNotEmpty())
  }

  @Test
  fun modifyConstructor() {
    val file = projectRule.createKtFile("ModifyConstructor.kt", """
      class MyClass() {
        init {
          val x = 0
        }
      }
    """)
    val cache = projectRule.initialCache(listOf(file))

   projectRule.modifyKtFile(file, """
      class MyClass() {
        init {
          val x = 999
        }
      }
    """)

    try {
      compile(file, cache)
      fail("Expected exception due to modified constructor")
    } catch (e: LiveEditUpdateException) {
      assertEquals(LiveEditUpdateException.Error.UNSUPPORTED_SRC_CHANGE_CONSTRUCTOR, e.error)
      assertContains(e.details, "MyClass")
    }
  }

  @Test
  fun modifyFieldValue() {
    val file = projectRule.createKtFile("ModifyFieldValue.kt", """
      class MyClass() {
        val a = 100
        val b = 200
      }
    """)
    val cache = projectRule.initialCache(listOf(file))

    projectRule.modifyKtFile(file, """
      class MyClass() {
        val a = 999
        val b = 200
      }
    """)

    try {
      compile(file, cache)
      fail("Expected exception due to modified field")
    }
    catch (e: LiveEditUpdateException) {
      assertEquals(LiveEditUpdateException.Error.UNSUPPORTED_SRC_CHANGE_CONSTRUCTOR, e.error)
      assertContains(e.details, "MyClass")
      println(e.details)
    }
  }

  @Test
  fun modifyStaticInit() {
    val file = projectRule.createKtFile("ModifyStaticInit.kt", "val x = 1")
    val cache = projectRule.initialCache(listOf(file))
    val next = projectRule.fixture.configureByText("ModifyStaticInit.kt", """
      val x = 2
    """.trimIndent())

    try {
      compile(next, cache)
      fail("Expected exception due to modified static initializer")
    } catch (e: LiveEditUpdateException) {
      assertEquals(LiveEditUpdateException.Error.UNSUPPORTED_SRC_CHANGE_CLINIT, e.error)
      assertContains(e.details, "static initializer")
    }
  }

  @Test
  fun `Modify when Mapping`() {
    val enumDef = projectRule.createKtFile("Food.kt", """
      enum class Food { Pizza, Donuts }
    """)

    val file = projectRule.createKtFile("ModifyWhenMapping.kt", """
      fun getUnits(food: Food) : String {
        return when (food) {
          Food.Pizza -> "slices"
          Food.Donuts -> "dozens"
        }
      }
    """)
    val cache = projectRule.initialCache(listOf(enumDef, file))

    projectRule.modifyKtFile(file, """
      fun getUnits(food: Food) : String {
        return when (food) {
          Food.Donuts -> "x"
          Food.Pizza -> "y"
        }
      }
    """)

    try {
      compile(file, cache)
      fail("Expected exception due to modified constructor")
    } catch (e: LiveEditUpdateException) {
      assertEquals(LiveEditUpdateException.Error.UNSUPPORTED_SRC_CHANGE_WHEN_ENUM_PATH, e.error)
      assertContains(e.details, "Changing `when` on enum code path")
    }
  }

  @Test
  fun `Adding new WithMapping`() {
    val enumDef = projectRule.createKtFile("Food.kt", """
      enum class Food { Pizza, Donuts }
    """)

    val file = projectRule.createKtFile("ModifyWhenMapping.kt", """
      fun getUnits(food: Food) : String {
        var suffix = when (food) {
          Food.Pizza -> "!!"
          Food.Donuts -> "!!!!!"
        }
        return suffix
      }

       fun getMessage(): String {
          return getUnits(Food.Pizza)
       }
    """)
    val cache = projectRule.initialCache(listOf(enumDef, file))

    projectRule.modifyKtFile(file, """
      fun getUnits(food: Food) : String {
        var suffix = when (food) {
          Food.Pizza -> "!!"
          Food.Donuts -> "!!!!!"
        }

        return when (food) {
          Food.Pizza -> "slices"
          Food.Donuts -> "dozens"
        } + suffix
      }

       fun getMessage(): String {
          return getUnits(Food.Pizza)
       }
    """)

    val output = compile(file, irClassCache = cache)
    var apk = projectRule.directApiCompileByteArray(listOf(enumDef, file))

    Assert.assertTrue(output.classesMap["ModifyWhenMappingKt"]!!.isNotEmpty())
    val returnedValue = invokeStatic("getMessage", loadClass(output, extraClasses = apk))
    Assert.assertEquals("slices!!", returnedValue)
  }


  @Test
  fun diagnosticErrorForInvisibleReference() {
    try {
      val file = projectRule.createKtFile("A.kt", """
      open class Parent {
        protected open fun invisibleFunction() {}
      }
      class Child: Parent() {
        override fun invisibleFunction() {}
      }
      fun foo() {
        val child = Child()
        child.invisibleFunction()
      }
    """)
      compile(file)
      Assert.fail("A.kt contains a call to an invisible function invisibleFunction()")
    }
    catch (e: LiveEditUpdateException) {
      if (KotlinPluginModeProvider.isK2Mode()) {
        Assert.assertEquals("[INVISIBLE_REFERENCE] Cannot access 'fun invisibleFunction(): Unit': it is protected in '/Child'.", e.message)
      } else {
        Assert.assertTrue(e.message?.contains("Analyze Error. INVISIBLE_MEMBER") == true)
      }
    }
  }
}