repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
LordAkkarin/Beacon | core/src/test/kotlin/tv/dotstart/beacon/core/version/VersionTest.kt | 1 | 3767 | /*
* Copyright 2020 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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 tv.dotstart.beacon.core.version
import org.junit.jupiter.api.DynamicTest
import org.junit.jupiter.api.TestFactory
import kotlin.test.assertEquals
/**
* @author Johannes Donath
* @date 12/12/2020
*/
internal class VersionTest {
companion object {
private val parserMap = mapOf(
"0.1.0-alpha" to Version(0, 1, 0, "alpha", null, InstabilityType.ALPHA, null),
"0.1.0-alpha.1" to Version(0, 1, 0, "alpha", 1, InstabilityType.ALPHA, null),
"0.1.0" to Version(0, 1, 0, null, null, InstabilityType.INCUBATION, null),
"0.1.0+git-abcdef" to
Version(0, 1, 0, null, null, InstabilityType.INCUBATION, "git-abcdef"),
"0.1.0-alpha+git-abcdef" to
Version(0, 1, 0, "alpha", null, InstabilityType.ALPHA, "git-abcdef"),
"2.1.3" to Version(2, 1, 3, null, null, InstabilityType.NONE, null),
"2.1.3-alpha" to Version(2, 1, 3, "alpha", null, InstabilityType.ALPHA, null),
"2.1.3-alpha.ci.2" to Version(2, 1, 3, "alpha.ci", 2, InstabilityType.ALPHA, null),
"3.0.0-alpha.1" to Version(3, 0, 0, "alpha", 1, InstabilityType.ALPHA, null),
)
private val compareList = listOf(
Version(0, 1, 0, "alpha", null, InstabilityType.ALPHA, null),
Version(0, 1, 0, "alpha", 1, InstabilityType.ALPHA, null),
Version(0, 1, 0, "beta", null, InstabilityType.BETA, null),
Version(0, 1, 0, "beta", 1, InstabilityType.BETA, null),
Version(0, 1, 0, null, null, InstabilityType.INCUBATION, null),
Version(0, 2, 0, "alpha", null, InstabilityType.ALPHA, null),
Version(0, 2, 0, null, null, InstabilityType.INCUBATION, null),
Version(1, 0, 0, "rc", null, InstabilityType.RELEASE_CANDIDATE, null),
Version(1, 0, 0, null, null, InstabilityType.NONE, null),
Version(1, 0, 1, null, null, InstabilityType.NONE, null),
Version(2, 0, 1, null, null, InstabilityType.NONE, null)
)
}
/**
* Evaluates whether the implementation is capable of parsing human readable representations for
* each respective component within the version number.
*/
@TestFactory
fun `It parses versions`() = parserMap
.map { (input, expected) ->
DynamicTest.dynamicTest(input) {
val actual = Version.parse(input)
assertEquals(expected, actual)
}
}
/**
* Evaluates whether the implementation is capable of comparing version numbers.
*/
@TestFactory
fun `It compares versions`() = compareList
.flatMap { current ->
val position = compareList.indexOf(current)
compareList
.mapIndexed { index, other ->
val expected = position.compareTo(index)
val operationName = when {
expected < 0 -> "<"
expected > 0 -> ">"
else -> "=="
}
DynamicTest.dynamicTest("$current $operationName $other") {
val actual = current.compareTo(other)
assertEquals(expected, actual)
}
}
}
}
| apache-2.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/IsCloseableBottomSheet.kt | 1 | 338 | package de.westnordost.streetcomplete.quests
import de.westnordost.streetcomplete.data.osm.mapdata.LatLon
interface IsCloseableBottomSheet {
/** Returns true if the bottom sheet shall consume the event */
fun onClickMapAt(position: LatLon, clickAreaSizeInMeters: Double): Boolean
fun onClickClose(onConfirmed: () -> Unit)
}
| gpl-3.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/crossing_island/AddCrossingIsland.kt | 1 | 2431 | package de.westnordost.streetcomplete.quests.crossing_island
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BLIND
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddCrossingIsland : OsmElementQuestType<Boolean> {
private val crossingFilter by lazy { """
nodes with
highway = crossing
and foot != no
and crossing
and crossing != island
and !crossing:island
""".toElementFilterExpression()}
private val excludedWaysFilter by lazy { """
ways with
highway and access ~ private|no
or railway
or highway = service
or highway and oneway and oneway != no
""".toElementFilterExpression()}
override val commitMessage = "Add whether pedestrian crossing has an island"
override val wikiLink = "Key:crossing:island"
override val icon = R.drawable.ic_quest_pedestrian_crossing_island
override val questTypeAchievements = listOf(PEDESTRIAN, BLIND)
override fun getTitle(tags: Map<String, String>) = R.string.quest_pedestrian_crossing_island
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> {
val excludedWayNodeIds = mutableSetOf<Long>()
mapData.ways
.filter { excludedWaysFilter.matches(it) }
.flatMapTo(excludedWayNodeIds) { it.nodeIds }
return mapData.nodes
.filter { crossingFilter.matches(it) && it.id !in excludedWayNodeIds }
}
override fun isApplicableTo(element: Element): Boolean? =
if (!crossingFilter.matches(element)) false else null
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("crossing:island", answer.toYesNo())
}
}
| gpl-3.0 |
SirWellington/alchemy-http | src/test/java/tech/sirwellington/alchemy/http/Step3ImplTest.kt | 1 | 7345 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.http
import com.nhaarman.mockito_kotlin.KArgumentCaptor
import com.nhaarman.mockito_kotlin.argumentCaptor
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.not
import org.hamcrest.Matchers.notNullValue
import org.hamcrest.Matchers.sameInstance
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
import sir.wellington.alchemy.collections.maps.Maps
import tech.sirwellington.alchemy.generator.AlchemyGenerator.Get.one
import tech.sirwellington.alchemy.generator.BooleanGenerators.Companion.booleans
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.integers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.smallPositiveIntegers
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.hexadecimalString
import tech.sirwellington.alchemy.http.AlchemyRequestSteps.OnSuccess
import tech.sirwellington.alchemy.http.AlchemyRequestSteps.Step3
import tech.sirwellington.alchemy.http.Generators.validUrls
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.DontRepeat
import tech.sirwellington.alchemy.test.junit.runners.Repeat
import java.net.MalformedURLException
import java.net.URL
/**
*
* @author SirWellington
*/
@RunWith(AlchemyTestRunner::class)
@Repeat
class Step3ImplTest
{
@Mock
private lateinit var stateMachine: AlchemyHttpStateMachine
private lateinit var request: HttpRequest
private lateinit var requestCaptor: KArgumentCaptor<HttpRequest>
@Mock
private lateinit var onSuccess: OnSuccess<*>
private lateinit var url: URL
private lateinit var instance: Step3
@Before
@Throws(MalformedURLException::class)
fun setUp()
{
url = one(validUrls())
request = HttpRequest.Builder.newInstance()
.usingUrl(url)
.build()
instance = Step3Impl(stateMachine, request)
verifyZeroInteractions(stateMachine)
requestCaptor = argumentCaptor()
}
@Test
fun testUsingHeader()
{
//Edge Cases
assertThrows { instance.usingHeader("", "") }
.isInstanceOf(IllegalArgumentException::class.java)
//Happy cases
val expectedHeaders = CollectionGenerators.mapOf(alphabeticStrings(),
hexadecimalString(10),
20)
for ((key, value) in expectedHeaders)
{
instance = instance.usingHeader(key, value)
}
instance.at(url)
verify(stateMachine).executeSync(requestCaptor.capture())
val requestMade = requestCaptor.firstValue
assertThat(requestMade, notNullValue())
assertThat(requestMade, not(sameInstance(request)))
assertThat(requestMade.requestHeaders, equalTo((expectedHeaders)))
//Adding an empty value should be ok too
val key = one(alphabeticStrings())
instance.usingHeader(key, "")
}
@Test
fun testUsingQueryParam()
{
val amount = one(integers(5, 20))
val strings = CollectionGenerators.mapOf(alphabeticStrings(),
hexadecimalString(10),
amount)
val integers = CollectionGenerators.mapOf(alphabeticStrings(),
smallPositiveIntegers(),
amount)
val booleans = CollectionGenerators.mapOf(alphabeticStrings(),
booleans(),
amount)
for ((key, value) in strings)
{
instance = instance.usingQueryParam(key, value)
}
for ((key, value) in integers)
{
instance = instance.usingQueryParam(key, value)
}
for ((key, value) in booleans)
{
instance = instance.usingQueryParam(key, value)
}
val expected = Maps.mutableCopyOf(strings)
//Put the integers
integers.forEach { k, v -> expected.put(k, v.toString()) }
//Put the booleans too
booleans.forEach { k, v -> expected.put(k, v.toString()) }
instance.at(url)
verify(stateMachine).executeSync(requestCaptor.capture())
val requestMade = requestCaptor.firstValue
assertThat(requestMade, notNullValue())
assertThat(requestMade.queryParams, equalTo(expected))
assertThat(requestMade, not(sameInstance(request)))
}
@DontRepeat
@Test
fun testUsingQueryParamEdgeCases()
{
//Edge cases
assertThrows { instance.usingQueryParam("", "") }
.isInstanceOf(IllegalArgumentException::class.java)
}
@Test
fun testFollowRedirects()
{
assertThrows { instance.followRedirects(-10) }
.isInstanceOf(IllegalArgumentException::class.java)
instance = instance.followRedirects()
assertThat(instance, notNullValue())
instance = instance.followRedirects(30)
assertThat(instance, notNullValue())
}
@Test
fun testAt()
{
//Edge Cases
assertThrows { instance.at("") }
.isInstanceOf(IllegalArgumentException::class.java)
instance.at(url)
verify(stateMachine).executeSync(requestCaptor.capture())
val requestMade = requestCaptor.firstValue
assertThat(requestMade, notNullValue())
assertThat(requestMade.url, equalTo(url))
assertThat(requestMade, not(sameInstance(request)))
}
@Test
fun testOnSuccess()
{
instance.onSuccess(onSuccess as OnSuccess<HttpResponse>)
verify(stateMachine).jumpToStep5(request, HttpResponse::class.java, onSuccess as OnSuccess<HttpResponse>)
}
@Test
fun testExpecting()
{
//Sad Cases
assertThrows { instance.expecting(Void::class.java) }
.isInstanceOf(IllegalArgumentException::class.java)
//Happy cases
val expectedClass = String::class.java
instance.expecting(expectedClass)
verify(stateMachine).jumpToStep4(request, expectedClass)
}
}
| apache-2.0 |
CarrotCodes/Pellet | server/src/test/kotlin/dev/pellet/server/codec/mime/MediaTypeParserTests.kt | 1 | 2950 | package dev.pellet.server.codec.mime
import dev.pellet.assertFailureIs
import dev.pellet.assertSuccess
import dev.pellet.server.codec.ParseException
import kotlin.test.Test
class MediaTypeParserTests {
@Test
fun `empty media type fails`() {
val testCase = ""
val result = MediaTypeParser.parse(testCase)
assertFailureIs<ParseException>(result)
}
@Test
fun `simple media type`() {
val testCase = "text/plain"
val result = MediaTypeParser.parse(testCase)
val expected = MediaType(
type = "text",
subtype = "plain",
parameters = listOf()
)
assertSuccess(expected, result)
}
@Test
fun `simple media type with parameter`() {
val testCase = "application/json; charset=utf-8"
val result = MediaTypeParser.parse(testCase)
val expected = MediaType(
type = "application",
subtype = "json",
parameters = listOf(
"charset" to "utf-8"
)
)
assertSuccess(expected, result)
}
@Test
fun `optional whitespace doesn't affect output`() {
val testCase = "application/json ; charset=utf-8; something=else"
val result = MediaTypeParser.parse(testCase)
val expected = MediaType(
type = "application",
subtype = "json",
parameters = listOf(
"charset" to "utf-8",
"something" to "else"
)
)
assertSuccess(expected, result)
}
@Test
fun `quotation marks for parameter value`() {
val testCase = "application/json; charset=\"utf-8\""
val result = MediaTypeParser.parse(testCase)
val expected = MediaType(
type = "application",
subtype = "json",
parameters = listOf(
"charset" to "utf-8",
)
)
assertSuccess(expected, result)
}
@Test
fun `mismatched quotation marks for parameter value are preserved`() {
val testCase = "application/json; charset=\"utf-8"
val result = MediaTypeParser.parse(testCase)
val expected = MediaType(
type = "application",
subtype = "json",
parameters = listOf(
"charset" to "\"utf-8",
)
)
assertSuccess(expected, result)
}
@Test
fun `invalid media types`() {
val testCases = listOf(
" ",
"text/plain/something",
"text plain;",
"text/plain;;;",
"text/plain;==",
"text/plain;a=",
"text/",
"/plain",
";",
";/",
"/;",
)
testCases.forEach { testCase ->
val result = MediaTypeParser.parse(testCase)
assertFailureIs<ParseException>(result)
}
}
}
| apache-2.0 |
strykeforce/thirdcoast | src/main/kotlin/org/strykeforce/trapper/ActionCommand.kt | 1 | 699 | package org.strykeforce.trapper
import edu.wpi.first.wpilibj2.command.CommandBase
abstract class ActionCommand @JvmOverloads constructor(
var action: Action = Action(),
val trapperSubsystem: TrapperSubsystem
) : CommandBase() {
constructor(name: String, trapperSubsystem: TrapperSubsystem) : this(
Action(name),
trapperSubsystem
)
init {
addRequirements(trapperSubsystem)
}
val traces = mutableListOf<Trace>()
abstract val trace: Trace
override fun execute() = if (trapperSubsystem.enabled) traces += trace else Unit
fun postWith(session: OkHttpSession) =
if (trapperSubsystem.enabled) session.post(traces) else Unit
} | mit |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/provider/ThumbnailsIdProvider.kt | 1 | 423 | package com.boardgamegeek.provider
import android.content.Context
import android.net.Uri
import com.boardgamegeek.provider.BggContract.Companion.PATH_THUMBNAILS
class ThumbnailsIdProvider : BaseFileProvider() {
override val path = "$PATH_THUMBNAILS/*"
override val contentPath = PATH_THUMBNAILS
override fun generateFileName(context: Context, uri: Uri): String? {
return uri.lastPathSegment
}
}
| gpl-3.0 |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/entities/GameDetailEntity.kt | 1 | 139 | package com.boardgamegeek.entities
data class GameDetailEntity(
val id: Int,
val name: String,
val description: String = ""
)
| gpl-3.0 |
songzhw/Hello-kotlin | Advanced_kb/test/test/UnknowSystemTest2.kt | 1 | 629 | package test
import ExecutionTimeRunner
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.Assert.*
import org.junit.runner.RunWith
@RunWith(ExecutionTimeRunner::class)
class UnknownSystemTest2 {
lateinit var target: UnknownSystem
@Before
fun setup() {
println("szw @Before")
val worker = UnknownWorker()
target = UnknownSystem(worker)
}
@After
fun teardown() {
println("szw @after")
}
@Test
fun add() {
val result = target.add(3, 2)
assertEquals(5, result);
}
@Test
fun command() {
}
} | apache-2.0 |
JotraN/shows-to-watch-android | app/src/main/java/io/josephtran/showstowatch/shows/ShowsPresenter.kt | 1 | 3120 | package io.josephtran.showstowatch.shows
import android.content.Context
import android.util.Log
import io.josephtran.showstowatch.api.STWClientWrapper
import io.josephtran.showstowatch.api.STWShow
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
class ShowsPresenter(context: Context, val view: ShowsView) {
private val client = STWClientWrapper(context)
companion object {
val ALL_SHOWS = "All"
val IN_PROGRESS_SHOWS = "In Progress"
val ABANDONED_SHOWS = "Abandoned"
val COMPLETED_SHOWS = "Completed"
val SHOWS_TYPES = arrayOf(ALL_SHOWS, IN_PROGRESS_SHOWS, ABANDONED_SHOWS, COMPLETED_SHOWS)
fun getShowsType(typeIndex: Int): String {
if (typeIndex > SHOWS_TYPES.size || typeIndex < 0)
return ""
return SHOWS_TYPES.get(typeIndex)
}
fun getShowsTypesNum(): Int = SHOWS_TYPES.size
fun getTypeIndex(showsType: String) = SHOWS_TYPES.indexOf(showsType)
}
fun downloadShows(index: Int) {
val showsType = getShowsType(index)
when (showsType) {
ALL_SHOWS -> downloadAllShows()
IN_PROGRESS_SHOWS -> downloadInProgressShows()
ABANDONED_SHOWS -> downloadAbandonedShows()
COMPLETED_SHOWS -> downloadCompletedShows()
else -> downloadAllShows()
}
}
private fun downloadAllShows() {
view.showProgress(true)
client.getShows()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(STWShowsSubscriber(view))
}
private fun downloadInProgressShows() {
view.showProgress(true)
client.getInProgressShows()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(STWShowsSubscriber(view))
}
private fun downloadAbandonedShows() {
view.showProgress(true)
client.getAbandonedShows()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(STWShowsSubscriber(view))
}
private fun downloadCompletedShows() {
view.showProgress(true)
client.getCompletedShows()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(STWShowsSubscriber(view))
}
class STWShowsSubscriber(val view: ShowsView) : Subscriber<List<STWShow>>() {
private val errorMessage = "Error downloading shows."
override fun onNext(shows: List<STWShow>?) {
if (shows == null) view.showError(errorMessage)
else view.addShows(shows.sortedByDescending(STWShow::updatedAt))
}
override fun onCompleted() {
view.showProgress(false)
}
override fun onError(e: Throwable?) {
view.showProgress(false)
view.showError(errorMessage)
Log.e(javaClass.name, errorMessage, e)
}
}
} | mit |
ratabb/Hishoot2i | app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/tools/badge/BadgeView.kt | 1 | 205 | package org.illegaller.ratabb.hishoot2i.ui.tools.badge
internal sealed class BadgeView
internal class Fail(val cause: Throwable) : BadgeView()
internal class Success(val data: List<String>) : BadgeView()
| apache-2.0 |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/entity/LanternZombie.kt | 1 | 1286 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.entity
import org.lanternpowered.server.data.key.LanternKeys
import org.lanternpowered.server.inventory.equipment.AbstractArmorEquipable
import org.lanternpowered.server.inventory.vanilla.VanillaInventoryArchetypes
import org.lanternpowered.server.network.entity.EntityProtocolTypes
import org.spongepowered.api.entity.living.monster.zombie.Zombie
import org.spongepowered.api.item.inventory.equipment.EquipmentInventory
open class LanternZombie(creationData: EntityCreationData) : LanternAgent(creationData), Zombie, AbstractArmorEquipable {
private val equipmentInventory: EquipmentInventory
init {
this.protocolType = EntityProtocolTypes.ZOMBIE
this.equipmentInventory = VanillaInventoryArchetypes.ENTITY_EQUIPMENT.build()
keyRegistry {
register(LanternKeys.POSE, Pose.STANDING)
}
}
override fun getEquipment(): EquipmentInventory = this.equipmentInventory
}
| mit |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/entity/vanilla/PigEntityProtocol.kt | 1 | 1440 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.entity.vanilla
import org.lanternpowered.api.data.Keys
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.key.minecraftKey
import org.lanternpowered.server.entity.LanternEntity
import org.lanternpowered.server.network.entity.parameter.ParameterList
class PigEntityProtocol<E : LanternEntity>(entity: E) : AnimalEntityProtocol<E>(entity) {
companion object {
private val TYPE = minecraftKey("pig")
}
private var lastSaddled = false
override val mobType: NamespacedKey get() = TYPE
override fun spawn(parameterList: ParameterList) {
super.spawn(parameterList)
parameterList.add(EntityParameters.Pig.HAS_SADDLE, this.entity.get(Keys.IS_SADDLED).orElse(false))
}
override fun update(parameterList: ParameterList) {
super.update(parameterList)
val saddled = this.entity.get(Keys.IS_SADDLED).orElse(false)
if (this.lastSaddled != saddled) {
parameterList.add(EntityParameters.Pig.HAS_SADDLE, saddled)
this.lastSaddled = saddled
}
}
}
| mit |
sabi0/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/ide/scripting.kt | 2 | 5161 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.plugins.groovy.ide
import com.intellij.execution.ExecutionManager
import com.intellij.execution.console.*
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.execution.ui.actions.CloseAction
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.search.GlobalSearchScope
import groovy.lang.Binding
import groovy.lang.GroovySystem
import org.codehaus.groovy.tools.shell.Interpreter
import org.jetbrains.plugins.groovy.GroovyLanguage
import java.awt.BorderLayout
import java.io.PrintWriter
import java.io.StringWriter
import java.text.SimpleDateFormat
import java.util.*
import javax.swing.JPanel
class GroovyScriptingShellAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
initConsole(project)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = ApplicationManager.getApplication().isInternal
}
}
object MyConsoleRootType : ConsoleRootType("groovy.scripting.shell", null)
private val TITLE = "Groovy IDE Scripting Shell"
private val defaultImports = listOf(
"com.intellij.openapi.application.*",
"com.intellij.openapi.project.*",
"com.intellij.openapi.module.*",
"com.intellij.openapi.vfs.*",
"com.intellij.psi.*",
"com.intellij.psi.search.*",
"com.intellij.psi.stubs.*",
"com.intellij.util.indexing.*"
)
private val defaultImportStatements = defaultImports.map {
"import $it"
}
private fun initConsole(project: Project) {
val console = LanguageConsoleImpl(project, TITLE, GroovyLanguage)
val action = ConsoleExecuteAction(console, createExecuteHandler(project))
action.registerCustomShortcutSet(action.shortcutSet, console.consoleEditor.component)
ConsoleHistoryController(MyConsoleRootType, null, console).install()
val consoleComponent = console.component
val toolbarActions = DefaultActionGroup()
val toolbar = ActionManager.getInstance().createActionToolbar("GroovyScriptingConsole", toolbarActions, false)
toolbar.setTargetComponent(consoleComponent)
val panel = JPanel(BorderLayout())
panel.add(consoleComponent, BorderLayout.CENTER)
panel.add(toolbar.component, BorderLayout.WEST)
val descriptor = object : RunContentDescriptor(console, null, panel, TITLE) {
override fun isContentReuseProhibited() = true
}
toolbarActions.addAll(*console.createConsoleActions())
val executor = DefaultRunExecutor.getRunExecutorInstance()
toolbarActions.add(CloseAction(executor, descriptor, project))
ExecutionManager.getInstance(project).contentManager.showRunContent(executor, descriptor)
val appInfo = ApplicationInfo.getInstance()
val namesInfo = ApplicationNamesInfo.getInstance()
val buildDate = SimpleDateFormat("dd MMM yy HH:ss", Locale.US).format(appInfo.buildDate.time)
console.print(
"Welcome!\n${namesInfo.fullProductName} (build #${appInfo.build}, $buildDate); Groovy: ${GroovySystem.getVersion()}\n",
ConsoleViewContentType.SYSTEM_OUTPUT
)
console.print(
"'application', 'project', 'facade' and 'allScope' variables are available at the top level. \n",
ConsoleViewContentType.SYSTEM_OUTPUT
)
console.print(
"Default imports:\n${defaultImports.joinToString(separator = ",\n") { "\t$it" }}\n\n",
ConsoleViewContentType.SYSTEM_OUTPUT
)
}
private fun createExecuteHandler(project: Project) = object : BaseConsoleExecuteActionHandler(false) {
val interpreter: Interpreter by lazy {
val binding = Binding(mapOf(
"application" to ApplicationManager.getApplication(),
"project" to project,
"facade" to JavaPsiFacade.getInstance(project),
"allScope" to GlobalSearchScope.allScope(project)
))
Interpreter(Interpreter::class.java.classLoader, binding)
}
override fun execute(text: String, console: LanguageConsoleView) {
ApplicationManager.getApplication().executeOnPooledThread {
runReadAction {
try {
val result: Any? = interpreter.evaluate(defaultImportStatements + "" + "" + text)
console.print("Returned: ", ConsoleViewContentType.SYSTEM_OUTPUT)
console.print("$result\n", ConsoleViewContentType.NORMAL_OUTPUT)
}
catch (e: Throwable) {
val errors = StringWriter()
e.printStackTrace(PrintWriter(errors))
console.print("Error: $errors", ConsoleViewContentType.ERROR_OUTPUT)
}
}
}
}
}
| apache-2.0 |
songzhw/CleanAlpha-Kotlin | app/src/main/kotlin/cn/song/kotlind/view/threetap/BoxSubscriber.kt | 2 | 681 | package cn.song.kotlind.view.threetap
import rx.Subscriber
import java.util.*
/**
* @author hzsongzhengwang
* @date 2015/8/11
* Copyright 2015 Six. All rights reserved.
*/
public class BoxSubscriber<T>(val child : Subscriber<in List<T>>, val size : Int) : Subscriber<T>(child){
val buffer = ArrayList<T>(size)
override fun onNext(t: T) {
buffer.add(t)
if(buffer.size() == size){
child.onNext(ArrayList(buffer))
buffer.remove(0)
}
}
override fun onCompleted() {
println("BoxSubscriber onCompleted()")
}
override fun onError(e: Throwable?) {
println("BoxSubscriber onError()")
}
}
| apache-2.0 |
hellenxu/AndroidAdvanced | AndroidAdvanced/app/src/main/java/six/ca/androidadvanced/architecture/coroutines/MainSample.kt | 1 | 1227 | package six.ca.androidadvanced.architecture.coroutines
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.act_coroutine.*
import six.ca.androidadvanced.R
/**
* @author hellenxu
* @date 2019-05-29
* Copyright 2019 Six. All rights reserved.
*/
class MainSample: AppCompatActivity(), View.OnClickListener {
private lateinit var userViewModel: UserViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_coroutine)
btnGetUser.setOnClickListener(this)
userViewModel = ViewModelProvider.NewInstanceFactory().create(UserViewModel::class.java)
}
override fun onClick(v: View?) {
tvResult.text = getString(R.string.loading)
userViewModel.getUserList()
userViewModel.userList.observe(::getLifecycle, ::updateContent)
}
private fun updateContent(result: List<User>) {
val sb = StringBuilder()
result.forEach {
sb.append(it.toString()).append(System.lineSeparator())
}
tvResult.text = sb.toString()
}
} | apache-2.0 |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/actions/movies/SyncUpdatedMovies.kt | 1 | 3500 | /*
* Copyright (C) 2015 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.actions.movies
import android.content.ContentProviderOperation
import android.content.ContentValues
import android.content.Context
import android.text.format.DateUtils
import androidx.work.WorkManager
import net.simonvt.cathode.actions.PagedAction
import net.simonvt.cathode.actions.PagedResponse
import net.simonvt.cathode.api.entity.UpdatedItem
import net.simonvt.cathode.api.service.MoviesService
import net.simonvt.cathode.api.util.TimeUtils
import net.simonvt.cathode.provider.DatabaseContract.MovieColumns
import net.simonvt.cathode.provider.ProviderSchematic.Movies
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.helper.MovieDatabaseHelper
import net.simonvt.cathode.settings.Timestamps
import net.simonvt.cathode.work.enqueueUniqueNow
import net.simonvt.cathode.work.movies.SyncPendingMoviesWorker
import retrofit2.Call
import javax.inject.Inject
class SyncUpdatedMovies @Inject constructor(
private val context: Context,
private val workManager: WorkManager,
private val moviesService: MoviesService,
private val movieHelper: MovieDatabaseHelper
) : PagedAction<Unit, UpdatedItem>() {
private val currentTime = System.currentTimeMillis()
override fun key(params: Unit): String = "SyncUpdatedMovies"
override fun getCall(params: Unit, page: Int): Call<List<UpdatedItem>> {
val lastUpdated =
Timestamps.get(context).getLong(Timestamps.MOVIES_LAST_UPDATED, currentTime)
val millis = lastUpdated - 12 * DateUtils.HOUR_IN_MILLIS
val updatedSince = TimeUtils.getIsoTime(millis)
return moviesService.updated(updatedSince, page, LIMIT)
}
override suspend fun handleResponse(
params: Unit,
pagedResponse: PagedResponse<Unit, UpdatedItem>
) {
val ops = arrayListOf<ContentProviderOperation>()
var page: PagedResponse<Unit, UpdatedItem>? = pagedResponse
do {
for (item in page!!.response) {
val updatedAt = item.updated_at.timeInMillis
val movie = item.movie!!
val traktId = movie.ids.trakt!!
val movieId = movieHelper.getId(traktId)
if (movieId != -1L) {
if (movieHelper.isUpdated(traktId, updatedAt)) {
val values = ContentValues()
values.put(MovieColumns.NEEDS_SYNC, true)
ops.add(
ContentProviderOperation.newUpdate(Movies.withId(movieId))
.withValues(values)
.build()
)
}
}
}
page = page.nextPage()
} while (page != null)
context.contentResolver.batch(ops)
}
override fun onDone() {
workManager.enqueueUniqueNow(SyncPendingMoviesWorker.TAG, SyncPendingMoviesWorker::class.java)
Timestamps.get(context)
.edit()
.putLong(Timestamps.MOVIES_LAST_UPDATED, currentTime)
.apply()
}
companion object {
private const val LIMIT = 100
}
}
| apache-2.0 |
SimonVT/cathode | cathode-entity/src/main/java/net/simonvt/cathode/entity/UserList.kt | 1 | 513 | package net.simonvt.cathode.entity
import net.simonvt.cathode.api.enumeration.Privacy
import net.simonvt.cathode.api.enumeration.SortBy
import net.simonvt.cathode.api.enumeration.SortOrientation
data class UserList(
val id: Long,
val name: String,
val description: String?,
val privacy: Privacy,
val displayNumbers: Boolean,
val allowComments: Boolean,
val sortBy: SortBy,
val sortOrientation: SortOrientation,
val updatedAt: Long,
val likes: Int,
val slug: String?,
val traktId: Long
)
| apache-2.0 |
Ruben-Sten/TeXiFy-IDEA | test/nl/hannahsten/texifyidea/index/file/LatexExternalCommandDataIndexerTest.kt | 1 | 12227 | package nl.hannahsten.texifyidea.index.file
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.indexing.FileContent
import nl.hannahsten.texifyidea.file.LatexSourceFileType
class LatexExternalCommandDataIndexerTest : BasePlatformTestCase() {
fun testOneMacroOneLine() {
val text = """
%\begin{macro}{\gram}
% The gram is an odd unit as it is needed for the base unit kilogram.
% \begin{macrocode}
\DeclareSIUnit \gram { g }
% \end{macrocode}
%\end{macro}
""".trimIndent()
val file = myFixture.configureByText("siunitx.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals("The gram is an odd unit as it is needed for the base unit kilogram.", map["\\gram"])
}
fun testOneMacroTwoLines() {
val text = """
% \begin{macro}{\MacroTopsep}
% Here is the default value for the |\MacroTopsep| parameter
% used above.
% \begin{macrocode}
\newskip\MacroTopsep \MacroTopsep = 7pt plus 2pt minus 2pt
% \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifblank@line}
% \begin{macro}{\blank@linetrue}
% \begin{macro}{\blank@linefalse}
% |\ifblank@line| is the switch used in the definition above.
% In the original \textsf{verbatim} environment the |\if@tempswa|
% switch is used. This is dangerous because its value may change
% while processing lines in the \textsf{macrocode} environment.
% \begin{macrocode}
\newif\ifblank@line
% \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
""".trimIndent()
val file = myFixture.configureByText("doc.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(1, map.size)
assertEquals("Here is the default value for the \\MacroTopsep parameter<br> used above.", map["\\MacroTopsep"])
}
fun testDoubleMacroDefinition() {
val text = """
%
%
% \begin{macro}{\MacrocodeTopsep}
% \begin{macro}{\MacroIndent}
% In the code above, we have used two registers. Therefore we have
% to allocate them. The default values might be overwritten with
% the help of the |\DocstyleParms| macro.
% \changes{v1.5s}{1989/11/05}{Support for code line no. (Undoc)}
% \changes{v1.5y}{1990/02/24}{Default changed.}
% \changes{v1.6b}{1990/06/15}{\cs{rm} moved before \cs{scriptsize} to avoid unnecessary fontwarning.}
% \begin{macrocode}
\newskip\MacrocodeTopsep \MacrocodeTopsep = 3pt plus 1.2pt minus 1pt
\newdimen\MacroIndent
\settowidth\MacroIndent{\rmfamily\scriptsize 00\ }
% \end{macrocode}
% \end{macro}
% \end{macro}
%
%
""".trimIndent()
val file = myFixture.configureByText("doc.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(2, map.size)
assertEquals("In the code above, we have used two registers. Therefore we have<br> to allocate them. The default values might be overwritten with<br> the help of the \\DocstyleParms macro.", map["\\MacrocodeTopsep"])
assertEquals(map["\\MacrocodeTopsep"], map["\\MacroIndent"])
}
fun testDoubleMacroDefinition2() {
val text = """
%
%
% \begin{macro}{\endmacro}
% \begin{macro}{\endenvironment}
% Older releases of this environment omit the |\endgroup| token,
% when being nested. This was done to avoid unnecessary stack usage.
% However it does not work if \textsf{macro} and
% \textsf{environment} environments are mixed, therefore we now
% use a simpler approach.
% \changes{v1.5k}{1989/08/17}{Fix for save stack problem.}
% \changes{v1.9k}{1994/02/22}{Don't checkfor nesting}
% \begin{macrocode}
\let\endmacro \endtrivlist
\let\endenvironment\endmacro
% \end{macrocode}
% \end{macro}
% \end{macro}
%
""".trimIndent()
val file = myFixture.configureByText("doc.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(2, map.size)
assertEquals("Older releases of this environment omit the \\endgroup token,<br> when being nested. This was done to avoid unnecessary stack usage.<br> However it does not work if <tt>macro</tt> and<br> <tt>environment</tt> environments are mixed, therefore we now<br> use a simpler approach.", map["\\endenvironment"])
assertEquals(map["\\endenvironment"], map["\\endmacro"])
}
fun testDescribeMacro() {
val text = """
% \subsection{Describing the usage of new macros}
%
% \DescribeMacro\DescribeMacro
% \changes{v1.7c}{1992/03/26}{Added.}
% When you describe a new macro you may use |DescribeMacro| to
% indicate that at this point the usage of a specific macro is
% explained. It takes one argument which will be printed in the margin
% and also produces a special index entry. For example, I used
% <redacted> to make clear that this is the
% point where the usage of |DescribeMacro| is explained.
%
% \DescribeMacro{\DescribeEnv}
% An analogous macro |\DescribeEnv| should be used to indicate
% that a \LaTeX{} environment is explained. It will produce a somewhat
% different index entry. Below I used |\DescribeEnv{verbatim}|.
%
""".trimIndent()
val file = myFixture.configureByText("doc.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(2, map.size)
assertEquals("When you describe a new macro you may use DescribeMacro to<br> indicate that at this point the usage of a specific macro is<br> explained. It takes one argument which will be printed in the margin<br> and also produces a special index entry. For example, I used<br> <redacted> to make clear that this is the<br> point where the usage of DescribeMacro is explained.", map["\\DescribeMacro"])
assertEquals("An analogous macro \\DescribeEnv should be used to indicate<br> that a \\LaTeX{} environment is explained. It will produce a somewhat<br> different index entry. Below I used \\DescribeEnv{verbatim}.", map["\\DescribeEnv"])
}
fun testDescribeMacros() {
val text = """
% \DescribeMacro\DontCheckModules \DescribeMacro\CheckModules
% \DescribeMacro\Module \DescribeMacro\AltMacroFont The `module'
% directives of the \textsf{docstrip} system \cite{art:docstrip} are
% normally recognised and invoke special formatting.
%
""".trimIndent()
val file = myFixture.configureByText("doc.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(4, map.size)
assertEquals("The `module'<br> directives of the <tt>docstrip</tt> system are<br> normally recognised and invoke special formatting.", map["\\DontCheckModules"])
assertEquals(map["\\CheckModules"], map["\\DontCheckModules"])
assertEquals(map["\\Module"], map["\\DontCheckModules"])
assertEquals(map["\\AltMacroFont"], map["\\DontCheckModules"])
}
fun testDeclareCommand() {
val text = """
happy, if
% \cs{autoref} starts a paragraph.
% \begin{macrocode}
\DeclareRobustCommand*{\autoref}{%
\leavevmode
\@ifstar{\HyRef@autoref\@gobbletwo}{\HyRef@autoref\hyper@@link}%
}
\def\HyRef@autoref#1#2{%
\begingroup
""".trimIndent()
val file = myFixture.configureByText("hyperref.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(1, map.size)
assertEquals("", map["\\autoref"])
}
fun testFakeDescribeMacro() {
val text = """
% \DescribeMacro{\begin\{seriate\}} \DescribeMacro{\end\{seriate\}}
% |Blah blah blah|\par
% |\begin{seriate}|\par
% | \item first item,|\par
% | \item second item.|\par
% |\end{seriate}|\par
% |Blah blah blah|\par\vspace{0.6em}
% \noindent results in:\par\vspace{0.6em}
% |Blah blah blah (a) first item, (b) second item. Blah blah blah|
%
""".trimIndent()
val file = myFixture.configureByText("apa6.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(0, map.size)
}
fun testAmsmath() {
val text = """
%
% \begin{macro}{\DeclareMathOperator}
% The command \cn{DeclareMathOperator} defines the first argument to
% be an operator name whose text is the second argument. The star
% form means that the operator name should take limits (like \cn{max}
% or \cn{lim}).
% \begin{macrocode}
\newcommand{\DeclareMathOperator}{%
\@ifstar{\@declmathop m}{\@declmathop o}}
% \end{macrocode}
% \end{macro}
""".trimIndent()
val file = myFixture.configureByText("amsopn.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals("The command <tt>\\DeclareMathOperator</tt> defines the first argument to<br> be an operator name whose text is the second argument. The star<br> form means that the operator name should take limits (like <tt>\\max</tt><br> or <tt>\\lim</tt>).", map["\\DeclareMathOperator"])
}
fun testDeclareTextSymbol() {
val text = """
\DeclareTextSymbol{\textless}{T1}{`\<}
\DeclareTextSymbol{\textquestiondown}{T1}{190}
\DeclareTextCommand{\textdollar}{OT1}{\hmode@bgroup
\ifdim \fontdimen\@ne\font >\z@
\slshape
\else
\upshape
\fi
\char`\${'$'}\egroup}
""".trimIndent()
val file = myFixture.configureByText("ltoutenc.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(3, map.size)
assertEquals("", map["\\textless"])
}
fun testDef() {
val text = """
\blank@linefalse \def\par{\ifblank@line
\leavevmode\fi
\blank@linetrue\@@par
\penalty\interlinepenalty}
""".trimIndent()
val file = myFixture.configureByText("doc.dtx", text)
val map = LatexExternalCommandDataIndexer().map(MockContent(file))
assertEquals(1, map.size)
assertEquals("", map["\\par"])
}
class MockContent(val file: PsiFile) : FileContent {
override fun <T : Any?> getUserData(key: Key<T>): T? { return null }
override fun <T : Any?> putUserData(key: Key<T>, value: T?) { }
override fun getFileType() = LatexSourceFileType
override fun getFile(): VirtualFile = file.virtualFile
override fun getFileName() = "test"
override fun getProject() = file.project
override fun getContent() = ByteArray(0)
override fun getContentAsText(): CharSequence = file.text
override fun getPsiFile() = file
}
} | mit |
AgileVentures/MetPlus_resumeCruncher | core/src/test/kotlin/org/metplus/cruncher/resume/ResumeFileRepositoryFakeTest.kt | 1 | 237 | package org.metplus.cruncher.resume
class ResumeFileRepositoryFakeTest : ResumeFileRepositoryTest() {
private val repo = ResumeFileRepositoryFake()
override fun getRepository(): ResumeFileRepository {
return repo
}
} | gpl-3.0 |
FHannes/intellij-community | uast/uast-common/src/org/jetbrains/uast/internal/implementationUtils.kt | 8 | 1045 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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 org.jetbrains.uast.internal
import org.jetbrains.uast.UElement
import org.jetbrains.uast.visitor.UastVisitor
fun List<UElement>.acceptList(visitor: UastVisitor) {
for (element in this) {
element.accept(visitor)
}
}
@Suppress("unused")
inline fun <reified T : UElement> T.log(text: String = ""): String {
val className = T::class.java.simpleName
return if (text.isEmpty()) className else "$className ($text)"
} | apache-2.0 |
android/animation-samples | Motion/app/src/main/java/com/example/android/motion/demo/dissolve/DissolveViewModel.kt | 1 | 1073 | /*
* Copyright 2019 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.example.android.motion.demo.dissolve
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import com.example.android.motion.model.Cheese
class DissolveViewModel : ViewModel() {
private val position = MutableLiveData(0)
val image = position.map { p -> Cheese.IMAGES[p % Cheese.IMAGES.size] }
fun nextImage() {
position.value?.let { position.value = it + 1 }
}
}
| apache-2.0 |
FHannes/intellij-community | uast/uast-common/src/org/jetbrains/uast/expressions/UArrayAccessExpression.kt | 8 | 1717 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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 org.jetbrains.uast
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* Represents `receiver[index0, ..., indexN]` expression.
*/
interface UArrayAccessExpression : UExpression {
/**
* Returns the receiver expression.
*/
val receiver: UExpression
/**
* Returns the list of index expressions.
*/
val indices: List<UExpression>
override fun accept(visitor: UastVisitor) {
if (visitor.visitArrayAccessExpression(this)) return
annotations.acceptList(visitor)
receiver.accept(visitor)
indices.acceptList(visitor)
visitor.afterVisitArrayAccessExpression(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) =
visitor.visitArrayAccessExpression(this, data)
override fun asLogString() = log()
override fun asRenderString() = receiver.asRenderString() +
indices.joinToString(prefix = "[", postfix = "]") { it.asRenderString() }
} | apache-2.0 |
gotev/android-upload-service | uploadservice/src/main/java/net/gotev/uploadservice/network/HttpRequest.kt | 2 | 1967 | package net.gotev.uploadservice.network
import java.io.Closeable
import java.io.IOException
import net.gotev.uploadservice.data.NameValue
interface HttpRequest : Closeable {
/**
* Delegate called when the body is ready to be written.
*/
interface RequestBodyDelegate {
/**
* Handles the writing of the request body.
* @param bodyWriter object with which to write on the body
* @throws IOException if an error occurs while writing the body
*/
@Throws(IOException::class)
fun onWriteRequestBody(bodyWriter: BodyWriter)
}
/**
* Set request headers.
* @param requestHeaders request headers to set
* @throws IOException if an error occurs while setting request headers
* @return instance
*/
@Throws(IOException::class)
fun setHeaders(requestHeaders: List<NameValue>): HttpRequest
/**
* Sets the total body bytes.
* @param totalBodyBytes total number of bytes
* @param isFixedLengthStreamingMode true if the fixed length streaming mode must be used. If
* it's false, chunked streaming mode has to be used.
* https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88
* @return instance
*/
fun setTotalBodyBytes(totalBodyBytes: Long, isFixedLengthStreamingMode: Boolean): HttpRequest
/**
* Gets the server response.
* @return object containing the server response status, headers and body.
* @param delegate delegate which handles the writing of the request body
* @param listener listener which gets notified when bytes are written and which controls if
* the transfer should continue
* @throws IOException if an error occurs while getting the server response
* @return response from server
*/
@Throws(IOException::class)
fun getResponse(
delegate: RequestBodyDelegate,
listener: BodyWriter.OnStreamWriteListener
): ServerResponse
}
| apache-2.0 |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/MainActivity.kt | 1 | 8914 | /*****************************************************************************
* MainActivity.java
*
* Copyright © 2011-2019 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc.gui
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.TypedValue
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import androidx.appcompat.view.ActionMode
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.toolbar.*
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.resources.*
import org.videolan.tools.*
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.R
import org.videolan.vlc.StartActivity
import org.videolan.vlc.extensions.ExtensionManagerService
import org.videolan.vlc.extensions.ExtensionsManager
import org.videolan.vlc.gui.audio.AudioBrowserFragment
import org.videolan.vlc.gui.browser.BaseBrowserFragment
import org.videolan.vlc.gui.browser.ExtensionBrowser
import org.videolan.vlc.gui.helpers.INavigator
import org.videolan.vlc.gui.helpers.Navigator
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.gui.video.VideoGridFragment
import org.videolan.vlc.interfaces.Filterable
import org.videolan.vlc.interfaces.IRefreshable
import org.videolan.vlc.media.MediaUtils
import org.videolan.vlc.reloadLibrary
import org.videolan.vlc.util.Permissions
import org.videolan.vlc.util.Util
private const val TAG = "VLC/MainActivity"
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
class MainActivity : ContentActivity(),
ExtensionManagerService.ExtensionManagerActivity,
INavigator by Navigator()
{
var refreshing: Boolean = false
set(value) {
mainLoading.visibility = if (value) View.VISIBLE else View.GONE
field = value
}
private lateinit var mediaLibrary: Medialibrary
private var scanNeeded = false
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Util.checkCpuCompatibility(this)
/*** Start initializing the UI */
setContentView(R.layout.main)
initAudioPlayerContainerActivity()
setupNavigation(savedInstanceState)
if (savedInstanceState == null) Permissions.checkReadStoragePermission(this)
/* Set up the action bar */
prepareActionBar()
/* Reload the latest preferences */
scanNeeded = savedInstanceState == null && settings.getBoolean(KEY_MEDIALIBRARY_AUTO_RESCAN, true)
if (BuildConfig.DEBUG) extensionsManager = ExtensionsManager.getInstance()
mediaLibrary = Medialibrary.getInstance()
val color = TypedValue().run {
theme.resolveAttribute(R.attr.progress_indeterminate_tint, this, true)
data
}
mainLoadingProgress.indeterminateDrawable.setColorFilter(color, android.graphics.PorterDuff.Mode.SRC_IN)
}
private fun prepareActionBar() {
supportActionBar?.run {
setDisplayHomeAsUpEnabled(false)
setHomeButtonEnabled(false)
setDisplayShowTitleEnabled(!AndroidDevices.isPhone)
}
}
override fun onStart() {
super.onStart()
if (mediaLibrary.isInitiated) {
/* Load media items from database and storage */
if (scanNeeded && Permissions.canReadStorage(this)) this.reloadLibrary()
}
}
override fun onStop() {
super.onStop()
if (changingConfigurations == 0) {
/* Check for an ongoing scan that needs to be resumed during onResume */
scanNeeded = mediaLibrary.isWorking
}
}
override fun onSaveInstanceState(outState: Bundle) {
val current = currentFragment
if (current !is ExtensionBrowser) supportFragmentManager.putFragment(outState, "current_fragment", current!!)
outState.putInt(EXTRA_TARGET, currentFragmentId)
super.onSaveInstanceState(outState)
}
override fun onRestart() {
super.onRestart()
/* Reload the latest preferences */
reloadPreferences()
}
@TargetApi(Build.VERSION_CODES.N)
override fun onBackPressed() {
/* Close playlist search if open or Slide down the audio player if it is shown entirely. */
if (isAudioPlayerReady && (audioPlayer.backPressed() || slideDownAudioPlayer()))
return
// If it's the directory view, a "backpressed" action shows a parent.
val fragment = currentFragment
if (fragment is BaseBrowserFragment && fragment.goBack()) {
return
} else if (fragment is ExtensionBrowser) {
fragment.goBack()
return
}
if (AndroidUtil.isNougatOrLater && isInMultiWindowMode) {
UiTools.confirmExit(this)
return
}
finish()
}
override fun startSupportActionMode(callback: ActionMode.Callback): ActionMode? {
appBarLayout.setExpanded(true)
return super.startSupportActionMode(callback)
}
/**
* Handle onClick form menu buttons
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId != R.id.ml_menu_filter) UiTools.setKeyboardVisibility(appBarLayout, false)
// Handle item selection
return when (item.itemId) {
// Refresh
R.id.ml_menu_refresh -> {
forceRefresh()
true
}
android.R.id.home ->
// Slide down the audio player or toggle the sidebar
slideDownAudioPlayer()
else -> super.onOptionsItemSelected(item)
}
}
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
return if (currentFragment is Filterable) {
(currentFragment as Filterable).allowedToExpand()
} else false
}
fun forceRefresh() {
forceRefresh(currentFragment)
}
private fun forceRefresh(current: Fragment?) {
if (!mediaLibrary.isWorking) {
if (current != null && current is IRefreshable)
(current as IRefreshable).refresh()
else
reloadLibrary()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ACTIVITY_RESULT_PREFERENCES) {
when (resultCode) {
RESULT_RESCAN -> this.reloadLibrary()
RESULT_RESTART, RESULT_RESTART_APP -> {
val intent = Intent(this@MainActivity, if (resultCode == RESULT_RESTART_APP) StartActivity::class.java else MainActivity::class.java)
finish()
startActivity(intent)
}
RESULT_UPDATE_SEEN_MEDIA -> for (fragment in supportFragmentManager.fragments)
if (fragment is VideoGridFragment)
fragment.updateSeenMediaMarker()
RESULT_UPDATE_ARTISTS -> {
val fragment = currentFragment
if (fragment is AudioBrowserFragment) fragment.viewModel.refresh()
}
}
} else if (requestCode == ACTIVITY_RESULT_OPEN && resultCode == Activity.RESULT_OK) {
MediaUtils.openUri(this, data!!.data)
} else if (requestCode == ACTIVITY_RESULT_SECONDARY) {
if (resultCode == RESULT_RESCAN) {
forceRefresh(currentFragment)
}
}
}
// Note. onKeyDown will not occur while moving within a list
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
toolbar.menu.findItem(R.id.ml_menu_filter).expandActionView()
}
return super.onKeyDown(keyCode, event)
}
}
| gpl-2.0 |
misaochan/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/explore/PageableBaseDataSourceTest.kt | 8 | 2806 | package fr.free.nrw.commons.explore
import androidx.lifecycle.LiveData
import androidx.paging.PagedList
import com.nhaarman.mockitokotlin2.*
import fr.free.nrw.commons.explore.depictions.search.LoadFunction
import fr.free.nrw.commons.explore.paging.LiveDataConverter
import fr.free.nrw.commons.explore.paging.PageableBaseDataSource
import fr.free.nrw.commons.explore.paging.PagingDataSourceFactory
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
class PageableBaseDataSourceTest {
@Mock
private lateinit var liveDataConverter: LiveDataConverter
private lateinit var pageableBaseDataSource: PageableBaseDataSource<String>
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
pageableBaseDataSource = object: PageableBaseDataSource<String>(liveDataConverter){
override val loadFunction: LoadFunction<String>
get() = mock()
}
}
@Test
fun `onQueryUpdated emits new liveData`() {
val (_, liveData) = expectNewLiveData()
pageableBaseDataSource.pagingResults.test()
.also { pageableBaseDataSource.onQueryUpdated("test") }
.assertValue(liveData)
}
@Test
fun `onQueryUpdated invokes livedatconverter with no items emitter`() {
val (zeroItemsFuncCaptor, _) = expectNewLiveData()
pageableBaseDataSource.onQueryUpdated("test")
pageableBaseDataSource.noItemsLoadedQueries.test()
.also { zeroItemsFuncCaptor.firstValue.invoke() }
.assertValue("test")
}
/*
* Just for coverage, no way to really assert this
* */
@Test
fun `retryFailedRequest does nothing without a factory`() {
pageableBaseDataSource.retryFailedRequest()
}
@Test
@Ignore("Rewrite with Mockk constructor mocks")
fun `retryFailedRequest retries with a factory`() {
val (_, _, dataSourceFactoryCaptor) = expectNewLiveData()
pageableBaseDataSource.onQueryUpdated("test")
val dataSourceFactory = spy(dataSourceFactoryCaptor.firstValue)
pageableBaseDataSource.retryFailedRequest()
verify(dataSourceFactory).retryFailedRequest()
}
private fun expectNewLiveData(): Triple<KArgumentCaptor<() -> Unit>, LiveData<PagedList<String>>, KArgumentCaptor<PagingDataSourceFactory<String>>> {
val captor = argumentCaptor<() -> Unit>()
val dataSourceFactoryCaptor = argumentCaptor<PagingDataSourceFactory<String>>()
val liveData: LiveData<PagedList<String>> = mock()
whenever(liveDataConverter.convert(dataSourceFactoryCaptor.capture(), captor.capture()))
.thenReturn(liveData)
return Triple(captor, liveData, dataSourceFactoryCaptor)
}
}
| apache-2.0 |
AoEiuV020/PaNovel | api/src/test/java/cc/aoeiuv020/panovel/api/site/SiFangTest.kt | 1 | 1317 | package cc.aoeiuv020.panovel.api.site
import org.junit.Test
/**
* Created by AoEiuV020 on 2019.10.13-13:50:00.
*/
class SiFangTest : BaseNovelContextText(SiFang::class) {
@Test
fun search() {
search("逆风岁月", "君尽欢", "20")
}
@Test
fun detail() {
detail("20", "20", "逆风岁月", "君尽欢",
"http://www.sifangbook.com/uploads/20180724/4cf6966367c66aef17091409b493c895.jpg",
"当曾经的谎言破碎在手中,原本一心想逃离家族的俞南思不得不停下脚步。为夺回母亲该有的一切,她甚至不惜踏上违背初心的路。而赫北书,无论曾经现在,虚无的皮囊,内心下依然隐藏着恶魔,肆无忌惮。\n" +
"开始的二人,命途相似,做的却都不是真实的自...",
"2018-12-24 23:49:32")
}
@Test
fun chapters() {
chapters("20", "001:关于俞家", "712", null,
"140:圆满结局", "5543", "2018-12-24 23:49:32",
140)
}
@Test
fun content() {
content("712",
"三月,是雨最肆意的时节。",
"想到这儿,俞南思不屑地笑了笑,这种鬼话父亲也信,真是傻透了。",
56)
}
} | gpl-3.0 |
d3xter/bo-android | app/src/main/java/org/blitzortung/android/map/overlay/FadeOverlay.kt | 1 | 1351 | /*
Copyright 2015 Andreas Würl
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 org.blitzortung.android.map.overlay
import android.graphics.Canvas
import android.graphics.Paint
import com.google.android.maps.MapView
import com.google.android.maps.Overlay
import org.blitzortung.android.map.overlay.color.ColorHandler
class FadeOverlay(private val colorHandler: ColorHandler) : Overlay() {
private var alphaValue = 0
override fun draw(canvas: Canvas?, mapView: MapView?, shadow: Boolean) {
if (!shadow) {
val rect = canvas!!.clipBounds
val paint = Paint()
paint.color = colorHandler.backgroundColor
paint.alpha = alphaValue
canvas.drawRect(rect, paint)
}
}
fun setAlpha(alphaValue: Int) {
this.alphaValue = alphaValue
}
}
| apache-2.0 |
arturbosch/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Detektion.kt | 1 | 888 | package io.gitlab.arturbosch.detekt.api
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
/**
* Storage for all kinds of findings and additional information
* which needs to be transferred from the detekt engine to the user.
*/
interface Detektion {
val findings: Map<RuleSetId, List<Finding>>
val notifications: Collection<Notification>
val metrics: Collection<ProjectMetric>
/**
* Retrieves a value stored by the given key of the result.
*/
fun <V> getData(key: Key<V>): V?
/**
* Stores an arbitrary value inside the result bound to the given key.
*/
fun <V> addData(key: Key<V>, value: V)
/**
* Stores a notification in the result.
*/
fun add(notification: Notification)
/**
* Stores a metric calculated for the whole project in the result.
*/
fun add(projectMetric: ProjectMetric)
}
| apache-2.0 |
Reline/Onigokko | onigokko/src/main/java/com/reline/tag/database/SqlBriteDao.kt | 1 | 456 | package com.reline.tag.database
import android.content.SharedPreferences
import com.squareup.sqlbrite.BriteDatabase
class SqlBriteDao(val briteDatabase: BriteDatabase, val sharedPreferences: SharedPreferences): DatabaseAccessObject {
private val TOKEN = "TOKEN"
override fun getToken(): String = sharedPreferences.getString(TOKEN, String())
override fun saveToken(token: String) = sharedPreferences.edit().putString(TOKEN, token).apply()
} | mit |
JDA-Applications/Kotlin-JDA | src/main/kotlin/club/minnced/kjda/KJDAClientBuilder.kt | 1 | 4628 | /*
* Copyright 2016 - 2017 Florian Spieß
*
* 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.
*/
@file:JvmName("KJDAClientBuilder")
package club.minnced.kjda
import com.neovisionaries.ws.client.WebSocketFactory
import net.dv8tion.jda.core.AccountType
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.JDABuilder
import net.dv8tion.jda.core.OnlineStatus
import net.dv8tion.jda.core.audio.factory.IAudioSendFactory
import net.dv8tion.jda.core.entities.Game
import net.dv8tion.jda.core.hooks.IEventManager
import okhttp3.OkHttpClient
/**
* Constructs a new [JDABuilder] and applies the specified
* init function `() -> Unit` to that receiver.
* This uses [JDABuilder.buildAsync]
*
* The token is not required here, however needs to be configured in the given function!
*
* @param[accountType]
* The [AccountType] for the account being issued for creation
* @param[init]
* The function which uses the constructed JDABuilder as receiver to setup
* the JDA information before building it
*
* @sample client
*
* @see JDABuilder
*/
fun client(accountType: AccountType, init: JDABuilder.() -> Unit): JDA {
val builder = JDABuilder(accountType)
builder.init()
return builder.buildAsync()
}
/** Lazy infix overload for [JDABuilder.setToken] */
infix inline fun <reified T: JDABuilder> T.token(lazyToken: () -> String): T
= this.setToken(lazyToken()) as T
/** Lazy infix overload for [JDABuilder.setGame] */
infix inline fun <reified T: JDABuilder> T.game(lazy: () -> String): T
= this.setGame(Game.of(lazy())) as T
/** Lazy infix overload for [JDABuilder.setStatus] */
infix inline fun <reified T: JDABuilder> T.status(lazy: () -> OnlineStatus): T
= this.setStatus(lazy()) as T
/** Lazy infix overload for [JDABuilder.setEventManager] */
infix inline fun <reified T: JDABuilder> T.manager(lazy: () -> IEventManager): T
= this.setEventManager(lazy()) as T
/** Lazy infix overload for [JDABuilder.addEventListener] */
infix inline fun <reified T: JDABuilder> T.listener(lazy: () -> Any): T
= this.addEventListener(lazy()) as T
/** Lazy infix overload for [JDABuilder.setAudioSendFactory] */
infix inline fun <reified T: JDABuilder> T.audioSendFactory(lazy: () -> IAudioSendFactory): T
= this.setAudioSendFactory(lazy()) as T
/** Infix overload for [JDABuilder.setIdle] */
infix inline fun <reified T: JDABuilder> T.idle(lazy: Boolean): T
= this.setIdle(lazy) as T
/** Infix overload for [JDABuilder.setEnableShutdownHook] */
infix inline fun <reified T: JDABuilder> T.shutdownHook(lazy: Boolean): T
= this.setEnableShutdownHook(lazy) as T
/** Infix overload for [JDABuilder.setAudioEnabled] */
infix inline fun <reified T: JDABuilder> T.audio(lazy: Boolean): T
= this.setAudioEnabled(lazy) as T
/** Infix overload for [JDABuilder.setAutoReconnect] */
infix inline fun <reified T: JDABuilder> T.autoReconnect(lazy: Boolean): T
= this.setAutoReconnect(lazy) as T
/**
* Provides new WebSocketFactory and calls the provided lazy
* initializer to allow setting options like timeouts
*/
infix inline fun <reified T: JDABuilder> T.websocketSettings(init: WebSocketFactory.() -> Unit): T {
val factory = WebSocketFactory()
factory.init()
setWebsocketFactory(factory)
return this
}
/**
* Provides new OkHttpClient.Builder and calls the provided lazy
* initializer to allow setting options like timeouts
*/
infix inline fun <reified T: JDABuilder> T.httpSettings(init: OkHttpClient.Builder.() -> Unit): T {
val builder = OkHttpClient.Builder()
builder.init()
setHttpClientBuilder(builder)
return this
}
/** Overload for [JDABuilder.addEventListener] */
inline fun <reified T: JDABuilder> T.listener(vararg listener: Any): T
= this.addEventListener(*listener) as T
/** Overload for [JDABuilder.removeEventListener] */
inline fun <reified T: JDABuilder> T.removeListener(vararg listener: Any): T
= this.removeEventListener(*listener) as T
/** Operator overload for [JDABuilder.addEventListener] */
inline operator fun <reified T: JDABuilder> T.plusAssign(other: Any) { listener(other) }
| apache-2.0 |
adrcotfas/Goodtime | app/src/main/java/com/apps/adrcotfas/goodtime/statistics/SessionViewModel.kt | 1 | 2755 | /*
* Copyright 2016-2019 Adrian Cotfas
*
* 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.apps.adrcotfas.goodtime.statistics
import com.apps.adrcotfas.goodtime.database.SessionDao
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.apps.adrcotfas.goodtime.database.AppDatabase
import com.apps.adrcotfas.goodtime.database.Session
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.ZoneId
import javax.inject.Inject
@HiltViewModel
class SessionViewModel @Inject constructor(
database: AppDatabase
) : ViewModel() {
private val dao: SessionDao = database.sessionModel()
val allSessions: LiveData<List<Session>>
get() = dao.allSessions
val allSessionsUnlabeled: LiveData<List<Session>>
get() = dao.allSessionsUnlabeled
val allSessionsUnarchived: LiveData<List<Session>>
get() = dao.allSessionsUnarchived
fun getAllSessionsUnarchived(startMillis: Long, endMillis: Long): LiveData<List<Session>>
= dao.getAllSessionsUnarchived(startMillis, endMillis)
fun getSession(id: Long): LiveData<Session> {
return dao.getSession(id)
}
fun addSession(session: Session) {
viewModelScope.launch(Dispatchers.IO) {
dao.addSession(session)
}
}
fun editSession(session: Session) {
viewModelScope.launch(Dispatchers.IO) {
dao.editSession(
session.id, session.timestamp, session.duration, session.label
)
}
}
fun editLabel(id: Long?, label: String?) {
viewModelScope.launch(Dispatchers.IO) {
dao.editLabel(
id!!, label
)
}
}
fun deleteSession(id: Long) {
viewModelScope.launch(Dispatchers.IO) {
dao.deleteSession(id)
}
}
fun deleteSessionsFinishedAfter(timestamp: Long) {
viewModelScope.launch(Dispatchers.IO) {
dao.deleteSessionsAfter(timestamp)
}
}
fun getSessions(label: String): LiveData<List<Session>> {
return dao.getSessions(label)
}
} | apache-2.0 |
ofalvai/BPInfo | app/src/main/java/com/ofalvai/bpinfo/api/bkkfutar/RouteContract.kt | 1 | 1019 | /*
* Copyright 2018 Olivér Falvai
*
* 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.ofalvai.bpinfo.api.bkkfutar
internal interface RouteContract {
companion object {
const val ROUTE_ID = "id"
const val ROUTE_SHORT_NAME = "shortName"
const val ROUTE_LONG_NAME = "longName"
const val ROUTE_DESC = "description"
const val ROUTE_TYPE = "type"
const val ROUTE_COLOR = "color"
const val ROUTE_TEXT_COLOR = "textColor"
}
} | apache-2.0 |
marciogranzotto/mqtt-painel-kotlin | app/src/main/java/com/granzotto/mqttpainel/activities/MainActivity.kt | 1 | 1502 | package com.granzotto.mqttpainel.activities
import android.os.Bundle
import com.granzotto.mqttpainel.R
import com.granzotto.mqttpainel.models.ConnectionObj
import com.granzotto.mqttpainel.presenters.MainPresenter
import com.pawegio.kandroid.textWatcher
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.startActivity
class MainActivity: BaseActivity() {
companion object {
const val CONNECTION_OBJ = "connection_object"
}
private var presenter: MainPresenter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
presenter = MainPresenter(this)
setUpTextWatchers()
connectButton.setOnClickListener { presenter?.onConnectButtonClicked() }
presenter?.onIntentExtras(intent?.extras?.getParcelable<ConnectionObj>(CONNECTION_OBJ))
presenter?.onCreate()
}
override fun onDestroy() {
presenter?.onDestroy()
super.onDestroy()
}
private fun setUpTextWatchers() {
etServer.textWatcher {
afterTextChanged { text ->
presenter?.onServerTextChanged(text.toString())
}
}
etPort.textWatcher {
afterTextChanged { text ->
presenter?.onPortTextChanged(text.toString())
}
}
}
fun goToDashboardScreen() {
startActivity<DashboardActivity>()
finish()
}
} | gpl-3.0 |
nemerosa/ontrack | ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLRootQueryIndicatorPortfolioOfPortfolios.kt | 1 | 1011 | package net.nemerosa.ontrack.extension.indicators.ui.graphql
import graphql.schema.GraphQLFieldDefinition
import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorPortfolioService
import net.nemerosa.ontrack.graphql.schema.GQLRootQuery
import org.springframework.stereotype.Component
@Component
class GQLRootQueryIndicatorPortfolioOfPortfolios(
private val indicatorPortfolioOfPortfolios: GQLTypeIndicatorPortfolioOfPortfolios,
private val indicatorPortfolioService: IndicatorPortfolioService
) : GQLRootQuery {
override fun getFieldDefinition(): GraphQLFieldDefinition =
GraphQLFieldDefinition.newFieldDefinition()
.name("indicatorPortfolioOfPortfolios")
.description("List of all portfolios")
.type(indicatorPortfolioOfPortfolios.typeRef)
.dataFetcher {
indicatorPortfolioService.getPortfolioOfPortfolios()
}
.build()
} | mit |
chimbori/crux | src/main/kotlin/com/chimbori/crux/plugins/FaviconExtractor.kt | 1 | 849 | package com.chimbori.crux.plugins
import com.chimbori.crux.api.Extractor
import com.chimbori.crux.api.Fields.FAVICON_URL
import com.chimbori.crux.api.Resource
import com.chimbori.crux.common.isLikelyArticle
import com.chimbori.crux.extractors.extractCanonicalUrl
import com.chimbori.crux.extractors.extractFaviconUrl
import okhttp3.HttpUrl
public class FaviconExtractor : Extractor {
/** Skip handling any file extensions that are unlikely to be HTML pages. */
public override fun canExtract(url: HttpUrl): Boolean = url.isLikelyArticle()
override suspend fun extract(request: Resource): Resource {
val canonicalUrl = request.document?.extractCanonicalUrl()?.let { request.url?.resolve(it) } ?: request.url
return Resource(metadata = mapOf(FAVICON_URL to request.document?.extractFaviconUrl(canonicalUrl))).removeNullValues()
}
}
| apache-2.0 |
goodwinnk/intellij-community | platform/platform-impl/src/com/intellij/internal/heatmap/actions/ShowHeatMapAction.kt | 1 | 22686 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.heatmap.actions
import com.intellij.internal.heatmap.fus.*
import com.intellij.internal.heatmap.settings.ClickMapSettingsDialog
import com.intellij.internal.statistic.beans.ConvertUsagesUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.JBPopupMenu
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.ui.JBColor
import com.intellij.ui.PopupMenuListenerAdapter
import com.intellij.util.PlatformUtils
import com.intellij.util.ui.UIUtil
import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.io.IOException
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import javax.swing.JComponent
import javax.swing.MenuSelectionManager
import javax.swing.event.PopupMenuEvent
private val BUTTON_EMPTY_STATS_COLOR: Color = JBColor.GRAY.brighter()
val LOG = Logger.getInstance(ShowHeatMapAction::class.java)
class ShowHeatMapAction : AnAction(), DumbAware {
companion object MetricsCache {
private val toolbarsAllMetrics = mutableListOf<MetricEntity>()
private val mainMenuAllMetrics = mutableListOf<MetricEntity>()
private val toolbarsMetrics = hashMapOf<String, List<MetricEntity>>()
private val mainMenuMetrics = hashMapOf<String, List<MetricEntity>>()
private val toolbarsTotalMetricsUsers = hashMapOf<String, Int>()
private val mainMenuTotalMetricsUsers = hashMapOf<String, Int>()
//settings
private var myEndStartDate: Pair<Date, Date>? = null
private var myShareType: ShareType? = null
private var myServiceUrl: String? = null
private val myBuilds = mutableListOf<String>()
private var myIncludeEap = false
private var myColor = Color.RED
private val ourIdeBuildInfos = mutableListOf<ProductBuildInfo>()
fun getOurIdeBuildInfos(): List<ProductBuildInfo> = ourIdeBuildInfos
fun getSelectedServiceUrl(): String = (myServiceUrl ?: DEFAULT_SERVICE_URLS.first()).trimEnd('/')
}
@Volatile
private var myToolBarProgress = false
@Volatile
private var myMainMenuProgress = false
private val ourBlackList = HashMap<String, String>()
private val PRODUCT_CODE = getProductCode()
init {
ourBlackList["com.intellij.ide.ReopenProjectAction"] = "Reopen Project"
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = isInProgress().not()
super.update(e)
}
private fun isInProgress(): Boolean = myToolBarProgress || myMainMenuProgress
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (ourIdeBuildInfos.isEmpty()) ourIdeBuildInfos.addAll(getProductBuildInfos(PRODUCT_CODE))
askSettingsAndPaintUI(project)
}
private fun askSettingsAndPaintUI(project: Project) {
val frame = WindowManagerEx.getInstance().getIdeFrame(project)
if (frame == null) return
val askSettings = ClickMapSettingsDialog(project)
val ok = askSettings.showAndGet()
if (ok.not()) return
val serviceUrl = askSettings.getServiceUrl()
if (serviceUrl == null) {
showWarnNotification("Statistics fetch failed", "Statistic Service url is not specified", project)
return
}
val startEndDate = askSettings.getStartEndDate()
val shareType = askSettings.getShareType()
val ideBuilds = askSettings.getBuilds()
val isIncludeEap = askSettings.getIncludeEap()
if (settingsChanged(startEndDate, shareType, serviceUrl, ideBuilds, isIncludeEap)) {
clearCache()
}
myServiceUrl = serviceUrl
myBuilds.clear()
myBuilds.addAll(ideBuilds)
myEndStartDate = startEndDate
myIncludeEap = isIncludeEap
myShareType = shareType
myColor = askSettings.getColor()
if (toolbarsAllMetrics.isNotEmpty()) {
paintVisibleToolBars(project, frame.component, shareType, toolbarsAllMetrics)
}
else {
val accessToken = askSettings.getAccessToken()
if (StringUtil.isEmpty(accessToken)) {
showWarnNotification("Statistics fetch failed", "access token is not specified", project)
return
}
val startDate = getDateString(startEndDate.first)
val endDate = getDateString(startEndDate.second)
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Fetching statistics for toolbar clicks", false) {
override fun run(indicator: ProgressIndicator) {
myToolBarProgress = true
val toolBarAllStats = fetchStatistics(startDate, endDate, PRODUCT_CODE, myBuilds, arrayListOf(TOOLBAR_GROUP), accessToken!!)
LOG.debug("\nGot Tool bar clicks stat: ${toolBarAllStats.size} rows:")
toolBarAllStats.forEach {
LOG.debug("Entity: $it")
}
if (toolBarAllStats.isNotEmpty()) toolbarsAllMetrics.addAll(toolBarAllStats)
paintVisibleToolBars(project, frame.component, shareType, toolBarAllStats)
myToolBarProgress = false
}
})
}
if (frame is IdeFrameImpl) {
if (mainMenuAllMetrics.isNotEmpty()) {
groupStatsByMenus(frame, mainMenuAllMetrics)
addMenusPopupListener(frame, shareType)
}
else {
val accessToken = askSettings.getAccessToken()
if (StringUtil.isEmpty(accessToken)) {
showWarnNotification("Statistics fetch failed", "access token is not specified", project)
return
}
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Fetching statistics for Main menu", false) {
override fun run(indicator: ProgressIndicator) {
myMainMenuProgress = true
val startDate = getDateString(startEndDate.first)
val endDate = getDateString(startEndDate.second)
val menuAllStats = fetchStatistics(startDate, endDate, PRODUCT_CODE, myBuilds, arrayListOf(MAIN_MENU_GROUP), accessToken!!)
if (menuAllStats.isNotEmpty()) {
mainMenuAllMetrics.addAll(menuAllStats)
groupStatsByMenus(frame, mainMenuAllMetrics)
addMenusPopupListener(frame, shareType)
}
myMainMenuProgress = false
}
})
}
}
}
private fun groupStatsByMenus(frame: IdeFrameImpl, mainMenuAllStats: List<MetricEntity>) {
val menus = frame.rootPane.jMenuBar.components
for (menu in menus) {
if (menu is ActionMenu) {
val menuName = menu.text
if (mainMenuMetrics[menuName] == null) {
val menuStats = filterByMenuName(mainMenuAllStats, menuName)
if (menuStats.isNotEmpty()) mainMenuMetrics[menuName] = menuStats
var menuAllUsers = 0
menuStats.forEach { menuAllUsers += it.users }
if (menuAllUsers > 0) mainMenuTotalMetricsUsers[menuName] = menuAllUsers
}
}
}
}
private fun paintActionMenu(menu: ActionMenu, allUsers: Int, level: Float) {
val menuName = menu.text
val menuAllUsers = mainMenuTotalMetricsUsers[menuName]
menu.component.background = tuneColor(myColor, level)
menu.addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
ActionMenu.showDescriptionInStatusBar(true, menu.component, "$menuName: $menuAllUsers usages of total $allUsers")
}
override fun mouseExited(e: MouseEvent?) {
ActionMenu.showDescriptionInStatusBar(true, menu.component, "")
}
})
}
private fun addMenusPopupListener(frame: IdeFrameImpl, shareType: ShareType) {
val menus = frame.rootPane.jMenuBar.components
var mainMenuAllUsers = 0
mainMenuTotalMetricsUsers.values.forEach { mainMenuAllUsers += it }
for (menu in menus) {
if (menu is ActionMenu) {
paintMenuAndAddPopupListener(mutableListOf(menu.text), menu, mainMenuAllUsers, shareType)
}
}
}
private fun paintMenuAndAddPopupListener(menuGroupNames: MutableList<String>, menu: ActionMenu, menuAllUsers: Int, shareType: ShareType) {
val level = if (menuGroupNames.size == 1) {
val subMenuAllUsers = mainMenuTotalMetricsUsers[menuGroupNames[0]] ?: 0
subMenuAllUsers / menuAllUsers.toFloat()
}
else {
val subItemsStas: List<MetricEntity> = getMenuSubItemsStat(menuGroupNames)
val maxUsers = subItemsStas.maxBy { m -> m.users }
if (maxUsers != null) getLevel(shareType, maxUsers, MetricGroup.MAIN_MENU) else 0.001f
}
paintActionMenu(menu, menuAllUsers, level)
val popupMenu = menu.popupMenu as? JBPopupMenu ?: return
popupMenu.addPopupMenuListener(object : PopupMenuListenerAdapter() {
override fun popupMenuWillBecomeVisible(e: PopupMenuEvent) {
val source = e.source as? JBPopupMenu ?: return
val menuStats = mainMenuMetrics[menuGroupNames[0]] ?: return
for (c in source.components) {
if (c is ActionMenuItem) {
paintMenuItem(c, menuGroupNames, menuStats, shareType)
}
else if (c is ActionMenu) {
val newMenuGroup = menuGroupNames.toMutableList()
newMenuGroup.add(newMenuGroup.lastIndex + 1, c.text)
paintMenuAndAddPopupListener(newMenuGroup, c, menuAllUsers, shareType)
}
}
}
})
}
private fun getMenuSubItemsStat(menuGroupNames: MutableList<String>): List<MetricEntity> {
val menuStat = mainMenuMetrics[menuGroupNames[0]] ?: emptyList()
val pathPrefix = convertMenuItemsToKey(menuGroupNames)
val result = mutableListOf<MetricEntity>()
menuStat.forEach { if (it.id.startsWith(pathPrefix)) result.add(it) }
return result
}
private fun paintMenuItem(menuItem: ActionMenuItem, menuGroupNames: List<String>, menuStats: List<MetricEntity>, shareType: ShareType) {
val pathPrefix = convertMenuItemsToKey(menuGroupNames)
val metricId = pathPrefix + MENU_ITEM_SEPARATOR + menuItem.text
val menuItemMetric: MetricEntity? = findMetric(menuStats, metricId)
if (menuItemMetric != null) {
val color = calcColorForMetric(shareType, menuItemMetric, MetricGroup.MAIN_MENU)
menuItem.isOpaque = true
menuItem.text = menuItem.text + " (${menuItemMetric.users} / ${getMetricPlaceTotalUsersCache(menuItemMetric, MetricGroup.MAIN_MENU)})"
menuItem.component.background = color
}
menuItem.addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
//adds text to status bar and searching metrics if it was not found (using the path from MenuSelectionManager)
val actionMenuItem = e.source
if (actionMenuItem is ActionMenuItem) {
val placeText = menuGroupNames.first()
val action = actionMenuItem.anAction
if (menuItemMetric != null) {
val textWithStat = getTextWithStat(menuItemMetric, shareType,
getMetricPlaceTotalUsersCache(menuItemMetric, MetricGroup.MAIN_MENU), placeText)
val actionText = StringUtil.notNullize(menuItem.anAction.templatePresentation.text)
ActionMenu.showDescriptionInStatusBar(true, menuItem, "$actionText: $textWithStat")
}
else {
val pathStr = getPathFromMenuSelectionManager(action)
if (pathStr != null) {
val metric = findMetric(menuStats, pathStr)
if (metric != null) {
actionMenuItem.isOpaque = true
actionMenuItem.component.background = calcColorForMetric(shareType, metric, MetricGroup.MAIN_MENU)
val textWithStat = getTextWithStat(metric, shareType, getMetricPlaceTotalUsersCache(metric, MetricGroup.MAIN_MENU),
placeText)
val actionText = StringUtil.notNullize(menuItem.anAction.templatePresentation.text)
ActionMenu.showDescriptionInStatusBar(true, menuItem, "$actionText: $textWithStat")
}
}
}
}
}
override fun mouseExited(e: MouseEvent?) {
ActionMenu.showDescriptionInStatusBar(true, menuItem, "")
}
})
}
private fun getPathFromMenuSelectionManager(action: AnAction): String? {
val groups = MenuSelectionManager.defaultManager().selectedPath.filterIsInstance<ActionMenu>().map { o -> o.text }.toMutableList()
if (groups.size > 0) {
val text = getActionText(action)
groups.add(text)
return convertMenuItemsToKey(groups)
}
return null
}
private fun convertMenuItemsToKey(menuItems: List<String>): String {
return menuItems.joinToString(MENU_ITEM_SEPARATOR)
}
private fun getActionText(action: AnAction): String {
return ourBlackList[action.javaClass.name] ?: action.templatePresentation.text
}
private fun settingsChanged(startEndDate: Pair<Date, Date>,
shareType: ShareType,
currentServiceUrl: String,
ideBuilds: List<String>,
includeEap: Boolean): Boolean {
if (currentServiceUrl != myServiceUrl) return true
if (includeEap != myIncludeEap) return true
if (ideBuilds.size != myBuilds.size) return true
for (build in ideBuilds) {
if (!myBuilds.contains(build)) return true
}
val prevStartEndDate = myEndStartDate
if (prevStartEndDate != null) {
if (!isSameDay(prevStartEndDate.first, startEndDate.first) || !isSameDay(prevStartEndDate.second, startEndDate.second)) {
return true
}
}
val prevShareType = myShareType
if (prevShareType != null && prevShareType != shareType) {
return true
}
return false
}
private fun isSameDay(date1: Date, date2: Date): Boolean {
val c1 = Calendar.getInstance()
val c2 = Calendar.getInstance()
c1.time = date1
c2.time = date2
return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR)
}
private fun paintVisibleToolBars(project: Project, component: JComponent, shareType: ShareType, toolBarStats: List<MetricEntity>) {
if (component is ActionToolbarImpl) paintToolBarButtons(component, shareType, toolBarStats)
for (c in component.components) {
when (c) {
is ActionToolbarImpl -> paintToolBarButtons(c, shareType, toolBarStats)
is JComponent -> paintVisibleToolBars(project, c, shareType, toolBarStats)
else -> {
LOG.debug("Unknown component: ${c.name}")
}
}
}
}
private fun paintToolBarButtons(toolbar: ActionToolbarImpl, shareType: ShareType, toolBarAllStats: List<MetricEntity>) {
val place = ConvertUsagesUtil.escapeDescriptorName(toolbar.place).replace(' ', '.')
val toolBarStat = toolbarsMetrics[place] ?: filterByPlaceToolbar(toolBarAllStats, place)
var toolbarAllUsers = 0
toolBarStat.forEach { toolbarAllUsers += it.users }
if (toolBarStat.isNotEmpty()) toolbarsMetrics[place] = toolBarStat
if (toolbarAllUsers > 0) toolbarsTotalMetricsUsers[place] = toolbarAllUsers
for (button in toolbar.components) {
val action = (button as? ActionButton)?.action
?: UIUtil.getClientProperty(button, CustomComponentAction.ACTION_KEY) ?: continue
val id = getActionId(action)
val buttonMetric = findMetric(toolBarStat, "$id@$place")
val buttonColor = if (buttonMetric != null) calcColorForMetric(shareType, buttonMetric, MetricGroup.TOOLBAR)
else BUTTON_EMPTY_STATS_COLOR
val textWithStats = if (buttonMetric != null) getTextWithStat(buttonMetric, shareType, toolbarAllUsers, place) else ""
val tooltipText = StringUtil.notNullize(action.templatePresentation.text) + textWithStats
if (button is ActionButton) {
(button as JComponent).toolTipText = tooltipText
button.setLook(createButtonLook(buttonColor))
}
else if (button is JComponent) {
button.toolTipText = tooltipText
button.isOpaque = true
button.background = buttonColor
}
LOG.debug("Place: $place action id: [$id]")
}
}
private fun getTextWithStat(buttonMetric: MetricEntity, shareType: ShareType, placeAllUsers: Int, place: String): String {
val totalUsers = if (shareType == ShareType.BY_GROUP) buttonMetric.sampleSize else placeAllUsers
return "\nClicks: Unique:${buttonMetric.users} / Avg:${DecimalFormat("####.#").format(
buttonMetric.usagesPerUser)} / ${place.capitalize()} total:$totalUsers"
}
private fun clearCache() {
toolbarsAllMetrics.clear()
toolbarsMetrics.clear()
mainMenuAllMetrics.clear()
mainMenuMetrics.clear()
toolbarsTotalMetricsUsers.clear()
mainMenuTotalMetricsUsers.clear()
}
private fun getActionId(action: AnAction): String {
return ActionManager.getInstance().getId(action) ?: if (action is ActionWithDelegate<*>) {
(action as ActionWithDelegate<*>).presentableName
}
else {
action.javaClass.name
}
}
private fun getDateString(date: Date): String = SimpleDateFormat(DATE_PATTERN).format(date)
private fun findMetric(list: List<MetricEntity>, key: String): MetricEntity? {
val metricId = ConvertUsagesUtil.escapeDescriptorName(key)
list.forEach { if (it.id == metricId) return it }
return null
}
private fun createButtonLook(color: Color): ActionButtonLook {
return object : ActionButtonLook() {
override fun paintBorder(g: Graphics, c: JComponent, state: Int) {
g.drawLine(c.width - 1, 0, c.width - 1, c.height)
}
override fun paintBackground(g: Graphics, component: JComponent, state: Int) {
if (state == ActionButtonComponent.PUSHED) {
g.color = component.background.brighter()
(g as Graphics2D).fill(g.getClip())
}
else {
g.color = color
(g as Graphics2D).fill(g.getClip())
}
}
}
}
private fun getMetricPlaceTotalUsersCache(metricEntity: MetricEntity, group: MetricGroup): Int {
return when (group) {
MetricGroup.TOOLBAR -> toolbarsTotalMetricsUsers[getToolBarButtonPlace(metricEntity)] ?: -1
MetricGroup.MAIN_MENU -> mainMenuTotalMetricsUsers[getMenuName(metricEntity)] ?: -1
}
}
private fun calcColorForMetric(shareType: ShareType, metricEntity: MetricEntity, group: MetricGroup): Color {
val level = getLevel(shareType, metricEntity, group)
return tuneColor(myColor, level)
}
fun getLevel(shareType: ShareType, metricEntity: MetricEntity, group: MetricGroup): Float {
return if (shareType == ShareType.BY_GROUP) {
Math.max(metricEntity.share, 0.0001f) / 100.0f
}
else {
val toolbarUsers = getMetricPlaceTotalUsersCache(metricEntity, group)
if (toolbarUsers != -1) metricEntity.users / toolbarUsers.toFloat() else Math.max(metricEntity.share, 0.0001f) / 100.0f
}
}
private fun tuneColor(default: Color, level: Float): Color {
val r = default.red
val g = default.green
val b = default.blue
val hsb = FloatArray(3)
Color.RGBtoHSB(r, g, b, hsb)
hsb[1] *= level
val hsbBkg = FloatArray(3)
val background = UIUtil.getLabelBackground()
Color.RGBtoHSB(background.red, background.green, background.blue, hsbBkg)
return JBColor.getHSBColor(hsb[0], hsb[1], hsbBkg[2])
}
private fun getProductCode(): String {
var code = ApplicationInfo.getInstance().build.productCode
if (StringUtil.isNotEmpty(code)) return code
code = getProductCodeFromBuildFile()
return if (StringUtil.isNotEmpty(code)) code else getProductCodeFromPlatformPrefix()
}
private fun getProductCodeFromBuildFile(): String {
try {
val home = PathManager.getHomePath()
val buildTxtFile = FileUtil.findFirstThatExist(
"$home/build.txt",
"$home/Resources/build.txt",
"$home/community/build.txt",
"$home/ultimate/community/build.txt")
if (buildTxtFile != null) {
return FileUtil.loadFile(buildTxtFile).trim { it <= ' ' }.substringBefore('-', "")
}
}
catch (ignored: IOException) {
}
return ""
}
private fun getProductCodeFromPlatformPrefix(): String {
return when {
PlatformUtils.isIdeaCommunity() -> "IC"
PlatformUtils.isIdeaUltimate() -> "IU"
PlatformUtils.isAppCode() -> "AC"
PlatformUtils.isCLion() -> "CL"
PlatformUtils.isDataGrip() -> "DB"
PlatformUtils.isGoIde() -> "GO"
PlatformUtils.isPyCharmPro() -> "PY"
PlatformUtils.isPyCharmCommunity() -> "PC"
PlatformUtils.isPyCharmEducational() -> "PE"
PlatformUtils.isPhpStorm() -> "PS"
PlatformUtils.isRider() -> "RD"
PlatformUtils.isWebStorm() -> "WS"
PlatformUtils.isRubyMine() -> "RM"
else -> ""
}
}
}
enum class ShareType {
BY_PLACE, BY_GROUP
}
private const val MENU_ITEM_SEPARATOR = " -> "
private const val MAIN_MENU_GROUP = "statistics.actions.main.menu"
private const val TOOLBAR_GROUP = "statistics.ui.toolbar.clicks"
private const val DATE_PATTERN = "YYYY-MM-dd"
enum class MetricGroup(val groupId: String) {
TOOLBAR(TOOLBAR_GROUP), MAIN_MENU(MAIN_MENU_GROUP)
}
data class MetricEntity(val id: String,
val sampleSize: Int,
val groupSize: Int,
val users: Int,
val usages: Int,
val usagesPerUser: Float,
val share: Float)
data class ProductBuildInfo(val code: String, val type: String, val version: String, val majorVersion: String, val build: String) {
fun isEap(): Boolean = type.equals("eap", true)
} | apache-2.0 |
mockk/mockk | test-modules/performance-tests/src/main/kotlin/io/mockk/performance/JmhTest.kt | 1 | 905 | package io.mockk.performance
import io.mockk.every
import io.mockk.mockk
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.BenchmarkMode
import org.openjdk.jmh.annotations.Mode
import org.openjdk.jmh.infra.Blackhole
@BenchmarkMode(Mode.Throughput)
open class JmhTest {
@Benchmark
fun noMockOrStub(blackhole: Blackhole) {
val mockedClass = MockedClass()
blackhole.consume(mockedClass)
}
@Benchmark
fun simpleMock(blackhole: Blackhole) {
val mockedClass: MockedClass = mockk()
blackhole.consume(mockedClass)
}
@Benchmark
fun simpleMockAndStub(blackhole: Blackhole) {
val mockedClass: MockedClass = mockk()
every { mockedClass.mockedFun() } returns "Hello, mockk!"
blackhole.consume(mockedClass)
}
class MockedClass {
fun mockedFun(): String = "Hello, world!"
}
}
| apache-2.0 |
dewarder/Android-Kotlin-Commons | akommons-bindings/src/androidTest/java/com/dewarder/akommons/binding/dimen/TestDimenDialog.kt | 1 | 2394 | package com.dewarder.akommons.binding.dimen
import android.app.Dialog
import android.content.Context
import com.dewarder.akommons.binding.*
import com.dewarder.akommons.binding.common.NO_DIMEN1
import com.dewarder.akommons.binding.common.NO_DIMEN2
import com.dewarder.akommons.binding.common.dimen.TestableDimen
import com.dewarder.akommons.binding.common.R
class TestDimenDialog(context: Context) : Dialog(context), TestableDimen {
override val dimenRequiredExist by dimen(R.dimen.test_dimen_8dp)
override val dimenRequiredAbsent by dimen(NO_DIMEN1)
override val dimenOptionalExist by dimenOptional(R.dimen.test_dimen_8dp)
override val dimenOptionalAbsent by dimenOptional(NO_DIMEN1)
override val dimenRequiredExistPx by dimen(R.dimen.test_dimen_8px, DimensionType.PX)
override val dimenRequiredExistDp by dimen(R.dimen.test_dimen_8dp, DimensionType.DP)
override val dimenRequiredExistSp by dimen(R.dimen.test_dimen_8sp, DimensionType.SP)
override val dimenOptionalExistPx by dimen(R.dimen.test_dimen_8px, DimensionType.PX)
override val dimenOptionalExistDp by dimen(R.dimen.test_dimen_8dp, DimensionType.DP)
override val dimenOptionalExistSp by dimen(R.dimen.test_dimen_8sp, DimensionType.SP)
override val dimensRequiredAllExist by dimens(R.dimen.test_dimen_4dp, R.dimen.test_dimen_8dp)
override val dimensRequiredAllAbsent by dimens(NO_DIMEN1, NO_DIMEN2)
override val dimensOptionalAllExist by dimensOptional(R.dimen.test_dimen_4dp, R.dimen.test_dimen_8dp)
override val dimensOptionalAllAbsent by dimensOptional(NO_DIMEN1, NO_DIMEN2)
override val dimensRequiredFirstExistSecondAbsent by dimens(R.dimen.test_dimen_4dp, NO_DIMEN1)
override val dimensOptionalFirstExistSecondAbsent by dimensOptional(R.dimen.test_dimen_4dp, NO_DIMEN1)
override val dimensRequiredExistPxDpSpAllPx by dimens(R.dimen.test_dimen_8px, R.dimen.test_dimen_8dp, R.dimen.test_dimen_8sp)
override val dimensOptionalExistPxDpSpAllPx by dimensOptional(R.dimen.test_dimen_8px, R.dimen.test_dimen_8dp, R.dimen.test_dimen_8sp)
override val dimensRequiredExistPxDpSpAllDp by dimens(R.dimen.test_dimen_8px, R.dimen.test_dimen_8dp, R.dimen.test_dimen_8sp, dimension = DimensionType.DP)
override val dimensOptionalExistPxDpSpAllDp by dimens(R.dimen.test_dimen_8px, R.dimen.test_dimen_8dp, R.dimen.test_dimen_8sp, dimension = DimensionType.DP)
} | apache-2.0 |
bozaro/git-as-svn | src/main/kotlin/svnserver/parser/token/WordToken.kt | 1 | 1501 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.parser.token
import java.io.IOException
import java.io.OutputStream
import java.nio.charset.StandardCharsets
/**
* Ключевое слово.
*
*
* Допустимые символы: 'a'..'z', 'A'..'Z', '-', '0'..'9'
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class WordToken constructor(override val text: String) : TextToken {
@Throws(IOException::class)
override fun write(stream: OutputStream) {
write(stream, text)
}
override fun toString(): String {
return "Word{$text}"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as WordToken
if (text != other.text) return false
return true
}
override fun hashCode(): Int {
return text.hashCode()
}
companion object {
@Throws(IOException::class)
fun write(stream: OutputStream, word: String) {
stream.write(word.toByteArray(StandardCharsets.US_ASCII))
stream.write(' '.code)
}
}
}
| gpl-2.0 |
bozaro/git-as-svn | src/main/kotlin/svnserver/repository/git/GitSubmodules.kt | 1 | 2054 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git
import org.eclipse.jgit.internal.storage.file.FileRepository
import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.revwalk.RevWalk
import org.slf4j.Logger
import svnserver.Loggers
import svnserver.config.ConfigHelper
import svnserver.context.Shared
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.CopyOnWriteArraySet
/**
* Git submodules list.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class GitSubmodules : Shared {
private val repositories = CopyOnWriteArraySet<Repository>()
internal constructor()
constructor(basePath: Path, paths: Collection<String>) {
for (path in paths) {
val file: Path = ConfigHelper.joinPath(basePath, path)
if (!Files.exists(file)) throw FileNotFoundException(file.toString())
log.info("Linked repository path: {}", file)
repositories.add(FileRepository(file.toFile()))
}
}
@Throws(IOException::class)
fun findCommit(objectId: ObjectId): GitObject<RevCommit>? {
for (repo: Repository in repositories) {
if (repo.objectDatabase.has(objectId)) return GitObject(repo, RevWalk(repo).parseCommit(objectId))
}
return null
}
fun register(repository: Repository) {
repositories.add(repository)
}
fun unregister(repository: Repository) {
repositories.remove(repository)
}
companion object {
private val log: Logger = Loggers.git
}
}
| gpl-2.0 |
siarhei-luskanau/android-samples | workmanager/src/main/java/worker/s09/DataOverflowWorkFragment.kt | 1 | 1305 | package worker.s09
import android.content.Context
import androidx.work.Data
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import siarhei.luskanau.example.workmanager.BaseBeginCancelWorkFragment
import siarhei.luskanau.example.workmanager.BaseWorker
import siarhei.luskanau.example.workmanager.monitor.WorkManagerConstants
class DataOverflowWorkFragment : BaseBeginCancelWorkFragment() {
override fun onBeginButtonPressed() {
WorkManager.getInstance(requireContext())
.beginWith(
OneTimeWorkRequestBuilder<DataOverflowWork>()
.addTag(WorkManagerConstants.TAG_ALL)
.build()
).enqueue()
}
override fun onCancelButtonPressed() {
WorkManager.getInstance(requireContext())
.cancelAllWorkByTag(DataOverflowWork::class.java.name)
}
}
class DataOverflowWork(
context: Context,
workerParams: WorkerParameters
) : BaseWorker(
context,
workerParams
) {
override suspend fun doWorkDelegate(outputDataBuilder: Data.Builder): Result {
var i = 0
while (true) {
i++
outputDataBuilder.putInt("key_$i", i)
outputDataBuilder.build()
}
}
}
| mit |
cashapp/sqldelight | extensions/coroutines-extensions/src/nativeTest/kotlin/app/cash/sqldelight/coroutines/RunTest.kt | 1 | 859 | /*
* Copyright (C) 2018 Square, Inc.
*
* 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 app.cash.sqldelight.coroutines
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.runBlocking
actual fun DbTest.runTest(body: suspend CoroutineScope.(TestDb) -> Unit) = runBlocking {
val db = setupDb()
body(db)
db.close()
}
| apache-2.0 |
CherepanovAleksei/BinarySearchTree | src/Interfaces/TreeInterface.kt | 1 | 217 | /**
*
* by Cherepanov Aleksei (PI-171)
*
* [email protected]
*
**/
package Interfaces
interface Tree<K: Comparable <K>, V> {
fun insert(key:K,value:V)
fun delete(key:K)
fun search(key: K): V?
} | mit |
apixandru/intellij-community | platform/lang-impl/src/com/intellij/ide/util/gotoByName/SelectionPolicy.kt | 5 | 1782 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.intellij.ide.util.gotoByName
/**
* @author peter
*/
internal interface SelectionPolicy {
fun performSelection(popup: ChooseByNameBase, model: SmartPointerListModel<Any>): List<Int>
}
internal fun fromIndex(index: Int) = if (index <= 0) SelectMostRelevant else SelectIndex(index)
internal object SelectMostRelevant : SelectionPolicy {
override fun performSelection(popup: ChooseByNameBase, model: SmartPointerListModel<Any>) =
listOf(popup.calcSelectedIndex(model.items.toTypedArray(), popup.trimmedText))
}
internal data class SelectIndex(private val selectedIndex: Int) : SelectionPolicy {
override fun performSelection(popup: ChooseByNameBase, model: SmartPointerListModel<Any>) = listOf(selectedIndex)
}
internal data class SelectionSnapshot(val pattern: String, private val chosenElements: Set<Any>) : SelectionPolicy {
override fun performSelection(popup: ChooseByNameBase, model: SmartPointerListModel<Any>): List<Int> {
val items = model.items
return items.indices.filter { items[it] in chosenElements }
}
fun hasSamePattern(popup: ChooseByNameBase) = popup.transformPattern(pattern) == popup.transformPattern(popup.trimmedText)
} | apache-2.0 |
ivan-osipov/Clabo | src/main/kotlin/com/github/ivan_osipov/clabo/api/internal/IncomingInteractionApi.kt | 1 | 752 | package com.github.ivan_osipov.clabo.api.internal
import com.github.ivan_osipov.clabo.api.model.Chat
import com.github.ivan_osipov.clabo.api.model.Update
import com.github.ivan_osipov.clabo.api.model.User
import com.github.ivan_osipov.clabo.api.output.dto.GetChatParams
import com.github.ivan_osipov.clabo.api.output.dto.UpdatesParams
interface IncomingInteractionApi {
val defaultUpdatesParams: UpdatesParams
fun getMe(): User
fun getMe(callback: (User) -> Unit)
fun getChat(params: GetChatParams) : Chat
fun getChat(params: GetChatParams, callback: (Chat) -> Unit)
fun getUpdates(params: UpdatesParams = defaultUpdatesParams): List<Update>
fun getUpdates(params: UpdatesParams, callback: (List<Update>) -> Unit)
} | apache-2.0 |
Ribesg/anko | dsl/test/org/jetbrains/android/anko/functional/FunctionalTestsForSdk19.kt | 1 | 1977 | package org.jetbrains.android.anko.functional
import org.jetbrains.android.anko.config.*
import org.junit.Test
class FunctionalTestsForSdk19 : AbstractFunctionalTest() {
val version = "sdk19"
@Test
fun testComplexListenerClassTest() {
runFunctionalTest("ComplexListenerClassTest.kt", AnkoFile.LISTENERS, version) {
files.add(AnkoFile.LISTENERS)
tunes.add(ConfigurationTune.COMPLEX_LISTENER_CLASSES)
}
}
@Test
fun testComplexListenerSetterTest() {
runFunctionalTest("ComplexListenerSetterTest.kt", AnkoFile.LISTENERS, version) {
files.add(AnkoFile.LISTENERS)
tunes.add(ConfigurationTune.COMPLEX_LISTENER_SETTERS)
}
}
@Test
fun testLayoutsTest() {
runFunctionalTest("LayoutsTest.kt", AnkoFile.LAYOUTS, version) {
files.add(AnkoFile.LAYOUTS)
}
}
@Test
fun testViewTest() {
runFunctionalTest("ViewTest.kt", AnkoFile.VIEWS, version) {
files.add(AnkoFile.VIEWS)
tunes.add(ConfigurationTune.TOP_LEVEL_DSL_ITEMS)
tunes.add(ConfigurationTune.HELPER_CONSTRUCTORS)
}
}
@Test
fun testPropertyTest() {
runFunctionalTest("PropertyTest.kt", AnkoFile.PROPERTIES, version) {
files.add(AnkoFile.PROPERTIES)
}
}
@Test
fun testServicesTest() {
runFunctionalTest("ServicesTest.kt", AnkoFile.SERVICES, version) {
files.add(AnkoFile.SERVICES)
}
}
@Test
fun testSimpleListenerTest() {
runFunctionalTest("SimpleListenerTest.kt", AnkoFile.LISTENERS, version) {
files.add(AnkoFile.LISTENERS)
tunes.add(ConfigurationTune.SIMPLE_LISTENERS)
}
}
@Test
fun testSqlParserHelpersTest() {
runFunctionalTest("SqlParserHelpersTest.kt", AnkoFile.SQL_PARSER_HELPERS, version) {
files.add(AnkoFile.SQL_PARSER_HELPERS)
}
}
}
| apache-2.0 |
Nanoware/Terasology | build-logic/src/main/kotlin/org/terasology/gradology/file_operations.kt | 2 | 724 | // Copyright 2022 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.gradology
import org.gradle.api.internal.file.copy.CopySpecInternal
import org.gradle.api.tasks.Copy
/**
* Copy, but never overwrite any existing file.
*
* Preserves existing files regardless of how up-to-date they are.
*
* Useful for providing boilerplate or defaults.
*/
abstract class CopyButNeverOverwrite : Copy() {
override fun createRootSpec(): CopySpecInternal {
val copySpec = super.createRootSpec()
copySpec.eachFile {
if (this.relativePath.getFile(destinationDir).exists()) {
this.exclude()
}
}
return copySpec;
}
}
| apache-2.0 |
openstreetview/android | app/src/main/java/com/telenav/osv/jarvis/login/usecase/JarvisLoginUseCase.kt | 1 | 1139 | package com.telenav.osv.jarvis.login.usecase
import com.telenav.osv.jarvis.login.model.JarvisLoginResponse
import com.telenav.osv.jarvis.login.model.JarvisRefreshTokenResponse
import com.telenav.osv.jarvis.login.network.JarvisLoginApi
import com.telenav.osv.jarvis.login.network.JarvisLoginRequest
import com.telenav.osv.jarvis.login.network.JarvisRefreshTokenRequest
import io.reactivex.Single
internal interface JarvisLoginUseCase {
fun jarvisLogin(accessToken: String, loginRequest: JarvisLoginRequest): Single<JarvisLoginResponse>
fun jarvisRefreshToken(refreshTokenRequest: JarvisRefreshTokenRequest): Single<JarvisRefreshTokenResponse>
}
internal class JarvisLoginUseCaseImpl(private val jarvisLoginApi: JarvisLoginApi) : JarvisLoginUseCase {
override fun jarvisLogin(accessToken: String, loginRequest: JarvisLoginRequest): Single<JarvisLoginResponse> {
return jarvisLoginApi.login(accessToken, loginRequest)
}
override fun jarvisRefreshToken(refreshTokenRequest: JarvisRefreshTokenRequest): Single<JarvisRefreshTokenResponse> {
return jarvisLoginApi.refreshToken(refreshTokenRequest)
}
} | lgpl-3.0 |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/edit/richtext/SyntaxHighlighter.kt | 1 | 11362 | package org.wikipedia.edit.richtext
import android.content.Context
import android.os.Build
import android.text.Spanned
import androidx.core.text.getSpans
import androidx.core.widget.NestedScrollView
import androidx.core.widget.doAfterTextChanged
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.edit.SyntaxHighlightableEditText
import org.wikipedia.util.log.L
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.TimeUnit
class SyntaxHighlighter(
private var context: Context,
private val textBox: SyntaxHighlightableEditText,
private val scrollView: NestedScrollView) {
private val syntaxRules = listOf(
SyntaxRule("{{", "}}", SyntaxRuleStyle.TEMPLATE),
SyntaxRule("[[", "]]", SyntaxRuleStyle.INTERNAL_LINK),
SyntaxRule("[", "]", SyntaxRuleStyle.EXTERNAL_LINK),
SyntaxRule("<big>", "</big>", SyntaxRuleStyle.TEXT_LARGE),
SyntaxRule("<small>", "</small>", SyntaxRuleStyle.TEXT_SMALL),
SyntaxRule("<sub>", "</sub>", SyntaxRuleStyle.SUBSCRIPT),
SyntaxRule("<sup>", "</sup>", SyntaxRuleStyle.SUPERSCRIPT),
SyntaxRule("<code>", "</code>", if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) SyntaxRuleStyle.CODE else SyntaxRuleStyle.BOLD),
SyntaxRule("<u>", "</u>", SyntaxRuleStyle.UNDERLINE),
SyntaxRule("<s>", "</s>", SyntaxRuleStyle.STRIKETHROUGH),
SyntaxRule("<", ">", SyntaxRuleStyle.REF),
SyntaxRule("'''", "'''", SyntaxRuleStyle.BOLD),
SyntaxRule("''", "''", SyntaxRuleStyle.ITALIC),
SyntaxRule("=====", "=====", SyntaxRuleStyle.HEADING_SMALL),
SyntaxRule("====", "====", SyntaxRuleStyle.HEADING_SMALL),
SyntaxRule("===", "===", SyntaxRuleStyle.HEADING_MEDIUM),
SyntaxRule("==", "==", SyntaxRuleStyle.HEADING_LARGE),
)
private val disposables = CompositeDisposable()
private var currentHighlightTask: SyntaxHighlightTask? = null
private var lastScrollY = -1
private val highlightOnScrollRunnable = Runnable { postHighlightOnScroll() }
private var searchQueryPositions: List<Int>? = null
private var searchQueryLength = 0
private var searchQueryPositionIndex = 0
var enabled = true
set(value) {
field = value
if (!value) {
currentHighlightTask?.cancel()
disposables.clear()
textBox.text.getSpans<SpanExtents>().forEach { textBox.text.removeSpan(it) }
} else {
runHighlightTasks(HIGHLIGHT_DELAY_MILLIS)
}
}
init {
textBox.doAfterTextChanged { runHighlightTasks(HIGHLIGHT_DELAY_MILLIS * 2) }
textBox.scrollView = scrollView
postHighlightOnScroll()
}
private fun runHighlightTasks(delayMillis: Long) {
currentHighlightTask?.cancel()
disposables.clear()
if (!enabled) {
return
}
disposables.add(Observable.timer(delayMillis, TimeUnit.MILLISECONDS)
.flatMap {
if (textBox.layout == null) {
throw IllegalArgumentException()
}
var firstVisibleLine = textBox.layout.getLineForVertical(scrollView.scrollY)
if (firstVisibleLine < 0) firstVisibleLine = 0
var lastVisibleLine = textBox.layout.getLineForVertical(scrollView.scrollY + scrollView.height)
if (lastVisibleLine < firstVisibleLine) lastVisibleLine = firstVisibleLine
else if (lastVisibleLine >= textBox.lineCount) lastVisibleLine = textBox.lineCount - 1
val firstVisibleIndex = textBox.layout.getLineStart(firstVisibleLine)
val lastVisibleIndex = textBox.layout.getLineEnd(lastVisibleLine)
val textToHighlight = textBox.text.substring(firstVisibleIndex, lastVisibleIndex)
currentHighlightTask = SyntaxHighlightTask(textToHighlight, firstVisibleIndex)
Observable.zip<MutableList<SpanExtents>, List<SpanExtents>, List<SpanExtents>>(Observable.fromCallable(currentHighlightTask!!),
if (searchQueryPositions.isNullOrEmpty()) Observable.just(emptyList())
else Observable.fromCallable(SyntaxHighlightSearchMatchesTask(firstVisibleIndex, textToHighlight.length))) { f, s ->
f.addAll(s)
f
}
}
.retry(10)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result ->
textBox.enqueueNoScrollingLayoutChange()
var time = System.currentTimeMillis()
val oldSpans = textBox.text.getSpans<SpanExtents>().toMutableList()
val newSpans = result.toMutableList()
val dupes = oldSpans.filter { item ->
val r = result.find {
it.start == textBox.text.getSpanStart(item) && it.end == textBox.text.getSpanEnd(item) && it.syntaxRule == item.syntaxRule
}
if (r != null) {
newSpans.remove(r)
}
r != null
}
oldSpans.removeAll(dupes)
oldSpans.forEach { textBox.text.removeSpan(it) }
newSpans.forEach { textBox.text.setSpan(it, it.start, it.end, Spanned.SPAN_INCLUSIVE_INCLUSIVE) }
time = System.currentTimeMillis() - time
L.d("Took $time ms to remove ${oldSpans.size} spans and add ${newSpans.size} new.")
}) { L.e(it) })
}
fun setSearchQueryInfo(searchQueryPositions: List<Int>?, searchQueryLength: Int, searchQueryPositionIndex: Int) {
this.searchQueryPositions = searchQueryPositions
this.searchQueryLength = searchQueryLength
this.searchQueryPositionIndex = searchQueryPositionIndex
runHighlightTasks(0)
}
fun clearSearchQueryInfo() {
setSearchQueryInfo(null, 0, 0)
}
fun cleanup() {
scrollView.removeCallbacks(highlightOnScrollRunnable)
disposables.clear()
textBox.text.clearSpans()
}
private fun postHighlightOnScroll() {
if (lastScrollY != scrollView.scrollY) {
lastScrollY = scrollView.scrollY
runHighlightTasks(0)
}
scrollView.postDelayed(highlightOnScrollRunnable, HIGHLIGHT_DELAY_MILLIS)
}
private inner class SyntaxHighlightTask constructor(private val text: CharSequence, private val startOffset: Int) : Callable<MutableList<SpanExtents>> {
private var cancelled = false
fun cancel() {
cancelled = true
}
override fun call(): MutableList<SpanExtents> {
val spanStack = Stack<SpanExtents>()
val spansToSet = mutableListOf<SpanExtents>()
val textChars = text.toString().toCharArray()
/*
The (naïve) algorithm:
Iterate through the text string, and maintain a stack of matched syntax rules.
When the "start" and "end" symbol of a rule are matched in sequence, create a new
Span to be added to the EditText at the corresponding location.
*/
var i = 0
while (i < textChars.size) {
var newSpanInfo: SpanExtents
var completed = false
for (rule in syntaxRules) {
if (i + rule.endChars.size > textChars.size) {
continue
}
var pass = true
for (j in 0 until rule.endChars.size) {
if (textChars[i + j] != rule.endChars[j]) {
pass = false
break
}
}
if (pass) {
val sr = spanStack.find { it.syntaxRule == rule }
if (sr != null) {
newSpanInfo = sr
spanStack.remove(sr)
newSpanInfo.end = i + rule.endChars.size
spansToSet.add(newSpanInfo)
i += rule.endChars.size - 1
completed = true
break
}
}
}
if (!completed) {
for (rule in syntaxRules) {
if (i + rule.startChars.size > textChars.size) {
continue
}
var pass = true
for (j in 0 until rule.startChars.size) {
if (textChars[i + j] != rule.startChars[j]) {
pass = false
break
}
}
if (pass) {
val sp = rule.spanStyle.createSpan(context, i, rule)
spanStack.push(sp)
i += rule.startChars.size - 1
break
}
}
if (cancelled) {
break
}
}
i++
}
spansToSet.forEach {
it.start += startOffset
it.end += startOffset
}
spansToSet.sortWith { a, b -> a.syntaxRule.spanStyle.compareTo(b.syntaxRule.spanStyle) }
return spansToSet
}
}
private inner class SyntaxHighlightSearchMatchesTask constructor(private val startOffset: Int, private val textLength: Int) : Callable<List<SpanExtents>> {
override fun call(): List<SpanExtents> {
val spansToSet = mutableListOf<SpanExtents>()
val syntaxItem = SyntaxRule("", "", SyntaxRuleStyle.SEARCH_MATCHES)
searchQueryPositions?.let {
for (i in it.indices) {
if (it[i] >= startOffset && it[i] < startOffset + textLength) {
val newSpanInfo = if (i == searchQueryPositionIndex) {
SyntaxRuleStyle.SEARCH_MATCH_SELECTED.createSpan(context, it[i], syntaxItem)
} else {
SyntaxRuleStyle.SEARCH_MATCHES.createSpan(context, it[i], syntaxItem)
}
newSpanInfo.start = it[i]
newSpanInfo.end = it[i] + searchQueryLength
spansToSet.add(newSpanInfo)
}
}
}
return spansToSet
}
}
companion object {
const val HIGHLIGHT_DELAY_MILLIS = 500L
}
}
| apache-2.0 |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/TwidereViewUtils.kt | 1 | 1492 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util
import android.graphics.RectF
import android.support.annotation.UiThread
import android.view.MotionEvent
import android.view.View
object TwidereViewUtils {
private val location = IntArray(2)
private val rect = RectF()
@UiThread
fun hitView(event: MotionEvent, view: View): Boolean {
view.getLocationOnScreen(location)
rect.set(location[0].toFloat(), location[1].toFloat(), location[0].toFloat() + view.width,
location[1].toFloat() + view.height)
return rect.contains(event.rawX, event.rawY)
}
} | gpl-3.0 |
stripe/stripe-android | payments-ui-core/src/test/java/com/stripe/android/ui/core/elements/CardNumberConfigTest.kt | 1 | 4381 | package com.stripe.android.ui.core.elements
import androidx.compose.ui.text.AnnotatedString
import com.google.common.truth.Truth
import com.stripe.android.model.CardBrand
import com.stripe.android.ui.core.CardNumberFixtures
import com.stripe.android.ui.core.R
import org.junit.Test
class CardNumberConfigTest {
private val cardNumberConfig = CardNumberConfig()
@Test
fun `visualTransformation formats entered value`() {
Truth.assertThat(cardNumberConfig.visualTransformation.filter(AnnotatedString(CardNumberFixtures.VISA_NO_SPACES)).text)
.isEqualTo(AnnotatedString(CardNumberFixtures.VISA_WITH_SPACES))
Truth.assertThat(cardNumberConfig.visualTransformation.filter(AnnotatedString(CardNumberFixtures.AMEX_NO_SPACES)).text)
.isEqualTo(AnnotatedString(CardNumberFixtures.AMEX_WITH_SPACES))
Truth.assertThat(cardNumberConfig.visualTransformation.filter(AnnotatedString(CardNumberFixtures.DISCOVER_NO_SPACES)).text)
.isEqualTo(AnnotatedString(CardNumberFixtures.DISCOVER_WITH_SPACES))
Truth.assertThat(cardNumberConfig.visualTransformation.filter(AnnotatedString(CardNumberFixtures.DINERS_CLUB_14_NO_SPACES)).text)
.isEqualTo(AnnotatedString(CardNumberFixtures.DINERS_CLUB_14_WITH_SPACES))
Truth.assertThat(cardNumberConfig.visualTransformation.filter(AnnotatedString(CardNumberFixtures.DINERS_CLUB_16_NO_SPACES)).text)
.isEqualTo(AnnotatedString(CardNumberFixtures.DINERS_CLUB_16_WITH_SPACES))
Truth.assertThat(cardNumberConfig.visualTransformation.filter(AnnotatedString(CardNumberFixtures.JCB_NO_SPACES)).text)
.isEqualTo(AnnotatedString(CardNumberFixtures.JCB_WITH_SPACES))
Truth.assertThat(cardNumberConfig.visualTransformation.filter(AnnotatedString(CardNumberFixtures.UNIONPAY_NO_SPACES)).text)
.isEqualTo(AnnotatedString(CardNumberFixtures.UNIONPAY_WITH_SPACES))
}
@Test
fun `only numbers are allowed in the field`() {
Truth.assertThat(cardNumberConfig.filter("123^@Number[\uD83E\uDD57."))
.isEqualTo("123")
}
@Test
fun `blank Number returns blank state`() {
Truth.assertThat(cardNumberConfig.determineState(CardBrand.Visa, "", CardBrand.Visa.getMaxLengthForCardNumber("")))
.isEqualTo(TextFieldStateConstants.Error.Blank)
}
@Test
fun `card brand is invalid`() {
val state = cardNumberConfig.determineState(CardBrand.Unknown, "0", CardBrand.Unknown.getMaxLengthForCardNumber("0"))
Truth.assertThat(state)
.isInstanceOf(TextFieldStateConstants.Error.Invalid::class.java)
Truth.assertThat(
state.getError()?.errorMessage
).isEqualTo(R.string.invalid_card_number)
}
@Test
fun `incomplete number is in incomplete state`() {
val state = cardNumberConfig.determineState(CardBrand.Visa, "12", CardBrand.Visa.getMaxLengthForCardNumber("12"))
Truth.assertThat(state)
.isInstanceOf(TextFieldStateConstants.Error.Incomplete::class.java)
Truth.assertThat(
state.getError()?.errorMessage
).isEqualTo(R.string.invalid_card_number)
}
@Test
fun `card number is too long`() {
val state = cardNumberConfig.determineState(CardBrand.Visa, "1234567890123456789", CardBrand.Visa.getMaxLengthForCardNumber("1234567890123456789"))
Truth.assertThat(state)
.isInstanceOf(TextFieldStateConstants.Error.Invalid::class.java)
Truth.assertThat(
state.getError()?.errorMessage
).isEqualTo(R.string.invalid_card_number)
}
@Test
fun `card number has invalid luhn`() {
val state = cardNumberConfig.determineState(CardBrand.Visa, "4242424242424243", CardBrand.Visa.getMaxLengthForCardNumber("4242424242424243"))
Truth.assertThat(state)
.isInstanceOf(TextFieldStateConstants.Error.Invalid::class.java)
Truth.assertThat(
state.getError()?.errorMessage
).isEqualTo(R.string.invalid_card_number)
}
@Test
fun `card number is valid`() {
val state = cardNumberConfig.determineState(CardBrand.Visa, "4242424242424242", CardBrand.Visa.getMaxLengthForCardNumber("4242424242424242"))
Truth.assertThat(state)
.isInstanceOf(TextFieldStateConstants.Valid.Full::class.java)
}
}
| mit |
joffrey-bion/mc-mining-optimizer | src/main/kotlin/org/hildan/minecraft/mining/optimizer/patterns/tunnels/Axis.kt | 1 | 337 | package org.hildan.minecraft.mining.optimizer.patterns.tunnels
/**
* Defines a spatial dimensions.
*/
enum class Axis {
/**
* The X axis is horizontal, pointing East.
*/
X,
/**
* The Y axis is vertical, pointing up.
*/
Y,
/**
* The Z axis is horizontal, pointing South.
*/
Z,
}
| mit |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/networking/models/DocumentUploadParam.kt | 1 | 1008 | package com.stripe.android.identity.networking.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@Parcelize
internal data class DocumentUploadParam(
@SerialName("back_score")
val backScore: Float? = null,
@SerialName("front_card_score")
val frontCardScore: Float? = null,
@SerialName("high_res_image")
val highResImage: String,
@SerialName("invalid_score")
val invalidScore: Float? = null,
@SerialName("low_res_image")
val lowResImage: String? = null,
@SerialName("passport_score")
val passportScore: Float? = null,
@SerialName("upload_method")
val uploadMethod: UploadMethod
) : Parcelable {
@Serializable
internal enum class UploadMethod {
@SerialName("auto_capture")
AUTOCAPTURE,
@SerialName("file_upload")
FILEUPLOAD,
@SerialName("manual_capture")
MANUALCAPTURE;
}
}
| mit |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/IdentityFileProvider.kt | 1 | 208 | package com.stripe.android.identity
import androidx.core.content.FileProvider
/**
* Custom [FileProvider] class to avoid collision of hosting apps.
*/
internal class IdentityFileProvider : FileProvider()
| mit |
stripe/stripe-android | example/src/main/java/com/stripe/example/activity/UpiPaymentActivity.kt | 1 | 2363 | package com.stripe.example.activity
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.Observer
import com.stripe.android.model.Address
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodCreateParams
import com.stripe.android.payments.paymentlauncher.PaymentResult
import com.stripe.example.databinding.UpiPaymentActivityBinding
class UpiPaymentActivity : StripeIntentActivity() {
private val viewBinding: UpiPaymentActivityBinding by lazy {
UpiPaymentActivityBinding.inflate(layoutInflater)
}
private lateinit var paymentIntentSecret: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
viewModel.status.observe(this, Observer(viewBinding.status::setText))
viewBinding.submit.setOnClickListener {
val params = PaymentMethodCreateParams.create(
upi = PaymentMethodCreateParams.Upi(
vpa = viewBinding.vpa.text.toString()
),
billingDetails = PaymentMethod.BillingDetails(
name = "Jenny Rosen",
phone = "(555) 555-5555",
email = "[email protected]",
address = Address.Builder()
.setCity("San Francisco")
.setCountry("US")
.setLine1("123 Market St")
.setLine2("#345")
.setPostalCode("94107")
.setState("CA")
.build()
)
)
createAndConfirmPaymentIntent("in", params) { secret ->
paymentIntentSecret = secret
}
}
}
override fun onConfirmSuccess() {
startActivity(
Intent(this@UpiPaymentActivity, UpiWaitingActivity::class.java)
.putExtra(EXTRA_CLIENT_SECRET, paymentIntentSecret)
)
}
override fun onConfirmError(failedResult: PaymentResult.Failed) {
viewModel.status.value += "\n\nPaymentIntent confirmation failed with throwable " +
"${failedResult.throwable} \n\n"
}
internal companion object {
const val EXTRA_CLIENT_SECRET = "extra_client_secret"
}
}
| mit |
AndroidX/androidx | datastore/datastore-core/src/jvmMain/kotlin/androidx/datastore/core/handlers/NoOpCorruptionHandler.jvm.kt | 3 | 1052 | /*
* Copyright 2020 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 androidx.datastore.core.handlers
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.CorruptionHandler
/**
* Default corruption handler which does nothing but rethrow the exception.
*/
internal actual class NoOpCorruptionHandler<T> : CorruptionHandler<T> {
@Throws(CorruptionException::class)
override suspend fun handleCorruption(ex: CorruptionException): T {
throw ex
}
} | apache-2.0 |
codeka/wwmmo | common/src/main/kotlin/au/com/codeka/warworlds/common/sim/SuspiciousModificationException.kt | 1 | 377 | package au.com.codeka.warworlds.common.sim
import au.com.codeka.warworlds.common.proto.StarModification
/**
* An exception that is thrown when a suspicious modification to a star happens.
*/
class SuspiciousModificationException(
val starId: Long,
val modification: StarModification,
fmt: String?,
vararg args: Any?) : Exception(String.format(fmt!!, *args)) | mit |
vimeo/vimeo-networking-java | model-generator/integrations/models-input/src/main/java/com/vimeo/networking2/enums/ParameterizedSuperEnum.kt | 1 | 202 | package com.vimeo.networking2.enums
enum class ParameterizedSuperEnum(override val value: String): Container<String> {
FOO("foo"),
BAR("bar")
}
interface Container<TYPE>{
val value: TYPE
} | mit |
ioc1778/incubator | incubator-javafx-desktop/src/main/java/com/riaektiv/javafx/desktop/PortfolioApplication.kt | 2 | 3075 | package com.riaektiv.javafx.desktop
import javafx.application.Application
import javafx.collections.FXCollections
import javafx.geometry.Insets
import javafx.scene.Group
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.control.cell.PropertyValueFactory
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import javafx.scene.text.Font
import javafx.stage.Stage
/**
* Coding With Passion Since 1991
* Created: 9/4/2016, 6:12 PM Eastern Time
* @author Sergey Chuykov
*/
class PortfolioApplication : Application() {
private val table = TableView<Position>()
private val data = FXCollections.observableArrayList(
Position("APA", "Apache Corp.", "3000"),
Position("CHK", "Chesapeake Energy Corp.", "1000"),
Position("NBL", "Nobel Energy Inc.", "5000"))
@SuppressWarnings("unchecked")
@Throws(Exception::class)
override fun start(stage: Stage) {
val scene = Scene(Group())
stage.title = "Portfolio"
stage.width = 700.0
stage.height = 500.0
val label = Label("Positions")
label.font = Font("Arial", 20.0)
table.isEditable = true
table.maxHeight = 300.0
val symbolCol = TableColumn<Position, String>("Symbol")
symbolCol.minWidth = 100.0
symbolCol.cellValueFactory = PropertyValueFactory<Position, String>("symbol")
val companyCol = TableColumn<Position, String>("Company")
companyCol.minWidth = 400.0
companyCol.cellValueFactory = PropertyValueFactory<Position, String>("company")
val qtyCol = TableColumn<Position, String>("Qty")
qtyCol.minWidth = 100.0
qtyCol.cellValueFactory = PropertyValueFactory<Position, String>("qty")
table.items = data
table.columns.addAll(symbolCol, companyCol, qtyCol)
val symbolText = TextField()
symbolText.promptText = "Symbol"
symbolText.maxWidth = symbolCol.prefWidth
val companyText = TextField()
companyText.maxWidth = companyCol.prefWidth
companyText.promptText = "Company"
val qtyText = TextField()
qtyText.maxWidth = qtyCol.prefWidth
qtyText.promptText = "Qty"
val addButton = Button("Add")
addButton.setOnAction { e ->
data.add(Position(
symbolText.text,
companyText.text,
qtyText.text))
symbolText.clear()
companyText.clear()
qtyText.clear()
}
val hb = HBox()
hb.children.addAll(symbolText, companyText, qtyText, addButton)
hb.spacing = 3.0
val vb = VBox()
vb.spacing = 5.0
vb.padding = Insets(10.0, 0.0, 0.0, 10.0)
vb.children.addAll(label, table, hb)
(scene.root as Group).children.addAll(vb)
stage.scene = scene
stage.show()
}
companion object {
@JvmStatic fun main(args: Array<String>) {
launch(PortfolioApplication::class.java, *args)
}
}
}
| bsd-3-clause |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/intentions/SplitIfIntentionTest.kt | 2 | 7701 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class SplitIfIntentionTest : RsIntentionTestBase(SplitIfIntention::class) {
fun test1() = doUnavailableTest("""
fn main() {
42/*caret*/;
}
""")
fun test2() = doUnavailableTest("""
fn main() {
if true =/*caret*/= true && false {}
}
""")
fun `test availability range`() = checkAvailableInSelectionOnly("""
fn foo() {
if true <selection>&&</selection> false {}
if true <selection>&&</selection> false <selection>&&</selection> true {}
}
""")
fun `test simple &&`() = doAvailableTest("""
fn main() {
if true &/*caret*/& false {
42
} else {
24
};
}
""", """
fn main() {
if true {
if false {
42
} else {
24
}
} else {
24
};
}
""")
fun `test simple OR`() = doAvailableTest("""
fn main() {
if true |/*caret*/| false {
42
} else {
24
};
}
""", """
fn main() {
if true {
42
} else if false {
42
} else {
24
};
}
""")
fun `test simple && without else`() = doAvailableTest("""
fn main() {
if true &/*caret*/& false {
42
};
}
""", """
fn main() {
if true {
if false {
42
}
};
}
""")
fun `test simple OR without else`() = doAvailableTest("""
fn main() {
if true |/*caret*/| false {
42
};
}
""", """
fn main() {
if true {
42
} else if false {
42
};
}
""")
fun `test multy && 1`() = doAvailableTest("""
fn main() {
if true &/*caret*/& false && 1 == 1{
42
} else {
24
};
}
""", """
fn main() {
if true {
if false && 1 == 1 {
42
} else {
24
}
} else {
24
};
}
""")
fun `test multy && 2`() = doAvailableTest("""
fn main() {
if true && false &/*caret*/& 1 == 1{
42
} else {
24
};
}
""", """
fn main() {
if true && false {
if 1 == 1 {
42
} else {
24
}
} else {
24
};
}
""")
fun `test multiple OR 1`() = doAvailableTest("""
fn main() {
if true |/*caret*/| false || 1 == 1 {
42
} else {
24
};
}
""", """
fn main() {
if true {
42
} else if false || 1 == 1 {
42
} else {
24
};
}
""")
fun `test multiple OR 2`() = doAvailableTest("""
fn main() {
if true || false |/*caret*/| 1 == 1 {
42
} else {
24
};
}
""", """
fn main() {
if true || false {
42
} else if 1 == 1 {
42
} else {
24
};
}
""")
fun `test available mix 1`() = doAvailableTest("""
fn main() {
if true |/*caret*/| false && 1 == 1 {
42
} else {
24
};
}
""", """
fn main() {
if true {
42
} else if false && 1 == 1 {
42
} else {
24
};
}
""")
fun `test available mix 2`() = doAvailableTest("""
fn main() {
if false && true |/*caret*/| false && 1 == 1 && true {
42
} else {
24
};
}
""", """
fn main() {
if false && true {
42
} else if false && 1 == 1 && true {
42
} else {
24
};
}
""")
fun `test unavailable mix 1`() = doUnavailableTest("""
fn main() {
if false && true || false &/*caret*/& 1 == 1 && true {
42
} else {
24
};
}
""")
fun `test unavailable mix 2`() = doUnavailableTest("""
fn main() {
if false && true || false && 1 == 1 &/*caret*/& true {
42
} else {
24
};
}
""")
fun `test unavailable mix 3`() = doUnavailableTest("""
fn main() {
if false &/*caret*/& true || false && 1 == 1 && true {
42
} else {
24
};
}
""")
fun `test unavailable mix 4`() = doUnavailableTest("""
fn main() {
if (false && true |/*caret*/| false) && 1 == 1 && true {
42
} else {
24
};
}
""")
fun `test unavailable mix 5`() = doUnavailableTest("""
fn main() {
if(false &/*caret*/& true && false) && 1 == 1 && true {
42
} else {
24
};
}
""")
fun `test available mix with body`() = doAvailableTest("""
fn main() {
if true |/*caret*/| false && 1 == 1 {
4;
8;
15;
16;
23;
42;
} else {
24
};
}
""", """
fn main() {
if true {
4;
8;
15;
16;
23;
42;
} else if false && 1 == 1 {
4;
8;
15;
16;
23;
42;
} else {
24
};
}
""")
fun `test with parenthesis`() = doAvailableTest("""
fn main() {
if (((true)) &/*caret*/& false) {
42;
}
}
""", """
fn main() {
if ((true)) {
if false {
42;
}
}
}
""")
fun `test without spaces`() = doAvailableTest("""
fn main() {
if true&/*caret*/&false {
42;
}
}
""", """
fn main() {
if true {
if false {
42;
}
}
}
""")
fun `test with unary expr`() = doAvailableTest("""
fn main() {
if (!(1 == 1) &/*caret*/& 42 == 24) {
42;
}
}
""", """
fn main() {
if !(1 == 1) {
if 42 == 24 {
42;
}
}
}
""")
}
| mit |
Undin/intellij-rust | src/test/kotlin/org/rust/lang/core/type/RsImplicitTraitsTest.kt | 2 | 11122 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.type
import org.intellij.lang.annotations.Language
import org.rust.CheckTestmarkHit
import org.rust.lang.core.parser.RustParserUtil.PathParsingMode.TYPE
import org.rust.lang.core.psi.RsCodeFragmentFactory
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.RsTypeReference
import org.rust.lang.core.resolve.ImplLookup
import org.rust.lang.core.resolve.TYPES
import org.rust.lang.core.types.TraitRef
import org.rust.lang.core.types.infer.TypeInferenceMarks
import org.rust.lang.core.types.rawType
import org.rust.lang.core.types.ty.*
class RsImplicitTraitsTest : RsTypificationTestBase() {
fun `test primitive types are Sized`() = checkPrimitiveTypes("Sized")
fun `test array is Sized`() = doTest("""
fn foo() -> [i32; 2] { unimplemented!() }
//^ Sized
""")
fun `test slice is not Sized`() = doTest("""
fn foo() -> Box<[i32]> { unimplemented!() }
//^ !Sized
""")
fun `test str is not Sized`() = doTest("""
fn foo() -> Box<str> { unimplemented!() }
//^ !Sized
""")
fun `test trait object is not Sized`() = doTest("""
trait Foo {}
fn foo() -> Box<Foo> { unimplemented!() }
//^ !Sized
""")
fun `test enum is Sized`() = doTest("""
enum FooBar { Foo, Bar }
fn foo() -> FooBar { unimplemented!() }
//^ Sized
""")
fun `test struct is Sized`() = doTest("""
struct Foo { foo: i32 }
fn foo() -> Foo { unimplemented!() }
//^ Sized
""")
fun `test struct with DST field is not Sized`() = doTest("""
struct Foo { foo: i32, bar: [i32] }
fn foo() -> Box<Foo> { unimplemented!() }
//^ !Sized
""")
fun `test tuple struct is Sized`() = doTest("""
struct Foo(i32);
fn foo() -> Foo { unimplemented!() }
//^ Sized
""")
fun `test tuple struct with DST field is not Sized`() = doTest("""
struct Foo(i32, [i32]);
fn foo() -> Box<Foo> { unimplemented!() }
//^ !Sized
""")
fun `test empty struct is Sized`() = doTest("""
struct Foo;
fn foo() -> Foo { unimplemented!() }
//^ Sized
""")
fun `test tuple is Sized`() = doTest("""
fn foo() -> (i32, bool) { unimplemented!() }
//^ Sized
""")
fun `test tuple with DST field is not Sized`() = doTest("""
fn foo() -> Box<(i32, [i32])> { unimplemented!() }
//^ !Sized
""")
fun `test reference is Sized`() = doTest("""
fn foo() -> &i32 { unimplemented!() }
//^ Sized
""")
fun `test pointer is Sized`() = doTest("""
fn foo() -> *const u32 { unimplemented!() }
//^ Sized
""")
fun `test type parameter is Sized by default`() = doTest("""
fn foo<T>() -> T { unimplemented!() }
//^ Sized
""")
fun `test type parameter with Sized bound is Sized`() = doTest("""
fn foo<T: Sized>() -> T { unimplemented!() }
//^ Sized
""")
fun `test type parameter with qSized bound is not Sized`() = doTest("""
fn foo<T: ?Sized>() -> Box<T> { unimplemented!() }
//^ !Sized
""")
fun `test type parameter with qSized bound is not Sized 2`() = doTest("""
fn foo<T>() -> Box<T> where T: ?Sized { unimplemented!() }
//^ !Sized
""")
fun `test type parameter with Sized bound on impl member function is Sized`() = doTest("""
impl<T: ?Sized> Box<T> {
fn foo() -> Box<T> where T: Sized { unimplemented!() }
} //^ Sized
""")
fun `test type parameter with Sized bound on triat member function is Sized`() = doTest("""
trait Tra<T: ?Sized> {
fn foo() -> T where T: Sized { todo!() }
} //^ Sized
""")
fun `test Self is qSized by default`() = doTest("""
trait Foo {
fn foo(self: Self);
//^ !Sized
}
""")
fun `test Self is Sized if trait is Sized`() = doTest("""
trait Foo : Sized {
fn foo(self: Self);
//^ Sized
}
""")
fun `test Self is Sized if trait is Sized (vie where clause)`() = doTest("""
trait Foo where Self: Sized {
fn foo(self: Self);
//^ Sized
}
""")
fun `test Self is Sized in Sized type impl`() = doTest("""
trait Foo {
fn foo(self: Self);
}
struct Bar;
impl Foo for Bar {
fn foo(self: Self) { unimplemented!() }
//^ Sized
}
""")
fun `test RPIT is Sized`() = doTest("""
trait Foo {}
fn foo() -> impl Foo { todo!() }
//^ Sized
""")
fun `test RPIT is not Sized if qSized unbound is present`() = doTest("""
trait Foo {}
fn foo() -> impl Foo+?Sized { todo!() }
//^ !Sized
""")
fun `test struct with DST field is not Sized with associated type projection`() = doTest("""
trait Trait {
type Item: ?Sized;
}
struct S<T: Trait> {
last: T::Item
}
struct X;
impl Trait for X {
type Item = [u8]; // !Sized
}
type T = S<X>;
//^ !Sized
""")
fun `test derive for generic type`() = doTest("""
struct X; // Not `Copy`
#[derive(Copy, Clone)]
struct S<T>(T);
type T = S<X>;
//^ !Copy
""")
fun `test associated type projection is Sized`() = doTest("""
trait Foo {
type Item;
}
fn foo<T: Foo>() -> T::Item { todo!() }
//^ Sized
""")
fun `test associated type projection is not Sized when qSized bound is present`() = doTest("""
trait Foo {
type Item: ?Sized;
}
fn foo<T: Foo>() -> T::Item { todo!() }
//^ !Sized
""")
fun `test tuple of 'Copy' types is 'Copy'`() = doTest("""
type T = ((), ());
//^ Copy
""")
fun `test tuple of not 'Copy' types is not 'Copy'`() = doTest("""
struct X;
type T = (i32, X);
//^ !Copy
""")
fun `test invalid self-containing struct 1`() = doTest("""
struct S {
field: Self
}
type T = S;
//^ Sized
""")
fun `test invalid self-containing struct 2`() = doTest("""
struct Rc<T>(T);
struct S {
field: Rc<Self>
}
type T = S;
//^ Sized
""")
@CheckTestmarkHit(TypeInferenceMarks.UnsizeArrayToSlice::class)
fun `test unsize array to slice`() = doTest("""
type T = [i32; 2];
//^ Unsize<[i32]>
""")
fun `test don't unsize array to slice if element types mismatch`() = doTest("""
type T = [i32; 2];
//^ !Unsize<[u8]>
""")
@CheckTestmarkHit(TypeInferenceMarks.UnsizeToTraitObject::class)
fun `test struct to trait object`() = doTest("""
struct S;
trait Foo {}
impl Foo for S {}
type T = S;
//^ Unsize<dyn Foo>
""")
@CheckTestmarkHit(TypeInferenceMarks.UnsizeTuple::class)
fun `test unsize tuple with unsize last field`() = doTest("""
type T = (i32, [i32; 2]);
//^ Unsize<(i32, [i32])>
""")
fun `test don't unsize tuple with different size`() = doTest("""
type T = (i32, i32, [i32; 2]);
//^ !Unsize<(i32, [i32])>
""")
fun `test don't unsize tuple with different types`() = doTest("""
type T = (i32, [i32; 2]);
//^ !Unsize<(u8, [i32])>
""")
@CheckTestmarkHit(TypeInferenceMarks.UnsizeStruct::class)
fun `test unsize struct with unsize last field`() = doTest("""
struct S<T: ?Sized> {
head: i32,
tail: T,
}
type T = S<[i32; 2]>;
//^ Unsize<S<[i32]>>
""")
fun `test don't unsize struct with different types`() = doTest("""
struct S<H, T: ?Sized> {
head: H,
tail: T,
}
type T = S<i32, [i32; 2]>;
//^ !Unsize<u32, S<[i32]>>
""")
fun `test don't unsize struct with multiple fields affected`() = doTest("""
struct S<T: ?Sized> {
head: T,
tail: T,
}
type T = S<[i32; 2]>;
//^ !Unsize<S<[i32]>>
""")
fun `test a type is automatically Sync`() = doTest("""
struct S;
type T = S;
//^ Sync
""")
fun `test a type is not Sync if a negative impl present`() = doTest("""
struct S;
impl !Sync for S {}
type T = S;
//^ !Sync
""")
private fun checkPrimitiveTypes(traitName: String) {
val allIntegers = TyInteger.VALUES.toTypedArray()
val allFloats = TyFloat.VALUES.toTypedArray()
for (ty in listOf(TyBool, TyChar, TyUnit, TyNever, *allIntegers, *allFloats)) {
doTest("""
fn foo() -> $ty { unimplemented!() }
//^ $traitName
""")
}
}
private fun doTest(@Language("Rust") code: String) {
val fullTestCode = """
#[lang = "sized"] pub trait Sized {}
#[lang = "copy"] pub trait Copy {}
#[lang = "unsize"] pub trait Unsize<T: ?Sized> {}
#[lang = "sync"] pub unsafe auto trait Sync {}
$code
"""
InlineFile(fullTestCode)
val (typeRef, data) = findElementAndDataInEditor<RsTypeReference>()
val (traitName, mustHaveImpl) = if (data.startsWith('!')) {
data.drop(1) to false
} else {
data to true
}
val lookup = ImplLookup.relativeTo(typeRef)
val traitPath = RsCodeFragmentFactory(project).createPath(traitName, myFixture.file as RsFile, TYPE, TYPES)
?: error("Cannot parse path `$traitName`")
val trait = traitPath.reference?.advancedResolve()?.downcast<RsTraitItem>()
?: error("Cannot resolve path `traitName` to a trait")
val hasImpl = lookup.canSelect(TraitRef(typeRef.rawType, trait))
check(mustHaveImpl == hasImpl) {
if (mustHaveImpl) {
"The trait `$traitName` must be implemented for the type `${typeRef.rawType}`, but it actually doesn't"
} else {
"The trait `$traitName` must NOT be implemented for the type `${typeRef.rawType}`, but it is actually implemented"
}
}
}
}
| mit |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/issues/actions/AnalyzeStacktraceAction.kt | 1 | 2463 | package com.github.jk1.ytplugin.issues.actions
import com.github.jk1.ytplugin.issues.model.Issue
import com.github.jk1.ytplugin.whenActive
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.ide.CopyPasteManager
import org.apache.commons.lang.StringEscapeUtils
import java.awt.datatransfer.StringSelection
import javax.swing.Icon
/**
* Checks, if issue description contains an exception and enables analyze stack trace
* action for that exception. Current implementation can recognize only one exception
* per issue and ignores comments.
*
* todo: add configurable option to skip an unscramble dialog and analyze stacktrace right away
*/
class AnalyzeStacktraceAction(private val getSelectedIssue: () -> Issue?) : IssueAction() {
override val text = "Analyze Stack Trace"
override val description = "Open the content from the issue description in the Analyze Stack Trace dialog"
override val icon: Icon = AllIcons.Actions.Lightning
override val shortcut = "control shift S"
override fun actionPerformed(event: AnActionEvent) {
event.whenActive {
val issue = getSelectedIssue.invoke()
if (issue != null && issue.hasException()) {
openAnalyzeDialog(issue, event)
}
}
}
override fun update(event: AnActionEvent) {
val issue = getSelectedIssue.invoke()
event.presentation.isEnabled = issue != null && issue.hasException()
}
private fun openAnalyzeDialog(issue: Issue, event: AnActionEvent) {
val clipboard = CopyPasteManager.getInstance()
val existingContent = clipboard.contents
// Analyze dialog uses clipboard contents, let's put a stack trace there
clipboard.setContents(StringSelection(issue.getException()))
ActionManager.getInstance().getAction("Unscramble").actionPerformed(event)
if (existingContent != null) {
// and restore everything afterwards
clipboard.setContents(existingContent)
}
}
private fun Issue.hasException() = description.contains("<pre class=\"wiki-exception\"")
private fun Issue.getException() = StringEscapeUtils.unescapeHtml(description
.split("</pre>")[1]
.replace("<br/>", "\n")
.replace("<[^>]+>".toRegex(), "")
.replace("…", ""))
} | apache-2.0 |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/setup/SetupRepositoryConnector.kt | 1 | 7980 | package com.github.jk1.ytplugin.setup
import com.github.jk1.ytplugin.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.tasks.youtrack.YouTrackRepository
import com.intellij.util.net.IdeHttpClientHelpers
import com.intellij.util.net.ssl.CertificateManager
import io.netty.handler.codec.http.HttpScheme
import org.apache.http.HttpRequest
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.CredentialsProvider
import org.apache.http.client.config.AuthSchemes
import org.apache.http.client.config.RequestConfig
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder
import java.net.URL
class SetupRepositoryConnector {
companion object {
fun setupHttpClient(repository: YouTrackRepository): CloseableHttpClient {
val requestConfigBuilder = RequestConfig.custom()
.setConnectTimeout(60000)
.setSocketTimeout(30000)
if (repository.isUseProxy) {
setupProxy(repository, requestConfigBuilder)
}
return HttpClientBuilder.create()
.disableRedirectHandling()
.setSSLContext(CertificateManager.getInstance().sslContext)
.setDefaultRequestConfig(requestConfigBuilder.build()).build()
}
private fun setupProxy(repository: YouTrackRepository, requestConfigBuilder: RequestConfig.Builder ) {
val createCredentialsProvider: CredentialsProvider = BasicCredentialsProvider()
createCredentialsProvider.setCredentials(AuthScope(
AuthScope.ANY_HOST,
AuthScope.ANY_PORT,
AuthScope.ANY_REALM, AuthSchemes.BASIC),
UsernamePasswordCredentials(repository.username, repository.password))
IdeHttpClientHelpers.ApacheHttpClient4
.setProxyForUrlIfEnabled(requestConfigBuilder, repository.url)
// Proxy authentication
IdeHttpClientHelpers.ApacheHttpClient4
.setProxyCredentialsForUrlIfEnabled(createCredentialsProvider, repository.url)
}
}
@Volatile
var noteState = NotifierState.INVALID_TOKEN
private val endpoint = "/api/users/me?fields=name"
private fun checkAndFixConnection(repository: YouTrackRepository, project: Project) {
val checker = ConnectionChecker(repository, project)
checker.onSuccess { request ->
if (isValidYouTrackVersion(repository)) {
repository.url = request.requestLine.uri.replace(endpoint, "")
logger.debug("valid YouTrack version detected")
noteState = NotifierState.SUCCESS
} else {
logger.debug("invalid YouTrack version detected")
if (noteState != NotifierState.LOGIN_ERROR){
noteState = NotifierState.INVALID_VERSION
}
}
}
checker.onVersionError { _ ->
if (getInstanceVersion() == null){
obtainYouTrackConfiguration(repository)
}
val version = getInstanceVersion()
if (version != null && version >= 2017.1 && version <= 2020.4) {
logger.debug("valid YouTrack version detected but it is not sufficient for bearer token usage")
noteState = NotifierState.INSUFFICIENT_FOR_TOKEN_VERSION
} else {
logger.debug("guest login is not allowed")
if (noteState != NotifierState.LOGIN_ERROR){
noteState = NotifierState.INVALID_TOKEN
}
}
}
checker.onRedirectionError { request, response ->
logger.debug("handling application error for ${repository.url}")
when (response.statusLine.statusCode) {
// handles both /youtrack absence (for old instances) and http instead of https protocol
in 301..399 -> {
logger.debug("handling response code 301..399 for the ${repository.url}: REDIRECT")
val location = response.getFirstHeader("Location").value
replaceRepositoryUrlWithLocation(repository, location, request)
logger.debug("url after correction: ${repository.url}")
// unloaded instance redirect can't handle /api/* suffix properly
checker.check()
}
401, 403 -> {
logger.debug("handling response code 403 for the ${repository.url}: UNAUTHORIZED")
noteState = NotifierState.UNAUTHORIZED
}
else -> {
logger.debug("handling response code other than 301..399, 403 ${repository.url}: MANUAL FIX")
if (!request.requestLine.uri.contains("/youtrack")) {
repository.url = "${repository.url}/youtrack"
logger.debug("url after manual ending fix: ${repository.url}")
checker.check()
} else {
logger.debug("no manual ending fix: LOGIN_ERROR")
noteState = NotifierState.LOGIN_ERROR
}
}
}
}
checker.onTransportError { request: HttpRequest, _: Exception ->
logger.debug("handling transport error for ${repository.url}")
// handles https instead of http protocol
if (URL(request.requestLine.uri).protocol == HttpScheme.HTTPS.toString()) {
logger.debug("handling transport error for ${repository.url}: MANUAL PROTOCOL FIX")
val repoUrl = URL(repository.url)
repository.url = URL(HttpScheme.HTTP.toString(), repoUrl.host, repoUrl.port, repoUrl.path).toString()
logger.debug("url after manual protocol fix: ${repository.url}")
checker.check()
} else {
logger.debug("no manual transport fix: LOGIN_ERROR")
noteState = NotifierState.LOGIN_ERROR
}
}
checker.check()
}
private fun replaceRepositoryUrlWithLocation(repository: YouTrackRepository, location: String, request: HttpRequest) {
if (!location.contains("/waitInstanceStartup/")) {
repository.url = if (location.contains(endpoint)){
location.replace(endpoint, "")
} else {
"${repository.url}$location"
}
} else {
if (!request.requestLine.uri.contains("/youtrack")) {
logger.debug("url after manual ending fix for waitInstanceStartup : ${repository.url}")
repository.url = "${repository.url}/youtrack"
}
}
}
fun testConnection(repository: YouTrackRepository, myProject: Project) {
logger.debug("TRY CONNECTION FOR ${repository.url}")
val task = object : Task.Modal(myProject, "Test connection", true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = "Connecting to " + repository.url + "..."
indicator.fraction = 0.0
indicator.isIndeterminate = true
checkAndFixConnection(repository, myProject)
}
}
ProgressManager.getInstance().run(task)
}
private fun isValidYouTrackVersion(repo: YouTrackRepository): Boolean {
// on the first invoke setup YouTrack configuration
obtainYouTrackConfiguration(repo)
val version = getInstanceVersion()
return version != null && version >= 2017.1
}
} | apache-2.0 |
deva666/anko | anko/idea-plugin/preview/src/org/jetbrains/kotlin/android/dslpreview/UpdateActivityNameTask.kt | 2 | 2725 | package org.jetbrains.kotlin.android.dslpreview
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.wm.ToolWindow
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.idea.internal.Location
import org.jetbrains.kotlin.idea.util.LongRunningReadTask
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import javax.swing.DefaultComboBoxModel
class UpdateActivityNameTask(
val previewManager: AnkoNlPreviewManager
) : LongRunningReadTask<PsiElement, PreviewClassDescription>() {
override fun prepareRequestInfo(): PsiElement? = with (previewManager) {
val toolWindow: ToolWindow = toolWindow ?: return null
if (!toolWindow.isVisible) return null
val editor = FileEditorManager.getInstance(project).selectedTextEditor
val location = Location.fromEditor(editor, project)
if (location.editor == null) return null
val file = location.kFile
if (file == null || !ProjectRootsUtil.isInProjectSource(file)) return null
val psiElement = file.findElementAt(location.startOffset) ?: return null
return psiElement
}
override fun cloneRequestInfo(requestInfo: PsiElement): PsiElement {
val newRequestInfo = super.cloneRequestInfo(requestInfo)
assert(requestInfo == newRequestInfo) { "cloneRequestInfo should generate same location object" }
return newRequestInfo
}
override fun hideResultOnInvalidLocation() {
}
override fun processRequest(element: PsiElement): PreviewClassDescription? {
val cacheService = KotlinCacheService.getInstance(previewManager.project)
return previewManager.classResolver.resolveClassDescription(element, cacheService)
}
private fun indexOf(model: DefaultComboBoxModel<Any>, description: PreviewClassDescription): Int? {
for (i in 0..(model.size - 1)) {
val item = model.getElementAt(i) as? PreviewClassDescription ?: continue
if (item == description) return i
}
return null
}
private fun setSelection(model: DefaultComboBoxModel<Any>, description: PreviewClassDescription): Boolean {
val index = indexOf(model, description) ?: return false
model.selectedItem = model.getElementAt(index)
return true
}
override fun onResultReady(requestInfo: PsiElement, description: PreviewClassDescription?) = with (previewManager) {
if (description == null) return
val model = myActivityListModel
if (!setSelection(model, description)) {
resolveAvailableClasses()
setSelection(model, description)
}
}
}
| apache-2.0 |
norswap/violin | src/norswap/violin/Utils.kt | 1 | 4585 | @file:Suppress("PackageDirectoryMismatch")
package norswap.violin.utils
import java.io.PrintWriter
import java.io.StringWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.util.Comparator
/**
* This file contains a smattering of functions that do not find their place anywhere else.
*/
// -------------------------------------------------------------------------------------------------
/**
* Returns the result of [f].
* The point is to allow statements in an expression context.
*/
inline fun <T> expr(f: () -> T): T = f()
// -------------------------------------------------------------------------------------------------
/**
* Returns the receiver after evaluating [f] on it.
*/
inline infix fun <T> T.after(f: (T) -> Unit): T {
f(this)
return this
}
// -------------------------------------------------------------------------------------------------
/**
* Syntactic sugar for `if (this) then f() else null`.
*/
infix inline fun <T> Boolean.then (f: () -> T): T?
= if (this) f() else null
// -------------------------------------------------------------------------------------------------
/**
* Analogous to `Kotlin.arrayOf`, but doesn't require reification.
*/
@Suppress("UNCHECKED_CAST")
fun <T: Any> array(vararg items: T) = items as Array<T>
// -------------------------------------------------------------------------------------------------
/**
* Shorthand for [StringBuilder.append].
*/
operator fun StringBuilder.plusAssign(s: String) { append(s) }
// -------------------------------------------------------------------------------------------------
/**
* Shorthand for [StringBuilder.append].
*/
operator fun StringBuilder.plusAssign(o: Any?) { append(o) }
// -------------------------------------------------------------------------------------------------
/**
* Casts the receiver to [T].
*
* This is more useful than regular casts because it enables casts to non-denotable types
* through type inference.
*/
@Suppress("UNCHECKED_CAST")
fun <T> Any?.cast() = this as T
// -------------------------------------------------------------------------------------------------
/**
* Like `String.substring` but allows [start] and [end] to be negative numbers.
*
* The first item in the sequence has index `0` (same as `-length`).
* The last item in the sequence has index `length-1` (same as `-1`).
*
* The [start] bound is always inclusive.
* The [end] bound is exclusive if positive, else inclusive.
*
* Throws an [IndexOutOfBoundsException] if the [start] bounds refers to an index below `0` or
* if [end] refers to an index equal to or past `CharSequence.length`.
*
* It is fine to call this with [start] referring to `a` and [end] referring to `b` such that
* `a > b`, as long the previous condition is respected. The result is then the empty string.
*/
operator fun CharSequence.get(start: Int, end: Int = length): String {
val a = if (start >= 0) start else length + start
val b = if (end >= 0) end else length + end + 1
if (a < 0) throw IndexOutOfBoundsException("Start index < 0")
if (b > length) throw IndexOutOfBoundsException("End index > length")
if (a > b) return ""
return substring(a, b)
}
// -------------------------------------------------------------------------------------------------
/**
* Reads a complete file and returns its contents as a string.
* @throws IOException see [Files.readAllBytes]
* @throws InvalidPathException see [Paths.get]
*/
fun readFile(file: String)
= String(Files.readAllBytes(Paths.get(file)))
// -------------------------------------------------------------------------------------------------
/**
* Returns a comparator for type T that delegates to a `Comparable` type U.
*/
fun <T, U: Comparable<U>> comparator(f: (T) -> U)
= Comparator<T> { o1, o2 -> f(o1).compareTo(f(o2)) }
// -------------------------------------------------------------------------------------------------
/**
* Returns a comparator for type [T] that delegates the receiver, a comparator for type [U].
*/
fun <T, U> Comparator<U>.derive(f: (T) -> U)
= Comparator<T> { o1, o2 -> compare(f(o1), f(o2)) }
// -------------------------------------------------------------------------------------------------
/**
* Returns a string representation of the Throwable's stack trace.
*/
fun Throwable.stackTraceString(): String {
val sw = StringWriter()
printStackTrace(PrintWriter(sw))
return sw.toString()
}
// ------------------------------------------------------------------------------------------------- | bsd-3-clause |
androidx/androidx | graphics/graphics-core/src/main/java/androidx/opengl/EGLHandle.kt | 3 | 1089 | /*
* Copyright 2022 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 androidx.opengl
/**
* Interface used to wrap native EGL objects to create type safe objects
*/
@Suppress("AcronymName")
interface EGLHandle {
/**
* Returns the native handle of the wrapped EGL object. This handle can be
* cast to the corresponding native type on the native side.
*
* For example, EGLDisplay dpy = (EGLDisplay)handle;
*
* @return the native handle of the wrapped EGL object.
*/
val nativeHandle: Long
} | apache-2.0 |
config4k/config4k | src/test/kotlin/io/github/config4k/TestEnum.kt | 1 | 408 | package io.github.config4k
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
class TestEnum : WordSpec({
"Config.extract<Size>" should {
"return SMALL" {
val config = "key = SMALL".toConfig()
val small = config.extract<Size>("key")
small shouldBe Size.SMALL
}
}
})
enum class Size {
SMALL,
MEDIUM,
LARGE
}
| apache-2.0 |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/GLES32.kt | 1 | 42137 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
import org.lwjgl.opengles.BufferType.*
val GLES32 = "GLES32".nativeClassGLES("GLES32", postfix = "") {
documentation =
"The core OpenGL ES 3.2 functionality."
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.",
"MULTISAMPLE_LINE_WIDTH_RANGE_ARB"..0x9381,
"MULTISAMPLE_LINE_WIDTH_GRANULARITY_ARB"..0x9382
)
// KHR_blend_equation_advanced
IntConstant(
"Accepted by the {@code mode} parameter of BlendEquation and BlendEquationi.",
"MULTIPLY"..0x9294,
"SCREEN"..0x9295,
"OVERLAY"..0x9296,
"DARKEN"..0x9297,
"LIGHTEN"..0x9298,
"COLORDODGE"..0x9299,
"COLORBURN"..0x929A,
"HARDLIGHT"..0x929B,
"SOFTLIGHT"..0x929C,
"DIFFERENCE"..0x929E,
"EXCLUSION"..0x92A0,
"HSL_HUE"..0x92AD,
"HSL_SATURATION"..0x92AE,
"HSL_COLOR"..0x92AF,
"HSL_LUMINOSITY"..0x92B0
)
void(
"BlendBarrier",
"""
Specifies a boundary between passes when using advanced blend equations.
When using advanced blending equations, applications should split their rendering into a collection of blending passes, none of which touch an
individual sample in the framebuffer more than once. The results of blending are undefined if the sample being blended has been touched previously in
the same pass. Any command that causes the value of a sample to be modified using the framebuffer is considered to touch the sample, including clears,
blended or unblended primitives, and GLES30#BlitFramebuffer() copies.
"""
)
// OES_copy_image
void(
"CopyImageSubData",
"",
GLuint.IN("srcName", ""),
GLenum.IN("srcTarget", ""),
GLint.IN("srcLevel", ""),
GLint.IN("srcX", ""),
GLint.IN("srcY", ""),
GLint.IN("srcZ", ""),
GLuint.IN("dstName", ""),
GLenum.IN("dstTarget", ""),
GLint.IN("dstLevel", ""),
GLint.IN("dstX", ""),
GLint.IN("dstY", ""),
GLint.IN("dstZ", ""),
GLsizei.IN("srcWidth", ""),
GLsizei.IN("srcHeight", ""),
GLsizei.IN("srcDepth", "")
)
// KHR_debug
IntConstant(
"Tokens accepted by the {@code target} parameters of Enable, Disable, and IsEnabled.",
"DEBUG_OUTPUT"..0x92E0,
"DEBUG_OUTPUT_SYNCHRONOUS"..0x8242
)
IntConstant(
"Returned by GetIntegerv when {@code pname} is CONTEXT_FLAGS.",
"CONTEXT_FLAG_DEBUG_BIT"..0x00000002
)
IntConstant(
"Tokens accepted by the {@code value} parameters of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev and GetInteger64v.",
"MAX_DEBUG_MESSAGE_LENGTH"..0x9143,
"MAX_DEBUG_LOGGED_MESSAGES"..0x9144,
"DEBUG_LOGGED_MESSAGES"..0x9145,
"DEBUG_NEXT_LOGGED_MESSAGE_LENGTH"..0x8243,
"MAX_DEBUG_GROUP_STACK_DEPTH"..0x826C,
"DEBUG_GROUP_STACK_DEPTH"..0x826D,
"MAX_LABEL_LENGTH"..0x82E8
)
IntConstant(
"Tokens accepted by the {@code pname} parameter of GetPointerv.",
"DEBUG_CALLBACK_FUNCTION"..0x8244,
"DEBUG_CALLBACK_USER_PARAM"..0x8245
)
val DebugSources = IntConstant(
"""
Tokens accepted or provided by the {@code source} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC, and the {@code sources} parameter
of GetDebugMessageLog.
""",
"DEBUG_SOURCE_API"..0x8246,
"DEBUG_SOURCE_WINDOW_SYSTEM"..0x8247,
"DEBUG_SOURCE_SHADER_COMPILER"..0x8248,
"DEBUG_SOURCE_THIRD_PARTY"..0x8249,
"DEBUG_SOURCE_APPLICATION"..0x824A,
"DEBUG_SOURCE_OTHER"..0x824B
).javaDocLinks
val DebugTypes = IntConstant(
"""
Tokens accepted or provided by the {@code type} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC, and the {@code types} parameter of
GetDebugMessageLog.
""",
"DEBUG_TYPE_ERROR"..0x824C,
"DEBUG_TYPE_DEPRECATED_BEHAVIOR"..0x824D,
"DEBUG_TYPE_UNDEFINED_BEHAVIOR"..0x824E,
"DEBUG_TYPE_PORTABILITY"..0x824F,
"DEBUG_TYPE_PERFORMANCE"..0x8250,
"DEBUG_TYPE_OTHER"..0x8251,
"DEBUG_TYPE_MARKER"..0x8268
).javaDocLinks
IntConstant(
"""
Tokens accepted or provided by the {@code type} parameters of DebugMessageControl and DEBUGPROC, and the {@code types} parameter of GetDebugMessageLog.
""",
"DEBUG_TYPE_PUSH_GROUP"..0x8269,
"DEBUG_TYPE_POP_GROUP"..0x826A
)
val DebugSeverities = IntConstant(
"""
Tokens accepted or provided by the {@code severity} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC callback functions, and the
{@code severities} parameter of GetDebugMessageLog.
""",
"DEBUG_SEVERITY_HIGH"..0x9146,
"DEBUG_SEVERITY_MEDIUM"..0x9147,
"DEBUG_SEVERITY_LOW"..0x9148,
"DEBUG_SEVERITY_NOTIFICATION"..0x826B
).javaDocLinks
IntConstant(
"Returned by GetError.",
"STACK_UNDERFLOW"..0x0504,
"STACK_OVERFLOW"..0x0503
)
val DebugIdentifiers = IntConstant(
"Tokens accepted or provided by the {@code identifier} parameters of ObjectLabel and GetObjectLabel.",
"BUFFER"..0x82E0,
"SHADER"..0x82E1,
"PROGRAM"..0x82E2,
"QUERY"..0x82E3,
"PROGRAM_PIPELINE"..0x82E4,
"SAMPLER"..0x82E6
).javaDocLinks
void(
"DebugMessageControl",
"""
Controls the volume of debug output in the active debug group, by disabling specific or groups of messages.
If {@code enabled} is GLES20#TRUE, the referenced subset of messages will be enabled. If GLES20#FALSE, then those messages will be disabled.
This command can reference different subsets of messages by first considering the set of all messages, and filtering out messages based on the following
ways:
${ul(
"""
If {@code source}, {@code type}, or {@code severity} is GLES20#DONT_CARE, the messages from all sources, of all types, or of all severities are
referenced respectively.
""",
"""
When values other than GLES20#DONT_CARE are specified, all messages whose source, type, or severity match the specified {@code source}, {@code type},
or {@code severity} respectively will be referenced.
""",
"""
If {@code count} is greater than zero, then {@code ids} is an array of {@code count} message IDs for the specified combination of {@code source} and
{@code type}. In this case, if {@code source} or {@code type} is GLES20#DONT_CARE, or {@code severity} is not GLES20#DONT_CARE, the error
GLES20#INVALID_OPERATION is generated.
"""
)}
Unrecognized message IDs in {@code ids} are ignored. If {@code count} is zero, the value if {@code ids} is ignored.
Although messages are grouped into an implicit hierarchy by their sources and types, there is no explicit per-source, per-type or per-severity enabled
state. Instead, the enabled state is stored individually for each message. There is no difference between disabling all messages from one source in a
single call, and individually disabling all messages from that source using their types and IDs.
If the #DEBUG_OUTPUT state is disabled the GL operates the same as if messages of every {@code source}, {@code type} or {@code severity} are
disabled.
""",
GLenum.IN("source", "the source of debug messages to enable or disable", DebugSources),
GLenum.IN("type", "the type of debug messages to enable or disable", DebugTypes),
GLenum.IN("severity", "the severity of debug messages to enable or disable", DebugSeverities),
AutoSize("ids")..GLsizei.IN("count", "the length of the array {@code ids}"),
SingleValue("id")..const..GLuint_p.IN("ids", "an array of unsigned integers containing the ids of the messages to enable or disable"),
GLboolean.IN("enabled", "whether the selected messages should be enabled or disabled")
)
void(
"DebugMessageInsert",
"""
This function can be called by applications and third-party libraries to generate their own messages, such as ones containing timestamp information or
signals about specific render system events.
The value of {@code id} specifies the ID for the message and {@code severity} indicates its severity level as defined by the caller. The string
{@code buf} contains the string representation of the message. The parameter {@code length} contains the number of characters in {@code buf}. If
{@code length} is negative, it is implied that {@code buf} contains a null terminated string. The error GLES20#INVALID_VALUE will be generated if the
number of characters in {@code buf}, excluding the null terminator when {@code length} is negative, is not less than the value of
#MAX_DEBUG_MESSAGE_LENGTH.
If the #DEBUG_OUTPUT state is disabled calls to DebugMessageInsert are discarded and do not generate an error.
""",
GLenum.IN("source", "the source of the debug message to insert", DebugSources),
GLenum.IN("type", "the type of the debug message insert", DebugTypes),
GLuint.IN("id", "the user-supplied identifier of the message to insert", DebugSeverities),
GLenum.IN("severity", "the severity of the debug messages to insert"),
AutoSize("message")..GLsizei.IN("length", "the length of the string contained in the character array whose address is given by {@code message}"),
const..GLcharUTF8_p.IN("message", "a character array containing the message to insert")
)
void(
"DebugMessageCallback",
"""
Specifies a callback to receive debugging messages from the GL.
The function's prototype must follow the type definition of DEBUGPROC including its platform-dependent calling convention. Anything else will result in
undefined behavior. Only one debug callback can be specified for the current context, and further calls overwrite the previous callback. Specifying
$NULL as the value of {@code callback} clears the current callback and disables message output through callbacks. Applications can provide
user-specified data through the pointer {@code userParam}. The context will store this pointer and will include it as one of the parameters in each call
to the callback function.
If the application has specified a callback function for receiving debug output, the implementation will call that function whenever any enabled message
is generated. The source, type, ID, and severity of the message are specified by the DEBUGPROC parameters {@code source}, {@code type}, {@code id}, and
{@code severity}, respectively. The string representation of the message is stored in {@code message} and its length (excluding the null-terminator) is
stored in {@code length}. The parameter {@code userParam} is the user-specified parameter that was given when calling DebugMessageCallback.
Applications can query the current callback function and the current user-specified parameter by obtaining the values of #DEBUG_CALLBACK_FUNCTION
and #DEBUG_CALLBACK_USER_PARAM, respectively.
Applications that specify a callback function must be aware of certain special conditions when executing code inside a callback when it is called by the
GL, regardless of the debug source.
The memory for {@code message} is owned and managed by the GL, and should only be considered valid for the duration of the function call.
The behavior of calling any GL or window system function from within the callback function is undefined and may lead to program termination.
Care must also be taken in securing debug callbacks for use with asynchronous debug output by multi-threaded GL implementations.
If the #DEBUG_OUTPUT state is disabled then the GL will not call the callback function.
""",
nullable..GLDEBUGPROC.IN("callback", "a callback function that will be called when a debug message is generated"),
nullable..const..voidptr.IN(
"userParam",
"a user supplied pointer that will be passed on each invocation of {@code callback}"
)
)
GLuint(
"GetDebugMessageLog",
"""
Retrieves messages from the debug message log.
This function fetches a maximum of {@code count} messages from the message log, and will return the number of messages successfully fetched.
Messages will be fetched from the log in order of oldest to newest. Those messages that were fetched will be removed from the log.
The sources, types, severities, IDs, and string lengths of fetched messages will be stored in the application-provided arrays {@code sources},
{@code types}, {@code severities}, {@code ids}, and {@code lengths}, respectively. The application is responsible for allocating enough space for each
array to hold up to {@code count} elements. The string representations of all fetched messages are stored in the {@code messageLog} array. If multiple
messages are fetched, their strings are concatenated into the same {@code messageLog} array and will be separated by single null terminators. The last
string in the array will also be null-terminated. The maximum size of {@code messageLog}, including the space used by all null terminators, is given by
{@code bufSize}. If {@code bufSize} is less than zero and {@code messageLog} is not $NULL, an GLES20#INVALID_VALUE error will be generated. If a message's
string, including its null terminator, can not fully fit within the {@code messageLog} array's remaining space, then that message and any subsequent
messages will not be fetched and will remain in the log. The string lengths stored in the array {@code lengths} include the space for the null terminator of each string.
Any or all of the arrays {@code sources}, {@code types}, {@code ids}, {@code severities}, {@code lengths} and {@code messageLog} can also be null
pointers, which causes the attributes for such arrays to be discarded when messages are fetched, however those messages will still be removed from the
log. Thus to simply delete up to {@code count} messages from the message log while ignoring their attributes, the application can call the function with
null pointers for all attribute arrays.
If the context was created without the #CONTEXT_FLAG_DEBUG_BIT, then the GL can opt to never add messages to the message log so GetDebugMessageLog will
always return zero.
""",
GLuint.IN("count", "the number of debug messages to retrieve from the log"),
AutoSize("messageLog")..GLsizei.IN("bufsize", "the size of the buffer whose address is given by {@code messageLog}"),
Check("count")..nullable..GLenum_p.OUT("sources", "an array of variables to receive the sources of the retrieved messages"),
Check("count")..nullable..GLenum_p.OUT("types", "an array of variables to receive the types of the retrieved messages"),
Check("count")..nullable..GLuint_p.OUT("ids", "an array of unsigned integers to receive the ids of the retrieved messages"),
Check("count")..nullable..GLenum_p.OUT("severities", "an array of variables to receive the severites of the retrieved messages"),
Check("count")..nullable..GLsizei_p.OUT("lengths", "an array of variables to receive the lengths of the received messages"),
nullable..GLcharUTF8_p.OUT("messageLog", "an array of characters that will receive the messages")
)
void(
"GetPointerv",
"",
GLenum.IN("pname", ""),
ReturnParam..Check(1)..void_pp.OUT("params", "")
)
void(
"PushDebugGroup",
"""
Pushes a debug group described by the string {@code message} into the command stream. The value of {@code id} specifies the ID of messages generated.
The parameter {@code length} contains the number of characters in {@code message}. If {@code length} is negative, it is implied that {@code message}
contains a null terminated string. The message has the specified {@code source} and {@code id}, {@code type} #DEBUG_TYPE_PUSH_GROUP, and
{@code severity} #DEBUG_SEVERITY_NOTIFICATION. The GL will put a new debug group on top of the debug group stack which inherits the control of the
volume of debug output of the debug group previously residing on the top of the debug group stack. Because debug groups are strictly hierarchical, any
additional control of the debug output volume will only apply within the active debug group and the debug groups pushed on top of the active debug
group.
An GLES20#INVALID_ENUM error is generated if the value of {@code source} is neither #DEBUG_SOURCE_APPLICATION nor #DEBUG_SOURCE_THIRD_PARTY. An
GLES20#INVALID_VALUE error is generated if {@code length} is negative and the number of characters in {@code message}, excluding the null-terminator,
is not less than the value of #MAX_DEBUG_MESSAGE_LENGTH.
""",
GLenum.IN("source", "the source of the debug message", "#DEBUG_SOURCE_APPLICATION #DEBUG_SOURCE_THIRD_PARTY"),
GLuint.IN("id", "the identifier of the message"),
AutoSize("message")..GLsizei.IN("length", "the length of the message to be sent to the debug output stream"),
const..GLcharUTF8_p.IN("message", "a string containing the message to be sent to the debug output stream")
)
void(
"PopDebugGroup",
"""
Pops the active debug group. When a debug group is popped, the GL will also generate a debug output message describing its cause based on the
{@code message} string, the source {@code source}, and an ID {@code id} submitted to the associated #PushDebugGroup() command.
#DEBUG_TYPE_PUSH_GROUP and #DEBUG_TYPE_POP_GROUP share a single namespace for message {@code id}. {@code severity} has the value
#DEBUG_SEVERITY_NOTIFICATION. The {@code type} has the value #DEBUG_TYPE_POP_GROUP. Popping a debug group restores the debug output volume
control of the parent debug group.
Attempting to pop the default debug group off the stack generates a #STACK_UNDERFLOW error; pushing a debug group onto a stack containing
#MAX_DEBUG_GROUP_STACK_DEPTH minus one elements will generate a #STACK_OVERFLOW error.
"""
)
void(
"ObjectLabel",
"Labels a named object identified within a namespace.",
GLenum.IN(
"identifier",
"the namespace from which the name of the object is allocated",
DebugIdentifiers + " GLES20#TEXTURE GLES20#RENDERBUFFER GLES20#FRAMEBUFFER GLES30#TRANSFORM_FEEDBACK"
),
GLuint.IN("name", "the name of the object to label"),
AutoSize("label")..GLsizei.IN("length", "the length of the label to be used for the object"),
const..GLcharUTF8_p.IN("label", "a string containing the label to assign to the object")
)
void(
"GetObjectLabel",
"Retrieves the label of a named object identified within a namespace.",
GLenum.IN(
"identifier",
"the namespace from which the name of the object is allocated",
DebugIdentifiers + " GLES20#TEXTURE GLES20#RENDERBUFFER GLES20#FRAMEBUFFER GLES30#TRANSFORM_FEEDBACK"
),
GLuint.IN("name", "the name of the object whose label to retrieve"),
AutoSize("label")..GLsizei.IN("bufSize", "the length of the buffer whose address is in {@code label}"),
Check(1)..nullable..GLsizei_p.OUT("length", "the address of a variable to receive the length of the object label"),
Return("length", "GLES20.glGetInteger(GL_MAX_LABEL_LENGTH)")..GLcharUTF8_p.OUT("label", "a string that will receive the object label")
)
void(
"ObjectPtrLabel",
"Labels a sync object identified by a pointer.",
voidptr.IN("ptr", "a pointer identifying a sync object"),
AutoSize("label")..GLsizei.IN("length", "the length of the label to be used for the object"),
const..GLcharUTF8_p.IN("label", "a string containing the label to assign to the object")
)
void(
"GetObjectPtrLabel",
"Retrieves the label of a sync object identified by a pointer.",
voidptr.IN("ptr", "the name of the sync object whose label to retrieve"),
AutoSize("label")..GLsizei.IN("bufSize", "the length of the buffer whose address is in {@code label}"),
Check(1)..nullable..GLsizei_p.OUT("length", "a variable to receive the length of the object label"),
Return("length", "GLES20.glGetInteger(GL_MAX_LABEL_LENGTH)")..GLcharUTF8_p.OUT("label", "a string that will receive the object label")
)
// OES_draw_buffers_indexed
void(
"Enablei",
"",
GLenum.IN("target", ""),
GLuint.IN("index", "")
)
void(
"Disablei",
"",
GLenum.IN("target", ""),
GLuint.IN("index", "")
)
void(
"BlendEquationi",
"",
GLuint.IN("buf", ""),
GLenum.IN("mode", "")
)
void(
"BlendEquationSeparatei",
"",
GLuint.IN("buf", ""),
GLenum.IN("modeRGB", ""),
GLenum.IN("modeAlpha", "")
)
void(
"BlendFunci",
"",
GLuint.IN("buf", ""),
GLenum.IN("src", ""),
GLenum.IN("dst", "")
)
void(
"BlendFuncSeparatei",
"",
GLuint.IN("buf", ""),
GLenum.IN("srcRGB", ""),
GLenum.IN("dstRGB", ""),
GLenum.IN("srcAlpha", ""),
GLenum.IN("dstAlpha", "")
)
void(
"ColorMaski",
"",
GLuint.IN("index", ""),
GLboolean.IN("r", ""),
GLboolean.IN("g", ""),
GLboolean.IN("b", ""),
GLboolean.IN("a", "")
)
GLboolean(
"IsEnabledi",
"",
GLenum.IN("target", ""),
GLuint.IN("index", "")
)
// OES_draw_elements_base_vertex
void(
"DrawElementsBaseVertex",
"",
GLenum.IN("mode", ""),
AutoSizeShr("GLESChecks.typeToByteShift(type)", "indices")..GLsizei.IN("count", ""),
AutoType("indices", GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT)..GLenum.IN("type", ""),
ELEMENT_ARRAY_BUFFER..const..void_p.IN("indices", ""),
GLint.IN("basevertex", "")
)
void(
"DrawRangeElementsBaseVertex",
"",
GLenum.IN("mode", ""),
GLuint.IN("start", ""),
GLuint.IN("end", ""),
AutoSizeShr("GLESChecks.typeToByteShift(type)", "indices")..GLsizei.IN("count", ""),
AutoType("indices", GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT)..GLenum.IN("type", ""),
ELEMENT_ARRAY_BUFFER..const..void_p.IN("indices", ""),
GLint.IN("basevertex", "")
)
void(
"DrawElementsInstancedBaseVertex",
"",
GLenum.IN("mode", ""),
AutoSizeShr("GLESChecks.typeToByteShift(type)", "indices")..GLsizei.IN("count", ""),
AutoType("indices", GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT)..GLenum.IN("type", ""),
ELEMENT_ARRAY_BUFFER..const..void_p.IN("indices", ""),
GLsizei.IN("instancecount", ""),
GLint.IN("basevertex", "")
)
// OES_geometry_shader
IntConstant(
"""
Accepted by the {@code type} parameter of CreateShader and CreateShaderProgramv, by the {@code pname} parameter of GetProgramPipelineiv and returned in
the {@code params} parameter of GetShaderiv when {@code pname} is SHADER_TYPE.
""",
"GEOMETRY_SHADER"..0x8DD9
)
IntConstant(
"Accepted by the {@code stages} parameter of UseProgramStages.",
"GEOMETRY_SHADER_BIT"..0x00000004
)
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"GEOMETRY_LINKED_VERTICES_OUT"..0x8916,
"GEOMETRY_LINKED_INPUT_TYPE"..0x8917,
"GEOMETRY_LINKED_OUTPUT_TYPE"..0x8918,
"GEOMETRY_SHADER_INVOCATIONS"..0x887F
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetInteger64v.",
"LAYER_PROVOKING_VERTEX"..0x825E,
"MAX_GEOMETRY_UNIFORM_COMPONENTS"..0x8DDF,
"MAX_GEOMETRY_UNIFORM_BLOCKS"..0x8A2C,
"MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS"..0x8A32,
"MAX_GEOMETRY_INPUT_COMPONENTS"..0x9123,
"MAX_GEOMETRY_OUTPUT_COMPONENTS"..0x9124,
"MAX_GEOMETRY_OUTPUT_VERTICES"..0x8DE0,
"MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS"..0x8DE1,
"MAX_GEOMETRY_SHADER_INVOCATIONS"..0x8E5A,
"MAX_GEOMETRY_TEXTURE_IMAGE_UNITS"..0x8C29,
"MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS"..0x92CF,
"MAX_GEOMETRY_ATOMIC_COUNTERS"..0x92D5,
"MAX_GEOMETRY_IMAGE_UNIFORMS"..0x90CD,
"MAX_GEOMETRY_SHADER_STORAGE_BLOCKS"..0x90D7
)
IntConstant(
"Returned in the {@code data} parameter from a Get query with a {@code pname} of LAYER_PROVOKING_VERTEX.",
"FIRST_VERTEX_CONVENTION"..0x8E4D,
"LAST_VERTEX_CONVENTION"..0x8E4E,
"UNDEFINED_VERTEX"..0x8260
)
IntConstant(
"Accepted by the {@code target} parameter of BeginQuery, EndQuery, GetQueryiv, and GetQueryObjectuiv.",
"PRIMITIVES_GENERATED"..0x8C87
)
IntConstant(
"Accepted by the {@code mode} parameter of DrawArrays, DrawElements, and other commands which draw primitives.",
"LINES_ADJACENCY"..0xA,
"LINE_STRIP_ADJACENCY"..0xB,
"TRIANGLES_ADJACENCY"..0xC,
"TRIANGLE_STRIP_ADJACENCY"..0xD
)
IntConstant(
"Accepted by the {@code pname} parameter of FramebufferParameteri, and GetFramebufferParameteriv.",
"FRAMEBUFFER_DEFAULT_LAYERS"..0x9312
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetInteger64v, and GetFloatv.",
"MAX_FRAMEBUFFER_LAYERS"..0x9317
)
IntConstant(
"Returned by CheckFramebufferStatus.",
"FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"..0x8DA8
)
IntConstant(
"Accepted by the {@code pname} parameter of GetFramebufferAttachmentParameteriv.",
"FRAMEBUFFER_ATTACHMENT_LAYERED"..0x8DA7
)
IntConstant(
"Accepted by the {@code props} parameter of GetProgramResourceiv.",
"REFERENCED_BY_GEOMETRY_SHADER"..0x9309
)
void(
"FramebufferTexture",
"",
GLenum.IN("target", ""),
GLenum.IN("attachment", ""),
GLuint.IN("texture", ""),
GLint.IN("level", "")
)
// OES_primitive_bounding_box
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.",
"PRIMITIVE_BOUNDING_BOX_ARB"..0x92BE
)
void(
"PrimitiveBoundingBox",
"""
Specifies the primitive bounding box.
Implementations may be able to optimize performance if the application provides bounds of primitives that will be generated by the tessellation
primitive generator or the geometry shader prior to executing those stages. If the provided bounds are incorrect and primitives extend beyond them, the
rasterizer may or may not generate fragments for the portions of primitives outside the bounds.
""",
GLfloat.IN("minX", "the minimum x clip space coordinate"),
GLfloat.IN("minY", "the minimum y clip space coordinate"),
GLfloat.IN("minZ", "the minimum z clip space coordinate"),
GLfloat.IN("minW", "the minimum w clip space coordinate"),
GLfloat.IN("maxX", "the maximum x clip space coordinate"),
GLfloat.IN("maxY", "the maximum y clip space coordinate"),
GLfloat.IN("maxZ", "the maximum z clip space coordinate"),
GLfloat.IN("maxW", "the maximum w clip space coordinate")
)
// KHR_robustness
IntConstant(
"Returned by #GetGraphicsResetStatus().",
"NO_ERROR"..0x0000,
"GUILTY_CONTEXT_RESET"..0x8253,
"INNOCENT_CONTEXT_RESET"..0x8254,
"UNKNOWN_CONTEXT_RESET"..0x8255
)
IntConstant(
"Accepted by the {@code value} parameter of GetBooleanv, GetIntegerv, and GetFloatv.",
"CONTEXT_ROBUST_ACCESS"..0x90F3,
"RESET_NOTIFICATION_STRATEGY"..0x8256
)
IntConstant(
"Returned by GetIntegerv and related simple queries when {@code value} is #RESET_NOTIFICATION_STRATEGY.",
"LOSE_CONTEXT_ON_RESET"..0x8252,
"NO_RESET_NOTIFICATION"..0x8261
)
IntConstant(
"Returned by GLES20#GetError().",
"CONTEXT_LOST"..0x0507
)
GLenum(
"GetGraphicsResetStatus",
"""
Indicates if the GL context has been in a reset state at any point since the last call to GetGraphicsResetStatus:
${ul(
"GLES20#NO_ERROR indicates that the GL context has not been in a reset state since the last call.",
"#GUILTY_CONTEXT_RESET indicates that a reset has been detected that is attributable to the current GL context.",
"#INNOCENT_CONTEXT_RESET indicates a reset has been detected that is not attributable to the current GL context.",
"#UNKNOWN_CONTEXT_RESET indicates a detected graphics reset whose cause is unknown."
)}
If a reset status other than NO_ERROR is returned and subsequent calls return NO_ERROR, the context reset was encountered and completed. If a reset
status is repeatedly returned, the context may be in the process of resetting.
Reset notification behavior is determined at context creation time, and may be queried by calling GetIntegerv with the symbolic constant
#RESET_NOTIFICATION_STRATEGY.
If the reset notification behavior is #NO_RESET_NOTIFICATION, then the implementation will never deliver notification of reset events, and
GetGraphicsResetStatus will always return NO_ERROR.
If the behavior is #LOSE_CONTEXT_ON_RESET, a graphics reset will result in a lost context and require creating a new context as described
above. In this case GetGraphicsResetStatus will return an appropriate value from those described above.
If a graphics reset notification occurs in a context, a notification must also occur in all other contexts which share objects with that context.
After a graphics reset has occurred on a context, subsequent GL commands on that context (or any context which shares with that context) will generate a
#CONTEXT_LOST error. Such commands will not have side effects (in particular, they will not modify memory passed by pointer for query results,
and may not block indefinitely or cause termination of the application. Exceptions to this behavior include:
${ul(
"""
GLES20#GetError() and GetGraphicsResetStatus behave normally following a graphics reset, so that the application can determine a reset has
occurred, and when it is safe to destroy and recreate the context.
""",
"""
Any commands which might cause a polling application to block indefinitely will generate a CONTEXT_LOST error, but will also return a value
indicating completion to the application.
"""
)}
"""
)
void(
"ReadnPixels",
"Behaves identically to GLES20#ReadPixels() except that it does not write more than {@code bufSize} bytes into {@code data}",
GLint.IN("x", "the left pixel coordinate"),
GLint.IN("y", "the lower pixel coordinate"),
GLsizei.IN("width", "the number of pixels to read in the x-dimension"),
GLsizei.IN("height", "the number of pixels to read in the y-dimension"),
GLenum.IN("format", "the pixel format"),
GLenum.IN("type", "the pixel type"),
AutoSize("pixels")..GLsizei.IN("bufSize", "the maximum number of bytes to write into {@code data}"),
PIXEL_PACK_BUFFER..MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT
)..void_p.OUT("pixels", "a buffer in which to place the returned pixel data")
)
void(
"GetnUniformfv",
"Returns the value or values of a uniform of the default uniform block.",
GLuint.IN("program", "the program object"),
GLint.IN("location", "the uniform location"),
AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of bytes to write to {@code params}"),
ReturnParam..GLfloat_p.OUT("params", "the buffer in which to place the returned data")
)
void(
"GetnUniformiv",
"Integer version of #GetnUniformfv().",
GLuint.IN("program", "the program object"),
GLint.IN("location", "the uniform location"),
AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of bytes to write to {@code params}"),
ReturnParam..GLfloat_p.OUT("params", "the buffer in which to place the returned data")
)
void(
"GetnUniformuiv",
"Unsigned version of #GetnUniformiv().",
GLuint.IN("program", "the program object"),
GLint.IN("location", "the uniform location"),
AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of bytes to write to {@code params}"),
ReturnParam..GLfloat_p.OUT("params", "the buffer in which to place the returned data")
)
// OES_sample_shading
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetInteger64v.
""",
"SAMPLE_SHADING"..0x8C36
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetInteger64v, and GetFloatv.",
"MIN_SAMPLE_SHADING_VALUE"..0x8C37
)
void(
"MinSampleShading",
"",
GLfloat.IN("value", "")
)
// OES_multisample_interpolation_features
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetInteger64v.",
"MIN_FRAGMENT_INTERPOLATION_OFFSET"..0x8E5B,
"MAX_FRAGMENT_INTERPOLATION_OFFSET"..0x8E5C,
"FRAGMENT_INTERPOLATION_OFFSET_BITS"..0x8E5D
)
// OES_tessellation_shader
IntConstant(
"Accepted by the {@code mode} parameter of DrawArrays, DrawElements, and other commands which draw primitives.",
"PATCHES"..0xE
)
IntConstant(
"Accepted by the {@code pname} parameter of PatchParameteri, GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.",
"PATCH_VERTICES"..0x8E72
)
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"TESS_CONTROL_OUTPUT_VERTICES"..0x8E75,
"TESS_GEN_MODE"..0x8E76,
"TESS_GEN_SPACING"..0x8E77,
"TESS_GEN_VERTEX_ORDER"..0x8E78,
"TESS_GEN_POINT_MODE"..0x8E79
)
IntConstant(
"Returned by GetProgramiv when {@code pname} is TESS_GEN_MODE.",
"ISOLINES"..0x8E7A,
"QUADS"..0x0007
)
IntConstant(
"Returned by GetProgramiv when {@code pname} is TESS_GEN_SPACING.",
"FRACTIONAL_ODD"..0x8E7B,
"FRACTIONAL_EVEN"..0x8E7C
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.",
"MAX_PATCH_VERTICES"..0x8E7D,
"MAX_TESS_GEN_LEVEL"..0x8E7E,
"MAX_TESS_CONTROL_UNIFORM_COMPONENTS"..0x8E7F,
"MAX_TESS_EVALUATION_UNIFORM_COMPONENTS"..0x8E80,
"MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS"..0x8E81,
"MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS"..0x8E82,
"MAX_TESS_CONTROL_OUTPUT_COMPONENTS"..0x8E83,
"MAX_TESS_PATCH_COMPONENTS"..0x8E84,
"MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS"..0x8E85,
"MAX_TESS_EVALUATION_OUTPUT_COMPONENTS"..0x8E86,
"MAX_TESS_CONTROL_UNIFORM_BLOCKS"..0x8E89,
"MAX_TESS_EVALUATION_UNIFORM_BLOCKS"..0x8E8A,
"MAX_TESS_CONTROL_INPUT_COMPONENTS"..0x886C,
"MAX_TESS_EVALUATION_INPUT_COMPONENTS"..0x886D,
"MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS"..0x8E1E,
"MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS"..0x8E1F,
"MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS"..0x92CD,
"MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS"..0x92CE,
"MAX_TESS_CONTROL_ATOMIC_COUNTERS"..0x92D3,
"MAX_TESS_EVALUATION_ATOMIC_COUNTERS"..0x92D4,
"MAX_TESS_CONTROL_IMAGE_UNIFORMS"..0x90CB,
"MAX_TESS_EVALUATION_IMAGE_UNIFORMS"..0x90CC,
"MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS"..0x90D8,
"MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS"..0x90D9,
"PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED"..0x8221
)
IntConstant(
"Accepted by the {@code props} parameter of GetProgramResourceiv.",
"IS_PER_PATCH"..0x92E7,
"REFERENCED_BY_TESS_CONTROL_SHADER"..0x9307,
"REFERENCED_BY_TESS_EVALUATION_SHADER"..0x9308
)
IntConstant(
"""
Accepted by the {@code type} parameter of CreateShader, by the {@code pname} parameter of GetProgramPipelineiv, and returned by the {@code params}
parameter of GetShaderiv.
""",
"TESS_EVALUATION_SHADER"..0x8E87,
"TESS_CONTROL_SHADER"..0x8E88
)
IntConstant(
"Accepted by the {@code stages} parameter of UseProgramStages.",
"TESS_CONTROL_SHADER_BIT"..0x00000008,
"TESS_EVALUATION_SHADER_BIT"..0x00000010
)
void(
"PatchParameteri",
"",
GLenum.IN("pname", ""),
GLint.IN("value", "")
)
// OES_texture_border_clamp
IntConstant(
"""
Accepted by the {@code pname} parameter of TexParameteriv, TexParameterfv, SamplerParameteriv, SamplerParameterfv, TexParameterIiv,
TexParameterIuiv, SamplerParameterIiv, SamplerParameterIuiv, GetTexParameteriv, GetTexParameterfv, GetTexParameterIiv,
GetTexParameterIuiv, GetSamplerParameteriv, GetSamplerParameterfv, GetSamplerParameterIiv, and GetSamplerParameterIuiv.
""",
"TEXTURE_BORDER_COLOR"..0x1004
)
IntConstant(
"""
Accepted by the {@code param} parameter of TexParameteri, TexParameterf, SamplerParameteri and SamplerParameterf, and by the {@code params} parameter of
TexParameteriv, TexParameterfv, TexParameterIiv, TexParameterIuiv, SamplerParameterIiv, SamplerParameterIuiv and returned by the
{@code params} parameter of GetTexParameteriv, GetTexParameterfv, GetTexParameterIiv, GetTexParameterIuiv, GetSamplerParameteriv,
GetSamplerParameterfv, GetSamplerParameterIiv, and GetSamplerParameterIuiv when their {@code pname} parameter is TEXTURE_WRAP_S, TEXTURE_WRAP_T,
or TEXTURE_WRAP_R.
""",
"CLAMP_TO_BORDER"..0x812D
)
void(
"TexParameterIiv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
SingleValue("param")..const..GLint_p.IN("params", "")
)
void(
"TexParameterIuiv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
SingleValue("param")..const..GLuint_p.IN("params", "")
)
void(
"GetTexParameterIiv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
void(
"GetTexParameterIuiv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLuint_p.OUT("params", "")
)
void(
"SamplerParameterIiv",
"",
GLuint.IN("sampler", ""),
GLenum.IN("pname", ""),
SingleValue("param")..const..GLint_p.IN("params", "")
)
void(
"SamplerParameterIuiv",
"",
GLuint.IN("sampler", ""),
GLenum.IN("pname", ""),
SingleValue("param")..const..GLuint_p.IN("params", "")
)
void(
"GetSamplerParameterIiv",
"",
GLuint.IN("sampler", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
void(
"GetSamplerParameterIuiv",
"",
GLuint.IN("sampler", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLuint_p.OUT("params", "")
)
// OES_texture_buffer
IntConstant(
"""
Accepted by the {@code target} parameter of BindBuffer, BufferData, BufferSubData, MapBufferRange, BindTexture, UnmapBuffer, GetBufferParameteriv,
GetBufferPointerv, TexBuffer, and TexBufferRange.
""",
"TEXTURE_BUFFER"..0x8C2A
)
IntConstant(
"Accepted by the {@code pname} parameters of GetBooleanv, GetFloatv, and GetIntegerv.",
"TEXTURE_BUFFER_BINDING"..0x8C2A
)
IntConstant(
"""
(note that this token name is an alias for TEXTURE_BUFFER, and is used for naming consistency with queries for the buffers bound to other buffer
binding points). MAX_TEXTURE_BUFFER_SIZE 0x8C2B TEXTURE_BINDING_BUFFER 0x8C2C TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F Returned in the
{@code type} parameter of GetActiveUniform, the {@code params} parameter of GetActiveUniformsiv, and the {@code params} parameter of
GetProgramResourceiv when the TYPE property is queried on the UNIFORM interface.
""",
"SAMPLER_BUFFER"..0x8DC2,
"INT_SAMPLER_BUFFER"..0x8DD0,
"UNSIGNED_INT_SAMPLER_BUFFER"..0x8DD8,
"IMAGE_BUFFER"..0x9051,
"INT_IMAGE_BUFFER"..0x905C,
"UNSIGNED_INT_IMAGE_BUFFER"..0x9067
)
IntConstant(
"Accepted by the {@code pname} parameter of GetTexLevelParameter.",
"TEXTURE_BUFFER_DATA_STORE_BINDING"..0x8C2D,
"TEXTURE_BUFFER_OFFSET"..0x919D,
"TEXTURE_BUFFER_SIZE"..0x919E
)
void(
"TexBuffer",
"",
GLenum.IN("target", ""),
GLenum.IN("internalformat", ""),
GLuint.IN("buffer", "")
)
void(
"TexBufferRange",
"",
GLenum.IN("target", ""),
GLenum.IN("internalformat", ""),
GLuint.IN("buffer", ""),
GLintptr.IN("offset", ""),
GLsizeiptr.IN("size", "")
)
// KHR_texture_compression_astc_ldr
IntConstant(
"""
Accepted by the {@code internalformat} parameter of CompressedTexImage2D, CompressedTexSubImage2D, TexStorage2D, TextureStorage2D, TexStorage3D, and
TextureStorage3D.
""",
"COMPRESSED_RGBA_ASTC_4x4"..0x93B0,
"COMPRESSED_RGBA_ASTC_5x4"..0x93B1,
"COMPRESSED_RGBA_ASTC_5x5"..0x93B2,
"COMPRESSED_RGBA_ASTC_6x5"..0x93B3,
"COMPRESSED_RGBA_ASTC_6x6"..0x93B4,
"COMPRESSED_RGBA_ASTC_8x5"..0x93B5,
"COMPRESSED_RGBA_ASTC_8x6"..0x93B6,
"COMPRESSED_RGBA_ASTC_8x8"..0x93B7,
"COMPRESSED_RGBA_ASTC_10x5"..0x93B8,
"COMPRESSED_RGBA_ASTC_10x6"..0x93B9,
"COMPRESSED_RGBA_ASTC_10x8"..0x93BA,
"COMPRESSED_RGBA_ASTC_10x10"..0x93BB,
"COMPRESSED_RGBA_ASTC_12x10"..0x93BC,
"COMPRESSED_RGBA_ASTC_12x12"..0x93BD,
"COMPRESSED_SRGB8_ALPHA8_ASTC_4x4"..0x93D0,
"COMPRESSED_SRGB8_ALPHA8_ASTC_5x4"..0x93D1,
"COMPRESSED_SRGB8_ALPHA8_ASTC_5x5"..0x93D2,
"COMPRESSED_SRGB8_ALPHA8_ASTC_6x5"..0x93D3,
"COMPRESSED_SRGB8_ALPHA8_ASTC_6x6"..0x93D4,
"COMPRESSED_SRGB8_ALPHA8_ASTC_8x5"..0x93D5,
"COMPRESSED_SRGB8_ALPHA8_ASTC_8x6"..0x93D6,
"COMPRESSED_SRGB8_ALPHA8_ASTC_8x8"..0x93D7,
"COMPRESSED_SRGB8_ALPHA8_ASTC_10x5"..0x93D8,
"COMPRESSED_SRGB8_ALPHA8_ASTC_10x6"..0x93D9,
"COMPRESSED_SRGB8_ALPHA8_ASTC_10x8"..0x93DA,
"COMPRESSED_SRGB8_ALPHA8_ASTC_10x10"..0x93DB,
"COMPRESSED_SRGB8_ALPHA8_ASTC_12x10"..0x93DC,
"COMPRESSED_SRGB8_ALPHA8_ASTC_12x12"..0x93DD
)
// OES_texture_cube_map_array
IntConstant(
"""
Accepted by the {@code target} parameter of TexParameter{if}, TexParameter{if}v, TexParameterI{i ui}v, BindTexture, GenerateMipmap, TexImage3D,
TexSubImage3D, TexStorage3D, GetTexParameter{if}v, GetTexParameter{i ui}v, GetTexLevelParameter{if}v, CompressedTexImage3D, CompressedTexSubImage3D
and CopyTexSubImage3D.
""",
"TEXTURE_CUBE_MAP_ARRAY"..0x9009
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv and GetFloatv.",
"TEXTURE_BINDING_CUBE_MAP_ARRAY"..0x900A
)
IntConstant(
"Returned by the {@code type} parameter of GetActiveUniform, and by the {@code params} parameter of GetProgramResourceiv when {@code props} is TYPE.",
"SAMPLER_CUBE_MAP_ARRAY"..0x900C,
"SAMPLER_CUBE_MAP_ARRAY_SHADOW"..0x900D,
"INT_SAMPLER_CUBE_MAP_ARRAY"..0x900E,
"UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY"..0x900F,
"IMAGE_CUBE_MAP_ARRAY"..0x9054,
"INT_IMAGE_CUBE_MAP_ARRAY"..0x905F,
"UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY"..0x906A
)
// OES_texture_storage_multisample_2d_array
IntConstant(
"""
Accepted by the {@code target} parameter of BindTexture, TexStorage3DMultisample, GetInternalformativ, TexParameter{if}*, GetTexParameter{if}v and
GetTexLevelParameter{if}v. Also, the texture object indicated by the {@code texture} argument to FramebufferTextureLayer can be
TEXTURE_2D_MULTISAMPLE_ARRAY.
""",
"TEXTURE_2D_MULTISAMPLE_ARRAY"..0x9102
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, and GetFloatv.",
"TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY"..0x9105
)
IntConstant(
"Returned by the {@code type} parameter of GetActiveUniform.",
"SAMPLER_2D_MULTISAMPLE_ARRAY"..0x910B,
"INT_SAMPLER_2D_MULTISAMPLE_ARRAY"..0x910C,
"UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY"..0x910D
)
void(
"TexStorage3DMultisample",
"",
GLenum.IN("target", ""),
GLsizei.IN("samples", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLboolean.IN("fixedsamplelocations", "")
)
} | bsd-3-clause |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/listeners/DamageTakenListener.kt | 1 | 3959 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.listeners
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.querydsl.QDamageTaken
import org.bukkit.ChatColor
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityDamageEvent
class DamageTakenListener(private val plugin: StatCraft) : Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onDamageTaken(event: EntityDamageEvent) {
if (event.entity is Player && event.cause != EntityDamageEvent.DamageCause.ENTITY_ATTACK
&& event.cause != EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) {
val uuid = event.entity.uniqueId
val worldName = event.entity.world.name
val damageTaken = Math.round(event.finalDamage).toInt()
plugin.threadManager.schedule<QDamageTaken>(
uuid, worldName,
{ t, clause, id, worldId ->
clause.columns(t.id, t.worldId, t.entity, t.amount)
.values(id, worldId, event.cause.name, damageTaken).execute()
}, { t, clause, id, worldId ->
clause.where(t.id.eq(id), t.worldId.eq(worldId), t.entity.eq(event.cause.name))
.set(t.amount, t.amount.add(damageTaken)).execute()
}
)
// DROWN ANNOUNCE
if (plugin.config.stats.drowningAnnounce)
if (event.cause == EntityDamageEvent.DamageCause.DROWNING) {
if (System.currentTimeMillis() / 1000 - plugin.getLastDrownTime(uuid) > 120) {
event.entity.server.broadcastMessage(
ChatColor.BLUE.toString() +
plugin.config.stats.drownAnnounceMessage.replace(
"~".toRegex(),
(event.entity as Player).displayName + ChatColor.BLUE
)
)
plugin.setLastDrowningTime(uuid, (System.currentTimeMillis() / 1000).toInt())
}
}
// POISON ANNOUNCE
if (plugin.config.stats.poisonAnnounce)
if (event.cause == EntityDamageEvent.DamageCause.POISON) {
if (System.currentTimeMillis() / 1000 - plugin.getLastPoisonTime(uuid) > 120) {
event.entity.server.broadcastMessage(
ChatColor.GREEN.toString() +
plugin.config.stats.poisonAnnounceMessage.replace(
"~".toRegex(),
(event.entity as Player).displayName + ChatColor.GREEN
)
)
plugin.setLastPoisonTime(uuid, (System.currentTimeMillis() / 1000).toInt())
}
}
// WITHER ANNOUNCE
if (plugin.config.stats.witherAnnounce)
if (event.cause == EntityDamageEvent.DamageCause.WITHER) {
if (System.currentTimeMillis() / 1000 - plugin.getLastWitherTime(uuid) > 120) {
event.entity.server.broadcastMessage(
ChatColor.DARK_GRAY.toString() +
plugin.config.stats.witherAnnounceMessage.replace(
"~".toRegex(),
(event.entity as Player).displayName + ChatColor.DARK_GRAY
)
)
plugin.setLastWitherTime(uuid, (System.currentTimeMillis() / 1000).toInt())
}
}
}
}
}
| mit |
noemus/kotlin-eclipse | kotlin-eclipse-ui-test/testData/completion/basic/common/InParametersTypes.kt | 1 | 273 | class SomeClass {
class SomeInternal
fun some(a : S<caret>)
}
// INVOCATION_COUNT: 1
// EXIST: SomeClass
// EXIST: SomeInternal
// EXIST: { lookupString:"String", tailText:" (jet)" }
// EXIST: StringBuilder
// EXIST_JAVA_ONLY: StringBuffer
// ABSENT: HTMLStyleElement | apache-2.0 |
minecraft-dev/MinecraftDev | src/main/kotlin/insight/ColorLineMarkerProvider.kt | 1 | 5998 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight
import com.demonwav.mcdev.MinecraftSettings
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo
import com.intellij.codeInsight.daemon.NavigateAction
import com.intellij.codeInsight.hint.HintManager
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.psi.JVMElementFactories
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiEditorUtil
import com.intellij.ui.ColorChooser
import com.intellij.util.FunctionUtil
import com.intellij.util.ui.ColorIcon
import com.intellij.util.ui.ColorsIcon
import java.awt.Color
import javax.swing.Icon
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.ULiteralExpression
import org.jetbrains.uast.toUElementOfType
class ColorLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? {
if (!MinecraftSettings.instance.isShowChatColorGutterIcons) {
return null
}
val identifier = element.toUElementOfType<UIdentifier>() ?: return null
val info = identifier.findColor { map, chosen -> ColorInfo(element, chosen.value, map, chosen.key, identifier) }
if (info != null) {
NavigateAction.setNavigateAction(info, "Change Color", null)
}
return info
}
open class ColorInfo : MergeableLineMarkerInfo<PsiElement> {
protected val color: Color
constructor(
element: PsiElement,
color: Color,
map: Map<String, Color>,
colorName: String,
workElement: UElement
) : super(
element,
element.textRange,
ColorIcon(12, color),
FunctionUtil.nullConstant<Any, String>(),
GutterIconNavigationHandler handler@{ _, psiElement ->
if (psiElement == null || !psiElement.isWritable || !psiElement.isValid || !workElement.isPsiValid) {
return@handler
}
val editor = PsiEditorUtil.findEditor(psiElement) ?: return@handler
val picker = ColorPicker(map, editor.component)
val newColor = picker.showDialog()
if (newColor != null && map[newColor] != color) {
workElement.setColor(newColor)
}
},
GutterIconRenderer.Alignment.RIGHT,
{ "$colorName color indicator" }
) {
this.color = color
}
constructor(element: PsiElement, color: Color, handler: GutterIconNavigationHandler<PsiElement>) : super(
element,
element.textRange,
ColorIcon(12, color),
FunctionUtil.nullConstant<Any, String>(),
handler,
GutterIconRenderer.Alignment.RIGHT,
{ "color indicator" }
) {
this.color = color
}
override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is ColorInfo
override fun getCommonIconAlignment(infos: List<MergeableLineMarkerInfo<*>>) =
GutterIconRenderer.Alignment.RIGHT
override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<*>>): Icon {
if (infos.size == 2 && infos[0] is ColorInfo && infos[1] is ColorInfo) {
return ColorsIcon(12, (infos[0] as ColorInfo).color, (infos[1] as ColorInfo).color)
}
return AllIcons.Gutter.Colors
}
override fun getCommonTooltip(infos: List<MergeableLineMarkerInfo<*>>) =
FunctionUtil.nullConstant<PsiElement, String>()
}
class CommonColorInfo(
element: PsiElement,
color: Color,
workElement: UElement
) : ColorLineMarkerProvider.ColorInfo(
element,
color,
GutterIconNavigationHandler handler@{ _, psiElement ->
if (psiElement == null || !psiElement.isValid ||
!workElement.isPsiValid || workElement.sourcePsi?.isWritable != true
) {
return@handler
}
val editor = PsiEditorUtil.findEditor(psiElement) ?: return@handler
if (JVMElementFactories.getFactory(psiElement.language, psiElement.project) == null) {
// The setColor methods used here require a JVMElementFactory. Unfortunately the Kotlin plugin does not
// implement it yet. It is better to not display the color chooser at all than deceiving users after
// after they chose a color
HintManager.getInstance()
.showErrorHint(editor, "Can't change colors in " + psiElement.language.displayName)
return@handler
}
val c = ColorChooser.chooseColor(psiElement.project, editor.component, "Choose Color", color, false)
?: return@handler
when (workElement) {
is ULiteralExpression -> workElement.setColor(c.rgb and 0xFFFFFF)
is UCallExpression -> workElement.setColor(c.red, c.green, c.blue)
}
}
)
abstract class CommonLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? {
val pair = findColor(element) ?: return null
val info = CommonColorInfo(element, pair.first, pair.second)
NavigateAction.setNavigateAction(info, "Change color", null)
return info
}
abstract fun findColor(element: PsiElement): Pair<Color, UElement>?
}
}
| mit |
CruGlobal/android-gto-support | gto-support-db/src/main/java/org/ccci/gto/android/common/db/TableType.kt | 2 | 189 | package org.ccci.gto.android.common.db
internal class TableType(
val table: String,
val projection: Array<String>?,
val mapper: Mapper<*>?,
val primaryWhere: Expression?
)
| mit |
world-federation-of-advertisers/panel-exchange-client | src/main/kotlin/org/wfanet/panelmatch/client/eventpreprocessing/HkdfPepperProvider.kt | 1 | 857 | // Copyright 2021 The Cross-Media Measurement Authors
//
// 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 org.wfanet.panelmatch.client.eventpreprocessing
import com.google.protobuf.ByteString
import java.io.Serializable
/** Type-safe provider for the HKDF pepper. */
interface HkdfPepperProvider : Serializable {
fun get(): ByteString
}
| apache-2.0 |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/ext/LuaFileAdditionalResolver.kt | 2 | 1471 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* 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.tang.intellij.lua.ext
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.tang.intellij.lua.project.LuaSettings
class LuaFileAdditionalResolver : ILuaFileResolver {
override fun find(project: Project, shortUrl: String, extNames: Array<String>): VirtualFile? {
val sourcesRoot = LuaSettings.instance.additionalSourcesRoot
for (sr in sourcesRoot) {
for (ext in extNames) {
val path = "$sr/$shortUrl$ext"
val file = VirtualFileManager.getInstance().findFileByUrl(VfsUtil.pathToUrl(path))
if (file != null && !file.isDirectory) {
return file
}
}
}
return null
}
} | apache-2.0 |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/extensions/FlowExtensions.kt | 1 | 683 | package at.ac.tuwien.caa.docscan.extensions
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.SendChannel
/**
* A safe call for [SendChannel.offer] which is only called if [SendChannel.isClosedForSend] == false
* and surrounded with a try/catch in case a [CancellationException] is thrown.
*
* @return true if the value has been successfully added to the [SendChannel]'s queue else false
*/
@ExperimentalCoroutinesApi
fun <E> SendChannel<E>.safeOffer(value: E) = !isClosedForSend && try {
val result = trySend(value)
result.isSuccess
} catch (e: CancellationException) {
false
}
| lgpl-3.0 |
wordpress-mobile/AztecEditor-Android | wordpress-comments/src/main/java/org/wordpress/aztec/plugins/wpcomments/spans/GutenbergCommentSpan.kt | 1 | 725 | package org.wordpress.aztec.plugins.wpcomments.spans
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.ITextFormat
import org.wordpress.aztec.spans.IAztecBlockSpan
class GutenbergCommentSpan(
override val startTag: String,
override var nestingLevel: Int,
override var attributes: AztecAttributes = AztecAttributes()
) : IAztecBlockSpan {
override val TAG: String = "wp:"
override var startBeforeCollapse: Int = -1
override var endBeforeBleed: Int = -1
private var _endTag: String = super.endTag
override var endTag: String
get() = _endTag
set(value) {
_endTag = value
}
override val textFormat: ITextFormat? = null
}
| mpl-2.0 |
arkon/LISTEN.moe-Unofficial-Android-App | app/src/main/java/me/echeung/moemoekyun/ui/activity/SettingsActivity.kt | 1 | 2847 | package me.echeung.moemoekyun.ui.activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.app.TaskStackBuilder
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager
import me.echeung.moemoekyun.R
import me.echeung.moemoekyun.ui.base.BaseActivity
import me.echeung.moemoekyun.util.PreferenceUtil
class SettingsActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
initAppbar()
supportFragmentManager.beginTransaction()
.replace(R.id.content_frame, SettingsFragment())
.commit()
}
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.pref_general)
addPreferencesFromResource(R.xml.pref_music)
addPreferencesFromResource(R.xml.pref_audio)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
invalidateSettings()
}
private fun invalidateSettings() {
val languageSetting = findPreference<ListPreference>(PreferenceUtil.PREF_GENERAL_LANGUAGE)!!
setSummary(languageSetting)
languageSetting.setOnPreferenceChangeListener { _, o ->
setSummary(languageSetting, o)
recreateBackStack()
true
}
}
private fun setSummary(preference: Preference, value: Any = getPreferenceValue(preference)) {
val stringValue = value.toString()
if (preference is ListPreference) {
val index = preference.findIndexOfValue(stringValue)
preference.setSummary(
if (index >= 0) {
preference.entries[index]
} else {
null
}
)
} else {
preference.summary = stringValue
}
}
private fun getPreferenceValue(preference: Preference): String {
return PreferenceManager
.getDefaultSharedPreferences(preference.context)
.getString(preference.key, "")!!
}
private fun recreateBackStack() {
val activity = requireActivity()
TaskStackBuilder.create(activity)
.addNextIntent(Intent(activity, MainActivity::class.java))
.addNextIntent(activity.intent)
.startActivities()
}
}
}
| mit |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/procdebuggers/utils/DefaultRespondent.kt | 1 | 3041 | package org.jetbrains.haskell.debugger.procdebuggers.utils
import org.jetbrains.haskell.debugger.HaskellDebugProcess
import org.jetbrains.haskell.debugger.frames.HsSuspendContext
import org.jetbrains.haskell.debugger.utils.HaskellUtils
import com.intellij.openapi.vfs.LocalFileSystem
import org.jetbrains.haskell.debugger.frames.HsHistoryFrame
import org.jetbrains.haskell.debugger.parser.HistoryResult
import org.jetbrains.haskell.debugger.parser.HsHistoryFrameInfo
import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointDescription
public class DefaultRespondent(val debugProcess: HaskellDebugProcess) : DebugRespondent {
private val session = debugProcess.getSession()!!
override fun traceFinished() = debugProcess.traceFinished()
override fun positionReached(context: HsSuspendContext) = session.positionReached(context)
override fun breakpointReached(breakpoint: HaskellLineBreakpointDescription,
context: HsSuspendContext) {
val realBreakpoint = debugProcess.getBreakpointAtPosition(breakpoint.module, breakpoint.line)
if (realBreakpoint == null) {
session.positionReached(context)
} else {
session.breakpointReached(realBreakpoint, realBreakpoint.getLogExpression(), context)
}
}
override fun exceptionReached(context: HsSuspendContext) {
val breakpoint = debugProcess.exceptionBreakpoint
if (breakpoint == null) {
session.positionReached(context)
} else {
session.breakpointReached(breakpoint, breakpoint.getLogExpression(), context)
}
}
override fun breakpointRemoved() { }
override fun getBreakpointAt(module: String, line: Int): HaskellLineBreakpointDescription? {
val breakpoint = debugProcess.getBreakpointAtPosition(module, line)
if (breakpoint == null) {
return null
} else {
return HaskellLineBreakpointDescription(module, line, breakpoint.getCondition())
}
}
override fun setBreakpointNumberAt(breakpointNumber: Int, module: String, line: Int) =
debugProcess.setBreakpointNumberAtLine(breakpointNumber, module, line)
override fun resetHistoryStack() {}//= debugProcess.historyManager.resetHistoryStack()
override fun historyChange(currentFrame: HsHistoryFrame, history: HistoryResult?) {
//debugProcess.historyManager.historyFrameAppeared(currentFrame)
//if (history != null) {
// debugProcess.historyManager.setHistoryFramesInfo(
// HsHistoryFrameInfo(0, currentFrame.stackFrameInfo.functionName,
// currentFrame.stackFrameInfo.filePosition), history.frames, history.full)
//}
//debugProcess.historyManager.historyChanged(false, true, currentFrame)
}
override fun getModuleByFile(filename: String): String =
HaskellUtils.getModuleName(session.getProject(), LocalFileSystem.getInstance()!!.findFileByPath(filename)!!)
} | apache-2.0 |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/domain/entity/ContentType.kt | 1 | 481 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.domain.entity
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
enum class ContentType(
val isPlayable: Boolean,
val hasDuration: Boolean
) {
MOVIE(true, true),
MUSIC(true, true),
PHOTO(true, false),
CONTAINER(false, false),
UNKNOWN(false, false),
}
| mit |
pbauerochse/youtrack-worklog-viewer | application/src/main/java/de/pbauerochse/worklogviewer/settings/SettingsViewModel.kt | 1 | 12381 | package de.pbauerochse.worklogviewer.settings
import de.pbauerochse.worklogviewer.datasource.DataSources
import de.pbauerochse.worklogviewer.fx.ConnectorDescriptor
import de.pbauerochse.worklogviewer.fx.Theme
import de.pbauerochse.worklogviewer.timerange.TimerangeProvider
import de.pbauerochse.worklogviewer.toURL
import javafx.beans.binding.BooleanBinding
import javafx.beans.property.*
import javafx.beans.value.ChangeListener
import javafx.scene.input.KeyCombination
import java.time.DayOfWeek.*
import java.time.LocalDate
/**
* Java FX Model for the settings screen
*/
class SettingsViewModel internal constructor(val settings: Settings) {
val youTrackUrlProperty = SimpleStringProperty()
val youTrackConnectorProperty = SimpleObjectProperty<ConnectorDescriptor>()
val youTrackUsernameProperty = SimpleStringProperty()
val youTrackPermanentTokenProperty = SimpleStringProperty()
val themeProperty = SimpleObjectProperty<Theme>()
val workhoursProperty = SimpleFloatProperty()
val showAllWorklogsProperty = SimpleBooleanProperty()
val showStatisticsProperty = SimpleBooleanProperty()
val statisticsPaneDividerPosition = SimpleDoubleProperty()
val loadDataAtStartupProperty = SimpleBooleanProperty()
val showDecimalsInExcelProperty = SimpleBooleanProperty()
val enablePluginsProperty = SimpleBooleanProperty()
val lastUsedReportTimerangeProperty = SimpleObjectProperty<TimerangeProvider>()
val startDateProperty = SimpleObjectProperty<LocalDate>()
val endDateProperty = SimpleObjectProperty<LocalDate>()
val lastUsedGroupByCategoryIdProperty = SimpleStringProperty()
val lastUsedFilePath = SimpleStringProperty()
val collapseStateMondayProperty = SimpleBooleanProperty()
val collapseStateTuesdayProperty = SimpleBooleanProperty()
val collapseStateWednesdayProperty = SimpleBooleanProperty()
val collapseStateThursdayProperty = SimpleBooleanProperty()
val collapseStateFridayProperty = SimpleBooleanProperty()
val collapseStateSaturdayProperty = SimpleBooleanProperty()
val collapseStateSundayProperty = SimpleBooleanProperty()
val highlightStateMondayProperty = SimpleBooleanProperty()
val highlightStateTuesdayProperty = SimpleBooleanProperty()
val highlightStateWednesdayProperty = SimpleBooleanProperty()
val highlightStateThursdayProperty = SimpleBooleanProperty()
val highlightStateFridayProperty = SimpleBooleanProperty()
val highlightStateSaturdayProperty = SimpleBooleanProperty()
val highlightStateSundayProperty = SimpleBooleanProperty()
// search result
val showTagsInSearchResults = SimpleBooleanProperty()
val showFieldsInSearchResults = SimpleBooleanProperty()
val showDescriptionInSearchResults = SimpleBooleanProperty()
val hasMissingConnectionSettings = hasMissingConnectionSettingsBinding
// shortcuts
val fetchWorklogsKeyboardCombination = SimpleObjectProperty<KeyCombination>()
val showIssueSearchKeyboardCombination = SimpleObjectProperty<KeyCombination>()
val toggleStatisticsKeyboardCombination = SimpleObjectProperty<KeyCombination>()
val showSettingsKeyboardCombination = SimpleObjectProperty<KeyCombination>()
val exitWorklogViewerKeyboardCombination = SimpleObjectProperty<KeyCombination>()
// overtime statistics
var overtimeStatisticsIgnoreWeekendsProperty = SimpleBooleanProperty()
var overtimeStatisticsIgnoreWithoutTimeEntriesProperty = SimpleBooleanProperty()
var overtimeStatisticsIgnoreTodayProperty = SimpleBooleanProperty()
init {
applyPropertiesFromSettings()
bindAutoUpdatingProperties()
}
fun saveChanges() {
settings.youTrackConnectionSettings.baseUrl = youTrackUrlProperty.get().toURL()
settings.youTrackConnectionSettings.selectedConnectorId = youTrackConnectorProperty.get().id
settings.youTrackConnectionSettings.username = youTrackUsernameProperty.get()
settings.youTrackConnectionSettings.permanentToken = youTrackPermanentTokenProperty.get()
settings.theme = themeProperty.get()
settings.workHoursADay = workhoursProperty.get()
settings.isShowAllWorklogs = showAllWorklogsProperty.get()
settings.isShowStatistics = showStatisticsProperty.get()
settings.isLoadDataAtStartup = loadDataAtStartupProperty.get()
settings.isShowDecimalHourTimesInExcelReport = showDecimalsInExcelProperty.get()
settings.isEnablePlugins = enablePluginsProperty.get()
settings.lastUsedReportTimerange = lastUsedReportTimerangeProperty.get()
settings.startDate = startDateProperty.get()
settings.endDate = endDateProperty.get()
settings.lastUsedGroupByCategoryId = lastUsedGroupByCategoryIdProperty.get()
settings.collapseState.set(MONDAY, collapseStateMondayProperty.get())
settings.collapseState.set(TUESDAY, collapseStateTuesdayProperty.get())
settings.collapseState.set(WEDNESDAY, collapseStateWednesdayProperty.get())
settings.collapseState.set(THURSDAY, collapseStateThursdayProperty.get())
settings.collapseState.set(FRIDAY, collapseStateFridayProperty.get())
settings.collapseState.set(SATURDAY, collapseStateSaturdayProperty.get())
settings.collapseState.set(SUNDAY, collapseStateSundayProperty.get())
settings.highlightState.set(MONDAY, highlightStateMondayProperty.get())
settings.highlightState.set(TUESDAY, highlightStateTuesdayProperty.get())
settings.highlightState.set(WEDNESDAY, highlightStateWednesdayProperty.get())
settings.highlightState.set(THURSDAY, highlightStateThursdayProperty.get())
settings.highlightState.set(FRIDAY, highlightStateFridayProperty.get())
settings.highlightState.set(SATURDAY, highlightStateSaturdayProperty.get())
settings.highlightState.set(SUNDAY, highlightStateSundayProperty.get())
settings.isShowTagsInSearchResults = showTagsInSearchResults.get()
settings.isShowFieldsInSearchResults = showFieldsInSearchResults.get()
settings.isShowDescriptionInSearchResults = showDescriptionInSearchResults.get()
settings.shortcuts.fetchWorklogs = fetchWorklogsKeyboardCombination.get()?.name
settings.shortcuts.showIssueSearch = showIssueSearchKeyboardCombination.get()?.name
settings.shortcuts.toggleStatistics = toggleStatisticsKeyboardCombination.get()?.name
settings.shortcuts.showSettings = showSettingsKeyboardCombination.get()?.name
settings.shortcuts.exitWorklogViewer = exitWorklogViewerKeyboardCombination.get()?.name
SettingsUtil.saveSettings()
}
fun discardChanges() {
applyPropertiesFromSettings()
}
private fun applyPropertiesFromSettings() {
youTrackUrlProperty.set(settings.youTrackConnectionSettings.baseUrl?.toExternalForm())
youTrackConnectorProperty.set(DataSources.dataSourceFactories.find { it.id == settings.youTrackConnectionSettings.selectedConnectorId }?.let { ConnectorDescriptor(it.id, it.name) })
youTrackUsernameProperty.set(settings.youTrackConnectionSettings.username)
youTrackPermanentTokenProperty.set(settings.youTrackConnectionSettings.permanentToken)
themeProperty.set(settings.theme)
workhoursProperty.set(settings.workHoursADay)
showAllWorklogsProperty.set(settings.isShowAllWorklogs)
showStatisticsProperty.set(settings.isShowStatistics)
loadDataAtStartupProperty.set(settings.isLoadDataAtStartup)
showDecimalsInExcelProperty.set(settings.isShowDecimalHourTimesInExcelReport)
enablePluginsProperty.set(settings.isEnablePlugins)
lastUsedReportTimerangeProperty.set(settings.lastUsedReportTimerange)
lastUsedFilePath.set(settings.lastUsedFilePath)
startDateProperty.set(settings.startDate)
endDateProperty.set(settings.endDate)
lastUsedGroupByCategoryIdProperty.set(settings.lastUsedGroupByCategoryId)
collapseStateMondayProperty.set(settings.collapseState.isSet(MONDAY))
collapseStateTuesdayProperty.set(settings.collapseState.isSet(TUESDAY))
collapseStateWednesdayProperty.set(settings.collapseState.isSet(WEDNESDAY))
collapseStateThursdayProperty.set(settings.collapseState.isSet(THURSDAY))
collapseStateFridayProperty.set(settings.collapseState.isSet(FRIDAY))
collapseStateSaturdayProperty.set(settings.collapseState.isSet(SATURDAY))
collapseStateSundayProperty.set(settings.collapseState.isSet(SUNDAY))
highlightStateMondayProperty.set(settings.highlightState.isSet(MONDAY))
highlightStateTuesdayProperty.set(settings.highlightState.isSet(TUESDAY))
highlightStateWednesdayProperty.set(settings.highlightState.isSet(WEDNESDAY))
highlightStateThursdayProperty.set(settings.highlightState.isSet(THURSDAY))
highlightStateFridayProperty.set(settings.highlightState.isSet(FRIDAY))
highlightStateSaturdayProperty.set(settings.highlightState.isSet(SATURDAY))
highlightStateSundayProperty.set(settings.highlightState.isSet(SUNDAY))
showTagsInSearchResults.set(settings.isShowTagsInSearchResults)
showFieldsInSearchResults.set(settings.isShowFieldsInSearchResults)
showDescriptionInSearchResults.set(settings.isShowDescriptionInSearchResults)
settings.shortcuts.fetchWorklogs?.let { fetchWorklogsKeyboardCombination.set(KeyCombination.valueOf(it)) }
settings.shortcuts.showIssueSearch?.let { showIssueSearchKeyboardCombination.set(KeyCombination.valueOf(it)) }
settings.shortcuts.toggleStatistics?.let { toggleStatisticsKeyboardCombination.set(KeyCombination.valueOf(it)) }
settings.shortcuts.showSettings?.let { showSettingsKeyboardCombination.set(KeyCombination.valueOf(it)) }
settings.shortcuts.exitWorklogViewer?.let { exitWorklogViewerKeyboardCombination.set(KeyCombination.valueOf(it)) }
overtimeStatisticsIgnoreWeekendsProperty.set(settings.isOvertimeStatisticsIgnoreWeekends)
overtimeStatisticsIgnoreWithoutTimeEntriesProperty.set(settings.isOvertimeStatisticsIgnoreWithoutTimeEntries)
overtimeStatisticsIgnoreTodayProperty.set(settings.isOvertimeStatisticsIgnoreToday)
statisticsPaneDividerPosition.set(settings.statisticsPaneDividerPosition)
}
private val hasMissingConnectionSettingsBinding: BooleanBinding
get() = youTrackUrlProperty.isEmpty
.or(youTrackConnectorProperty.isNull)
.or(youTrackUsernameProperty.isEmpty)
.or(youTrackPermanentTokenProperty.isEmpty)
/**
* These settings are applied to the persistent settings
* object whenever they are changed. In general, those are
* the application state properties, that are not set
* in the settings view.
*/
private fun bindAutoUpdatingProperties() {
lastUsedReportTimerangeProperty.addListener(invokeSetter { settings.lastUsedReportTimerange = it })
lastUsedGroupByCategoryIdProperty.addListener(invokeSetter { settings.lastUsedGroupByCategoryId = it })
startDateProperty.addListener(invokeSetter { settings.startDate = it })
endDateProperty.addListener(invokeSetter { settings.endDate = it })
lastUsedFilePath.addListener(invokeSetter { settings.lastUsedFilePath = it })
overtimeStatisticsIgnoreWeekendsProperty.addListener(invokeSetter { settings.isOvertimeStatisticsIgnoreWeekends = it })
overtimeStatisticsIgnoreWithoutTimeEntriesProperty.addListener(invokeSetter { settings.isOvertimeStatisticsIgnoreWithoutTimeEntries = it })
overtimeStatisticsIgnoreTodayProperty.addListener(invokeSetter { settings.isOvertimeStatisticsIgnoreToday = it })
showFieldsInSearchResults.addListener(invokeSetter { settings.isShowFieldsInSearchResults = it })
showTagsInSearchResults.addListener(invokeSetter { settings.isShowTagsInSearchResults = it })
showDescriptionInSearchResults.addListener(invokeSetter { settings.isShowDescriptionInSearchResults = it })
statisticsPaneDividerPosition.addListener(invokeSetter { settings.statisticsPaneDividerPosition = it.toDouble() })
}
private fun <T> invokeSetter(block: (t : T) -> Unit): ChangeListener<T> {
return ChangeListener { _, _, newValue -> block.invoke(newValue) }
}
}
| mit |
java-opengl-labs/learn-OpenGL | src/main/kotlin/learnOpenGL/d_advancedOpenGL/2 stencil testing.kt | 1 | 6198 | package learnOpenGL.d_advancedOpenGL
/**
* Created by elect on 13/05/17.
*/
import glm_.func.rad
import glm_.glm
import glm_.mat4x4.Mat4
import gln.draw.glDrawArrays
import gln.get
import gln.glClearColor
import gln.glf.glf
import gln.glf.semantic
import gln.program.usingProgram
import gln.set
import gln.uniform.glUniform
import gln.vertexArray.glBindVertexArray
import gln.vertexArray.glEnableVertexAttribArray
import gln.vertexArray.glVertexAttribPointer
import learnOpenGL.a_gettingStarted.end
import learnOpenGL.a_gettingStarted.swapAndPoll
import learnOpenGL.a_gettingStarted.verticesCube
import learnOpenGL.b_lighting.camera
import learnOpenGL.b_lighting.clearColor0
import learnOpenGL.b_lighting.initWindow0
import learnOpenGL.b_lighting.processFrame
import learnOpenGL.common.loadTexture
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL13.GL_TEXTURE0
import org.lwjgl.opengl.GL13.glActiveTexture
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.glGetUniformLocation
import org.lwjgl.opengl.GL30.*
import uno.buffer.destroyBuf
import uno.buffer.intBufferBig
import uno.glsl.Program
import uno.glsl.glDeletePrograms
import uno.glsl.glUseProgram
fun main(args: Array<String>) {
with(StencilTesting()) {
run()
end()
}
}
private class StencilTesting {
val window = initWindow0("Depth Testing View")
val program = ProgramB()
val programSingleColor = ProgramA()
enum class Object { Cube, Plane }
val vao = intBufferBig<Object>()
val vbo = intBufferBig<Object>()
val tex = intBufferBig<Object>()
inner open class ProgramA(vertex: String = "stencil-testing.vert", fragment: String = "stencil-single-color.frag") : Program("shaders/d/_2", vertex, fragment) {
val model = glGetUniformLocation(name, "model")
val view = glGetUniformLocation(name, "view")
val proj = glGetUniformLocation(name, "projection")
}
inner class ProgramB(shader: String = "stencil-testing") : ProgramA("$shader.vert", "$shader.frag") {
init {
usingProgram(name) { "texture1".unit = semantic.sampler.DIFFUSE }
}
}
init {
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LESS)
glEnable(GL_STENCIL_TEST)
glStencilFunc(GL_NOTEQUAL, 1, 0xFF)
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
glGenVertexArrays(vao)
glGenBuffers(vbo)
for (i in Object.values()) {
glBindVertexArray(vao[i])
glBindBuffer(GL_ARRAY_BUFFER, vbo[i])
glBufferData(GL_ARRAY_BUFFER, if (i == Object.Cube) verticesCube else planeVertices, GL_STATIC_DRAW)
glEnableVertexAttribArray(glf.pos3_tc2)
glVertexAttribPointer(glf.pos3_tc2)
glBindVertexArray()
}
// load textures
tex[Object.Cube] = loadTexture("textures/marble.jpg")
tex[Object.Plane] = loadTexture("textures/metal.png")
}
fun run() {
while (window.open) {
window.processFrame()
// render
glClearColor(clearColor0)
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT or GL_STENCIL_BUFFER_BIT) // don't forget to clear the stencil buffer!
// set uniforms
glUseProgram(programSingleColor)
var model = Mat4()
val view = camera.viewMatrix
val projection = glm.perspective(camera.zoom.rad, window.aspect, 0.1f, 100f)
glUniform(programSingleColor.proj, projection)
glUniform(programSingleColor.view, view)
glUseProgram(program)
glUniform(program.proj, projection)
glUniform(program.view, view)
/* draw floor as normal, but don't write the floor to the stencil buffer, we only care about the containers.
We set its mask to 0x00 to not write to the stencil buffer. */
glStencilMask(0x00)
// floor
glBindVertexArray(vao[Object.Plane])
glBindTexture(GL_TEXTURE_2D, tex[Object.Plane])
glUniform(program.model, model)
glDrawArrays(GL_TRIANGLES, 6)
glBindVertexArray()
// 1st. render pass, draw objects as normal, writing to the stencil buffer
glStencilFunc(GL_ALWAYS, 1, 0xFF)
glStencilMask(0xFF)
// cubes
glBindVertexArray(vao[Object.Cube])
glActiveTexture(GL_TEXTURE0 + semantic.sampler.DIFFUSE)
glBindTexture(GL_TEXTURE_2D, tex[Object.Cube])
model.translate_(-1f, 0f, -1f)
glUniform(program.model, model)
glDrawArrays(GL_TRIANGLES, 36)
model = Mat4().translate_(2f, 0f, 0f)
glUniform(program.model, model)
glDrawArrays(GL_TRIANGLES, 36)
/* 2nd. render pass: now draw slightly scaled versions of the objects, this time disabling stencil writing.
Because the stencil buffer is now filled with several 1s. The parts of the buffer that are 1 are not
drawn, thus only drawing the objects' size differences, making it look like borders. */
glStencilFunc(GL_NOTEQUAL, 1, 0xFF)
glStencilMask(0x00)
glDisable(GL_DEPTH_TEST)
glUseProgram(programSingleColor)
val scale = 1.1f
// cubes
glBindVertexArray(vao[Object.Cube])
model = Mat4()
.translate_(-1f, 0f, -1f)
.scale_(scale)
glUniform(programSingleColor.model, model)
glDrawArrays(GL_TRIANGLES, 36)
model = Mat4()
.translate_(2f, 0f, 0f)
.scale_(scale)
glUniform(programSingleColor.model, model)
glDrawArrays(GL_TRIANGLES, 36)
glBindVertexArray(0)
glStencilMask(0xFF)
glEnable(GL_DEPTH_TEST)
window.swapAndPoll()
}
}
fun end() {
glDeletePrograms(program, programSingleColor)
glDeleteVertexArrays(vao)
glDeleteBuffers(vbo)
glDeleteTextures(tex)
destroyBuf(vao, vbo, tex)
window.end()
}
} | mit |
pbauerochse/youtrack-worklog-viewer | application/src/main/java/de/pbauerochse/worklogviewer/fx/ConnectorDescriptor.kt | 1 | 115 | package de.pbauerochse.worklogviewer.fx
data class ConnectorDescriptor(
val id: String,
val name: String
) | mit |
ligee/kotlin-jupyter | jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/util/libraryProcessing.kt | 1 | 925 | package org.jetbrains.kotlinx.jupyter.util
import org.jetbrains.kotlinx.jupyter.api.libraries.CodeExecution
import org.jetbrains.kotlinx.jupyter.api.libraries.VariablesSubstitutionAware
/**
* Replace all $<name> substrings in [str] with corresponding
* [mapping] values
*/
fun replaceVariables(str: String, mapping: Map<String, String>) =
mapping.asSequence().fold(str) { s, template ->
s.replace("\$${template.key}", template.value)
}
@JvmName("replaceVariablesString")
fun Iterable<String>.replaceVariables(mapping: Map<String, String>) = map { replaceVariables(it, mapping) }
@JvmName("replaceVariables")
fun <T : VariablesSubstitutionAware<T>> Iterable<T>.replaceVariables(mapping: Map<String, String>) = map { it.replaceVariables(mapping) }
@JvmName("replaceVariablesExecution")
fun Iterable<CodeExecution>.replaceVariables(mapping: Map<String, String>) = map { it.toExecutionCallback(mapping) }
| apache-2.0 |
lydia-schiff/hella-renderscript | app/src/main/java/com/lydiaschiff/hellaparallel/RsCameraPreviewRenderer.kt | 1 | 6987 | package com.lydiaschiff.hellaparallel
import android.graphics.ImageFormat
import android.os.Handler
import android.os.HandlerThread
import android.renderscript.Allocation
import android.renderscript.Allocation.OnBufferAvailableListener
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicYuvToRGB
import android.util.Log
import android.view.Surface
import androidx.annotation.AnyThread
import androidx.annotation.RequiresApi
import androidx.annotation.WorkerThread
import com.lydiaschiff.hella.FrameStats
import com.lydiaschiff.hella.RsRenderer
import com.lydiaschiff.hella.RsSurfaceRenderer
import com.lydiaschiff.hella.RsUtil
import com.lydiaschiff.hella.renderer.DefaultRsRenderer
/**
* Created by lydia on 10/30/17.
*/
@RequiresApi(19)
class RsCameraPreviewRenderer
@JvmOverloads
constructor(
private val rs: RenderScript,
private var rsRenderer: RsRenderer,
x: Int,
y: Int,
// guarded by "this"
private var renderHandler: Handler? = null
) : RsSurfaceRenderer, OnBufferAvailableListener, Runnable {
private val yuvInAlloc: Allocation =
RsUtil.createYuvIoInputAlloc(rs, x, y, ImageFormat.YUV_420_888).also {
it.setOnBufferAvailableListener(this)
}
private val rgbInAlloc: Allocation = RsUtil.createRgbAlloc(rs, x, y)
private val rgbOutAlloc: Allocation = RsUtil.createRgbIoOutputAlloc(rs, x, y)
private val yuvToRGBScript = ScriptIntrinsicYuvToRGB.create(rs, Element.RGBA_8888(rs)).apply {
setInput(yuvInAlloc)
}
// all vars guarded by "this"
private var renderThread: HandlerThread? =
when (renderHandler) {
null -> HandlerThread(TAG).apply {
start()
renderHandler = Handler(looper)
}
else -> null
}
private var droppedFrameLogger: FrameStats? = null
private var nFramesAvailable = 0
private var totalFrames = 0
private var totalDropped = 0
private var outputSurfaceIsSet = false
init {
Log.i(TAG, "Setting up RsCameraPreviewRenderer with ${rsRenderer.name} ($x,$y)")
}
constructor(rs: RenderScript, x: Int, y: Int) : this(rs, DefaultRsRenderer(), x, y)
@AnyThread
@Synchronized
override fun setRsRenderer(rsRenderer: RsRenderer) {
if (isRunning) {
this.rsRenderer = rsRenderer
Log.i(TAG, "updating RsRenderer to \"" + rsRenderer.name + "\"")
totalFrames = 0
totalDropped = 0
if (droppedFrameLogger != null) {
droppedFrameLogger!!.clear()
}
}
}
@Synchronized
fun setDroppedFrameLogger(droppedFrameLogger: FrameStats) {
this.droppedFrameLogger = droppedFrameLogger
}
/**
* Check if this renderer is still running or has been shutdown.
*
* @return true if we're running, else false
*/
@get:Synchronized
@get:AnyThread
override val isRunning: Boolean
get() {
if (renderHandler == null) {
Log.w(TAG, "renderer was already shut down")
return false
}
return true
}
/**
* Set the output surface to consume the stream of edited camera frames. This is probably
* from a SurfaceView or TextureView. Please make sure it's valid.
*
* @param surface a valid surface to consume a stream of edited frames from the camera
*/
@AnyThread
@Synchronized
override fun setOutputSurface(surface: Surface) {
if (isRunning) {
require(surface.isValid) { "output was invalid" }
rgbOutAlloc.surface = surface
outputSurfaceIsSet = true
Log.d(TAG, "output surface was set")
}
}
/**
* Get the Surface that the camera will push frames to. This is the Surface from our yuv
* input allocation. It will recieve a callback when a frame is available from the camera.
*
* @return a surface that consumes yuv frames from the camera preview, or null renderer is
* shutdown
*/
@get:Synchronized
@get:AnyThread
override val inputSurface: Surface?
get() = if (isRunning) yuvInAlloc.surface else null
/**
* Callback for when the camera has a new frame. We want to handle this on the render thread
* specific thread, so we'll increment nFramesAvailable and post a render request.
*/
@Synchronized
override fun onBufferAvailable(a: Allocation) {
if (isRunning) {
if (!outputSurfaceIsSet) {
Log.e(TAG, "We are getting frames from the camera but we never set the view " +
"surface to render to")
return
}
nFramesAvailable++
renderHandler!!.post(this)
}
}
/**
* Render a frame on the render thread. Everything is async except for ioSend() will block
* until the rendering completes. If we wanted to time it, make sure to log the time after
* that call.
*/
@WorkerThread
override fun run() {
var renderer: RsRenderer
var nFrames: Int
synchronized(this) {
if (!isRunning) {
return
}
renderer = rsRenderer
nFrames = nFramesAvailable
nFramesAvailable = 0
logFrames(nFrames)
renderHandler!!.removeCallbacks(this)
}
for (i in 0 until nFrames) {
yuvInAlloc.ioReceive()
}
yuvToRGBScript.forEach(rgbInAlloc)
renderer.renderFrame(rs, rgbInAlloc, rgbOutAlloc)
rgbOutAlloc.ioSend()
}
private fun logFrames(nFrames: Int) {
if (droppedFrameLogger != null) {
totalFrames++
val droppedFrames = nFrames - 1
totalDropped += droppedFrames
droppedFrameLogger!!.logFrame(TAG, droppedFrames, totalDropped, totalFrames)
}
}
/**
* Shut down the renderer when you're finished.
*/
@AnyThread
override fun shutdown() {
synchronized(this) {
if (!isRunning) {
Log.d(TAG, "requesting shutdown...")
renderHandler!!.removeCallbacks(this)
renderHandler!!.postAtFrontOfQueue {
Log.i(TAG, "shutting down")
synchronized(this) {
droppedFrameLogger = null
yuvInAlloc.destroy()
rgbInAlloc.destroy()
rgbOutAlloc.destroy()
yuvToRGBScript.destroy()
renderThread?.quitSafely()
}
}
renderHandler = null
}
}
}
companion object {
private const val TAG = "RsCameraPreviewRenderer"
}
} | mit |
ligee/kotlin-jupyter | src/main/kotlin/org/jetbrains/kotlinx/jupyter/apiImpl.kt | 1 | 6829 | package org.jetbrains.kotlinx.jupyter
import jupyter.kotlin.JavaRuntime
import org.jetbrains.kotlinx.jupyter.api.CodeCell
import org.jetbrains.kotlinx.jupyter.api.DisplayContainer
import org.jetbrains.kotlinx.jupyter.api.DisplayResult
import org.jetbrains.kotlinx.jupyter.api.DisplayResultWithCell
import org.jetbrains.kotlinx.jupyter.api.JREInfoProvider
import org.jetbrains.kotlinx.jupyter.api.JupyterClientType
import org.jetbrains.kotlinx.jupyter.api.KotlinKernelVersion
import org.jetbrains.kotlinx.jupyter.api.Notebook
import org.jetbrains.kotlinx.jupyter.api.RenderersProcessor
import org.jetbrains.kotlinx.jupyter.api.ResultsAccessor
import org.jetbrains.kotlinx.jupyter.api.VariableState
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionRequest
import org.jetbrains.kotlinx.jupyter.repl.impl.SharedReplContext
class DisplayResultWrapper private constructor(
val display: DisplayResult,
override val cell: CodeCellImpl,
) : DisplayResult by display, DisplayResultWithCell {
companion object {
fun create(display: DisplayResult, cell: CodeCellImpl): DisplayResultWrapper {
return if (display is DisplayResultWrapper) DisplayResultWrapper(display.display, cell)
else DisplayResultWrapper(display, cell)
}
}
}
class DisplayContainerImpl : DisplayContainer {
private val displays: MutableMap<String?, MutableList<DisplayResultWrapper>> = mutableMapOf()
fun add(display: DisplayResultWrapper) {
val list = displays.getOrPut(display.id) { mutableListOf() }
list.add(display)
}
fun add(display: DisplayResult, cell: CodeCellImpl) {
add(DisplayResultWrapper.create(display, cell))
}
override fun getAll(): List<DisplayResultWithCell> {
return displays.flatMap { it.value }
}
override fun getById(id: String?): List<DisplayResultWithCell> {
return displays[id].orEmpty()
}
fun update(id: String?, display: DisplayResult) {
val initialDisplays = displays[id] ?: return
val updated = initialDisplays.map { DisplayResultWrapper.create(display, it.cell) }
initialDisplays.clear()
initialDisplays.addAll(updated)
}
}
class CodeCellImpl(
override val notebook: NotebookImpl,
override val id: Int,
override val internalId: Int,
override val code: String,
override val preprocessedCode: String,
override val prevCell: CodeCell?,
) : CodeCell {
var resultVal: Any? = null
override val result: Any?
get() = resultVal
private var isStreamOutputUpToDate: Boolean = true
private var collectedStreamOutput: String = ""
private val streamBuilder = StringBuilder()
fun appendStreamOutput(output: String) {
isStreamOutputUpToDate = false
streamBuilder.append(output)
}
override val streamOutput: String
get() {
if (!isStreamOutputUpToDate) {
isStreamOutputUpToDate = true
collectedStreamOutput = streamBuilder.toString()
}
return collectedStreamOutput
}
override val displays = DisplayContainerImpl()
fun addDisplay(display: DisplayResult) {
val wrapper = DisplayResultWrapper.create(display, this)
displays.add(wrapper)
notebook.displays.add(wrapper)
}
}
class EvalData(
val executionCounter: Int,
val rawCode: String,
) {
constructor(evalRequestData: EvalRequestData) : this(evalRequestData.jupyterId, evalRequestData.code)
}
class NotebookImpl(
private val runtimeProperties: ReplRuntimeProperties,
) : Notebook {
private val cells = hashMapOf<Int, CodeCellImpl>()
internal var sharedReplContext: SharedReplContext? = null
override val cellsList: Collection<CodeCellImpl>
get() = cells.values
override val variablesState: Map<String, VariableState> get() {
return sharedReplContext?.evaluator?.variablesHolder
?: throw IllegalStateException("Evaluator is not initialized yet")
}
override val cellVariables: Map<Int, Set<String>> get() {
return sharedReplContext?.evaluator?.cellVariables
?: throw IllegalStateException("Evaluator is not initialized yet")
}
override val resultsAccessor = ResultsAccessor { getResult(it) }
override fun getCell(id: Int): CodeCellImpl {
return cells[id] ?: throw ArrayIndexOutOfBoundsException(
"There is no cell with number '$id'"
)
}
override fun getResult(id: Int): Any? {
return getCell(id).result
}
private val history = arrayListOf<CodeCellImpl>()
private var mainCellCreated = false
val displays = DisplayContainerImpl()
override fun getAllDisplays(): List<DisplayResultWithCell> {
return displays.getAll()
}
override fun getDisplaysById(id: String?): List<DisplayResultWithCell> {
return displays.getById(id)
}
override val kernelVersion: KotlinKernelVersion
get() = runtimeProperties.version ?: throw IllegalStateException("Kernel version is not known")
override val jreInfo: JREInfoProvider
get() = JavaRuntime
override val jupyterClientType: JupyterClientType by lazy {
JupyterClientDetector.detect()
}
fun variablesReportAsHTML(): String {
return generateHTMLVarsReport(variablesState)
}
fun variablesReport(): String {
return if (variablesState.isEmpty()) ""
else {
buildString {
append("Visible vars: \n")
variablesState.forEach { (name, currentState) ->
append("\t$name : ${currentState.stringValue}\n")
}
}
}
}
fun addCell(
internalId: Int,
preprocessedCode: String,
data: EvalData,
): CodeCellImpl {
val cell = CodeCellImpl(this, data.executionCounter, internalId, data.rawCode, preprocessedCode, lastCell)
cells[data.executionCounter] = cell
history.add(cell)
mainCellCreated = true
return cell
}
fun beginEvalSession() {
mainCellCreated = false
}
override fun history(before: Int): CodeCellImpl? {
val offset = if (mainCellCreated) 1 else 0
return history.getOrNull(history.size - offset - before)
}
override val currentCell: CodeCellImpl?
get() = history(0)
override val lastCell: CodeCellImpl?
get() = history(1)
override val renderersProcessor: RenderersProcessor
get() = sharedReplContext?.renderersProcessor ?: throw IllegalStateException("Type renderers processor is not initialized yet")
override val libraryRequests: Collection<LibraryResolutionRequest>
get() = sharedReplContext?.librariesProcessor?.requests.orEmpty()
}
| apache-2.0 |
czyzby/ktx | assets/src/test/kotlin/ktx/assets/FilesTest.kt | 2 | 2203 | package ktx.assets
import com.badlogic.gdx.Files.FileType.Absolute
import com.badlogic.gdx.Files.FileType.Classpath
import com.badlogic.gdx.Files.FileType.External
import com.badlogic.gdx.Files.FileType.Internal
import com.badlogic.gdx.Files.FileType.Local
import com.badlogic.gdx.Gdx
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
/**
* Tests files-related utilities.
*/
class FilesTest {
@Before
fun `mock Files`() {
Gdx.files = MockFiles()
}
@Test
fun `should convert string to classpath FileHandle`() {
val file = "my/package/classpath.file".toClasspathFile()
assertNotNull(file)
assertEquals(Classpath, file.type())
assertEquals("my/package/classpath.file", file.path())
}
@Test
fun `should convert string to internal FileHandle`() {
val file = "internal.file".toInternalFile()
assertNotNull(file)
assertEquals(Internal, file.type())
assertEquals("internal.file", file.path())
}
@Test
fun `should convert string to local FileHandle`() {
val file = "local.file".toLocalFile()
assertNotNull(file)
assertEquals(Local, file.type())
assertEquals("local.file", file.path())
}
@Test
fun `should convert string to external FileHandle`() {
val file = "some/directory/external.file".toExternalFile()
assertNotNull(file)
assertEquals(External, file.type())
assertEquals("some/directory/external.file", file.path())
}
@Test
fun `should convert string to absolute FileHandle`() {
val file = "/home/mock/absolute.file".toAbsoluteFile()
assertNotNull(file)
assertEquals(Absolute, file.type())
assertEquals("/home/mock/absolute.file", file.path())
}
@Test
fun `should create FileHandle with default type`() {
val file = file("mock.file")
assertNotNull(file)
assertEquals(Internal, file.type())
assertEquals("mock.file", file.path())
}
@Test
fun `should create FileHandle with custom type`() {
val file = file("/home/ktx/mock.file", type = Absolute)
assertNotNull(file)
assertEquals(Absolute, file.type())
assertEquals("/home/ktx/mock.file", file.path())
}
}
| cc0-1.0 |
rhdunn/xquery-intellij-plugin | src/lang-xquery/test/uk/co/reecedunn/intellij/plugin/xquery/tests/psi/XQueryPsiTest.kt | 1 | 523672 | /*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.tests.psi
import com.intellij.mock.MockResolveScopeManager
import com.intellij.navigation.ItemPresentation
import com.intellij.navigation.NavigationItem
import com.intellij.openapi.extensions.PluginId
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.impl.DebugUtil
import com.intellij.psi.impl.ResolveScopeManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.ProjectScopeBuilder
import com.intellij.psi.util.elementType
import org.hamcrest.CoreMatchers.*
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import uk.co.reecedunn.intellij.plugin.core.extensions.registerServiceInstance
import uk.co.reecedunn.intellij.plugin.core.navigation.ItemPresentationEx
import uk.co.reecedunn.intellij.plugin.core.psi.resourcePath
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.core.sequences.descendants
import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree
import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat
import uk.co.reecedunn.intellij.plugin.core.tests.module.MockModuleManager
import uk.co.reecedunn.intellij.plugin.core.tests.psi.MockProjectScopeBuilder
import uk.co.reecedunn.intellij.plugin.core.vfs.ResourceVirtualFileSystem
import uk.co.reecedunn.intellij.plugin.intellij.lang.XQuerySpec
import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation
import uk.co.reecedunn.intellij.plugin.xdm.module.path.XdmModuleType
import uk.co.reecedunn.intellij.plugin.xdm.types.*
import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.*
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.*
import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathTokenType
import uk.co.reecedunn.intellij.plugin.xpath.model.getPrincipalNodeKind
import uk.co.reecedunn.intellij.plugin.xpath.model.getUsageType
import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathElementType
import uk.co.reecedunn.intellij.plugin.xpath.psi.impl.XmlNCNameImpl
import uk.co.reecedunn.intellij.plugin.xpath.psi.reference.XPathFunctionNameReference
import uk.co.reecedunn.intellij.plugin.xpath.resources.XPathIcons
import uk.co.reecedunn.intellij.plugin.xpm.context.XpmUsageType
import uk.co.reecedunn.intellij.plugin.xpm.context.expand
import uk.co.reecedunn.intellij.plugin.xpm.optree.annotation.XpmAccessLevel
import uk.co.reecedunn.intellij.plugin.xpm.optree.annotation.XpmAnnotated
import uk.co.reecedunn.intellij.plugin.xpm.optree.annotation.XpmVariadic
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.*
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.impl.XpmContextItem
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.impl.XpmEmptyExpression
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.type.XpmSequenceTypeExpression
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.type.XpmSequenceTypeOperation
import uk.co.reecedunn.intellij.plugin.xpm.optree.function.*
import uk.co.reecedunn.intellij.plugin.xpm.optree.function.impl.XpmMissingArgument
import uk.co.reecedunn.intellij.plugin.xpm.optree.item.XpmArrayExpression
import uk.co.reecedunn.intellij.plugin.xpm.optree.item.XpmMapExpression
import uk.co.reecedunn.intellij.plugin.xpm.optree.item.keyName
import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XdmNamespaceType
import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceDeclaration
import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceProvider
import uk.co.reecedunn.intellij.plugin.xpm.optree.path.XpmAxisType
import uk.co.reecedunn.intellij.plugin.xpm.optree.path.XpmPathStep
import uk.co.reecedunn.intellij.plugin.xpm.optree.variable.*
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginDefaultCaseClause
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginDirNamespaceAttribute
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.*
import uk.co.reecedunn.intellij.plugin.xquery.model.XQueryPrologResolver
import uk.co.reecedunn.intellij.plugin.xquery.model.getNamespaceType
import uk.co.reecedunn.intellij.plugin.xquery.optree.XQueryFunctionProvider
import uk.co.reecedunn.intellij.plugin.xquery.optree.XQueryNamespaceProvider
import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryElementType
import uk.co.reecedunn.intellij.plugin.xquery.resources.XQueryIcons
import uk.co.reecedunn.intellij.plugin.xquery.tests.parser.ParserTestCase
import xqt.platform.intellij.xpath.XPathTokenProvider
import java.math.BigDecimal
import java.math.BigInteger
@Suppress("Reformat", "ClassName", "RedundantVisibilityModifier")
@DisplayName("XQuery 3.1 - IntelliJ Program Structure Interface (PSI)")
class XQueryPsiTest : ParserTestCase() {
override val pluginId: PluginId = PluginId.getId("XQueryPsiTest")
private val res = ResourceVirtualFileSystem(this::class.java.classLoader)
fun parseResource(resource: String): XQueryModule = res.toPsiFile(resource, project)
override fun registerModules(manager: MockModuleManager) {
manager.addModule(res.findFileByPath("tests/module-xquery")!!)
}
override fun registerServicesAndExtensions() {
super.registerServicesAndExtensions()
XpmNamespaceProvider.register(this, XQueryNamespaceProvider)
XpmFunctionProvider.register(this, XQueryFunctionProvider)
project.registerServiceInstance(ProjectScopeBuilder::class.java, MockProjectScopeBuilder())
project.registerServiceInstance(ResolveScopeManager::class.java, MockResolveScopeManager(project))
}
@Nested
@DisplayName("XQuery 4.0 ED (2) Basics ; XQuery 3.1 (2) Basics")
internal inner class Basics {
@Nested
@DisplayName("XQuery 3.1 EBNF (217) URILiteral")
internal inner class URILiteral {
@Test
@DisplayName("uri literal content")
fun uriLiteral() {
val literal = parse<XPathUriLiteral>("module namespace test = \"Lorem ipsum.\uFFFF\"")[0] as XsAnyUriValue
assertThat(literal.data, `is`("Lorem ipsum.\uFFFF")) // U+FFFF = BAD_CHARACTER token.
assertThat(literal.element, sameInstance(literal as PsiElement))
}
@Test
@DisplayName("unclosed uri literal content")
fun unclosedUriLiteral() {
val literal = parse<XPathUriLiteral>("module namespace test = \"Lorem ipsum.")[0] as XsAnyUriValue
assertThat(literal.data, `is`("Lorem ipsum."))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
@Test
@DisplayName("EscapeApos tokens")
fun escapeApos() {
val literal = parse<XPathUriLiteral>("module namespace test = '''\"\"'")[0] as XsAnyUriValue
assertThat(literal.data, `is`("'\"\""))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
@Test
@DisplayName("EscapeQuot tokens")
fun escapeQuot() {
val literal = parse<XPathUriLiteral>("module namespace test = \"''\"\"\"")[0] as XsAnyUriValue
assertThat(literal.data, `is`("''\""))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
@Test
@DisplayName("PredefinedEntityRef tokens")
fun predefinedEntityRef() {
// entity reference types: XQuery, HTML4, HTML5, UTF-16 surrogate pair, multi-character entity, empty, partial
val literal = parse<XPathUriLiteral>("module namespace test = \"<áā𝔄≪̸&;>\"")[0] as XsAnyUriValue
assertThat(literal.data, `is`("<áā\uD835\uDD04≪\u0338&;>"))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
@Test
@DisplayName("CharRef tokens")
fun charRef() {
val literal = parse<XPathUriLiteral>("module namespace test = \"   𝔠\"")[0] as XsAnyUriValue
assertThat(literal.data, `is`("\u00A0\u00A0\u0020\uD835\uDD20"))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (223) URIQualifiedName")
internal inner class URIQualifiedName {
@Test
@DisplayName("non-keyword local name")
fun identifier() {
val qname = parse<XPathURIQualifiedName>("Q{http://www.example.com}test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("keyword local name")
fun keyword() {
val qname = parse<XPathURIQualifiedName>("Q{http://www.example.com}option")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("option"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("empty namespace")
fun emptyNamespace() {
val qname = parse<XPathURIQualifiedName>("Q{}test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`(""))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("missing local name")
fun noLocalName() {
val qname = parse<XPathURIQualifiedName>("Q{http://www.example.com}")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("wildcard")
fun wildcard() {
val qname = parse<XPathURIQualifiedName>("declare option Q{http://www.example.com}* \"\";")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.localName, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.localName!!.data, `is`("*"))
}
@Test
@DisplayName("PsiNameIdentifierOwner")
fun psiNameIdentifierOwner() {
val name = parse<XPathURIQualifiedName>("(: :) Q{http://www.example.com}test")[0] as PsiNameIdentifierOwner
val file = name.containingFile
assertThat(name.name, `is`("test"))
assertThat(name.textOffset, `is`(31))
assertThat(name.nameIdentifier, `is`(instanceOf(XmlNCNameImpl::class.java)))
assertThat(name.nameIdentifier?.text, `is`("test"))
DebugUtil.performPsiModification<Throwable>("rename") {
val renamed = name.setName("lorem-ipsum")
assertThat(renamed, `is`(instanceOf(XPathURIQualifiedName::class.java)))
assertThat(renamed.text, `is`("Q{http://www.example.com}lorem-ipsum"))
assertThat((renamed as PsiNameIdentifierOwner).name, `is`("lorem-ipsum"))
}
assertThat(file.text, `is`("(: :) Q{http://www.example.com}lorem-ipsum"))
}
@Test
@DisplayName("expand; namespace prefix in statically-known namespaces")
fun expandToExistingNamespace() {
val qname = parse<XPathURIQualifiedName>("Q{http://www.w3.org/2001/XMLSchema}test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`("http://www.w3.org/2001/XMLSchema"))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
// The URIQualifiedName itself, not bound to a namespace.
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.w3.org/2001/XMLSchema"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("expand; namespace prefix not in statically-known namespaces")
fun expandToMissingNamespace() {
val qname = parse<XPathURIQualifiedName>("Q{http://www.example.com}test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
// The URIQualifiedName itself, not bound to a namespace.
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.com"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (224) BracedURILiteral")
internal inner class BracedURILiteral {
@Test
@DisplayName("braced uri literal content")
fun bracedUriLiteral() {
val literal = parse<XPathBracedURILiteral>("Q{Lorem ipsum.\uFFFF}")[0] as XsAnyUriValue
assertThat(literal.data, `is`("Lorem ipsum.\uFFFF")) // U+FFFF = BAD_CHARACTER token.
assertThat(literal.context, `is`(XdmUriContext.Namespace))
assertThat(literal.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
@Test
@DisplayName("unclosed braced uri literal content")
fun unclosedBracedUriLiteral() {
val literal = parse<XPathBracedURILiteral>("Q{Lorem ipsum.")[0] as XsAnyUriValue
assertThat(literal.data, `is`("Lorem ipsum."))
assertThat(literal.context, `is`(XdmUriContext.Namespace))
assertThat(literal.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
@Test
@DisplayName("PredefinedEntityRef tokens")
fun predefinedEntityRef() {
// entity reference types: XQuery, HTML4, HTML5, UTF-16 surrogate pair, multi-character entity, empty, partial
val literal = parse<XPathBracedURILiteral>("Q{<áā𝔄≪̸&;>}")[0] as XsAnyUriValue
assertThat(literal.data, `is`("<áā\uD835\uDD04≪\u0338&;>"))
assertThat(literal.context, `is`(XdmUriContext.Namespace))
assertThat(literal.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
@Test
@DisplayName("CharRef tokens")
fun charRef() {
val literal = parse<XPathBracedURILiteral>("Q{   𝔠}")[0] as XsAnyUriValue
assertThat(literal.data, `is`("\u00A0\u00A0\u0020\uD835\uDD20"))
assertThat(literal.context, `is`(XdmUriContext.Namespace))
assertThat(literal.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (234) QName")
internal inner class QName {
@Test
@DisplayName("non-keyword prefix; non-keyword local name")
fun identifier() {
val qname = parse<XPathQName>("fn:true")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("keyword prefix; non-keyword local name")
fun keywordPrefix() {
val qname = parse<XPathQName>("option:test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("option"))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("non-keyword prefix; keyword local name")
fun keywordLocalName() {
val qname = parse<XPathQName>("test:case")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("test"))
assertThat(qname.localName!!.data, `is`("case"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("missing local name")
fun noLocalName() {
val qname = parse<XPathQName>("xs:")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("xs"))
assertThat(qname.localName, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("whitespace in QName; before ':'")
fun whitespaceInQName_beforeColon() {
val qname = parse<XPathQName>("xs :string")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("xs"))
assertThat(qname.localName!!.data, `is`("string"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("whitespace in QName; after ':'")
fun whitespaceInQName_afterColon() {
val qname = parse<XPathQName>("xs: string")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("xs"))
assertThat(qname.localName!!.data, `is`("string"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("whitespace in QName; before and after ':'")
fun whitespaceInQName_beforeAndAfterColon() {
val qname = parse<XPathQName>("xs : string")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("xs"))
assertThat(qname.localName!!.data, `is`("string"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("PsiNameIdentifierOwner")
fun psiNameIdentifierOwner() {
val name = parse<XPathQName>("(: :) a:test")[0] as PsiNameIdentifierOwner
val file = name.containingFile
assertThat(name.name, `is`("test"))
assertThat(name.textOffset, `is`(8))
assertThat(name.nameIdentifier, `is`(instanceOf(XmlNCNameImpl::class.java)))
assertThat(name.nameIdentifier?.text, `is`("test"))
DebugUtil.performPsiModification<Throwable>("rename") {
val renamed = name.setName("lorem-ipsum")
assertThat(renamed, `is`(instanceOf(XPathQName::class.java)))
assertThat(renamed.text, `is`("a:lorem-ipsum"))
assertThat((renamed as PsiNameIdentifierOwner).name, `is`("lorem-ipsum"))
}
assertThat(file.text, `is`("(: :) a:lorem-ipsum"))
}
@Test
@DisplayName("expand; namespace prefix in statically-known namespaces")
fun expandToExistingNamespace() {
val qname = parse<XPathQName>("xs:test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("xs"))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.w3.org/2001/XMLSchema"))
assertThat(expanded[0].prefix!!.data, `is`("xs"))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("expand; namespace prefix not in statically-known namespaces")
fun expandToMissingNamespace() {
val qname = parse<XPathQName>("xsd:test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("xsd"))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(0))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (235) NCName")
internal inner class NCName {
@Test
@DisplayName("identifier")
fun identifier() {
val qname = parse<XPathNCName>("test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("keyword")
fun keyword() {
val qname = parse<XPathNCName>("order")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("order"))
assertThat(qname.element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("wildcard")
fun wildcard() {
val qname = parse<XPathNCName>("declare option * \"\";")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.localName, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.localName!!.data, `is`("*"))
}
@Test
@DisplayName("PsiNameIdentifierOwner")
fun psiNameIdentifierOwner() {
val name = parse<XPathNCName>("(: :) test")[0] as PsiNameIdentifierOwner
val file = name.containingFile
assertThat(name.name, `is`("test"))
assertThat(name.textOffset, `is`(6))
assertThat(name.nameIdentifier, `is`(instanceOf(XmlNCNameImpl::class.java)))
assertThat(name.nameIdentifier?.text, `is`("test"))
DebugUtil.performPsiModification<Throwable>("rename") {
val renamed = name.setName("lorem-ipsum")
assertThat(renamed, `is`(instanceOf(XPathNCName::class.java)))
assertThat(renamed.text, `is`("lorem-ipsum"))
assertThat((renamed as PsiNameIdentifierOwner).name, `is`("lorem-ipsum"))
}
assertThat(file.text, `is`("(: :) lorem-ipsum"))
}
@Test
@DisplayName("expand")
fun expand() {
val qname = parse<XPathNCName>("test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
@Test
@DisplayName("Namespaces in XML 1.0 (3) Declaring Namespaces : EBNF (4) NCName")
fun xmlNCName() {
val literal = parse<XmlNCNameImpl>("test")[0] as XsNCNameValue
assertThat(literal.data, `is`("test"))
assertThat(literal.element, sameInstance(literal as PsiElement))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.4) Sequence Types ; XQuery 3.1 (2.5.4) SequenceType Syntax")
internal inner class SequenceTypes {
@Nested
@DisplayName("XQuery 3.1 EBNF (184) SequenceType")
internal inner class SequenceType {
@Test
@DisplayName("empty sequence")
fun emptySequence() {
val type = parse<XPathSequenceType>("() instance of empty-sequence ( (::) )")[0] as XdmSequenceType
assertThat(type.typeName, `is`("empty-sequence()"))
assertThat(type.itemType, `is`(nullValue()))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(0))
}
@Test
@DisplayName("optional item")
fun optionalItem() {
val type = parse<XPathSequenceType>("() instance of xs:string ?")[0] as XdmSequenceType
assertThat(type.typeName, `is`("xs:string?"))
assertThat(type.itemType?.typeName, `is`("xs:string"))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional sequence")
fun optionalSequence() {
val type = parse<XPathSequenceType>("() instance of xs:string *")[0] as XdmSequenceType
assertThat(type.typeName, `is`("xs:string*"))
assertThat(type.itemType?.typeName, `is`("xs:string"))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
@Test
@DisplayName("sequence")
fun sequence() {
val type = parse<XPathSequenceType>("() instance of xs:string +")[0] as XdmSequenceType
assertThat(type.typeName, `is`("xs:string+"))
assertThat(type.itemType?.typeName, `is`("xs:string"))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
@Test
@DisplayName("parenthesized item type")
fun parenthesizedItemType() {
val type = parse<XPathSequenceType>("() instance of ( xs:string ) ?")[0] as XdmSequenceType
assertThat(type.typeName, `is`("(xs:string)?"))
assertThat(type.itemType?.typeName, `is`("xs:string"))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("parenthesized sequence type")
fun parenthesizedSequenceType() {
val type = parse<XPathSequenceType>("() instance of ( xs:string + ) ?")[0] as XdmSequenceType
assertThat(type.typeName, `is`("(xs:string+)?"))
// NOTE: For the purposes of the plugin w.r.t. keeping consistent
// analysis/logic given that mixing SequenceTypes like this is an
// error, the outer-most SequenceType overrides the inner one.
assertThat(type.itemType?.typeName, `is`("xs:string"))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6) Item Types ; XQuery 3.1 (2.5.5) SequenceType Matching")
internal inner class ItemTypes {
@Nested
@DisplayName("XQuery 4.0 ED (3.6.1) General Item Types")
internal inner class GeneralItemTypes {
@Test
@DisplayName("XQuery 3.1 EBNF (186) ItemType ; XQuery 4.0 ED EBNF (203) AnyItemTest")
fun itemType() {
val type = parse<XPathAnyItemTest>("() instance of item ( (::) )")[0] as XdmItemType
assertThat(type.typeName, `is`("item()"))
assertThat(type.typeClass, `is`(sameInstance(XdmItem::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (216) ParenthesizedItemType")
internal inner class ParenthesizedItemType {
@Test
@DisplayName("item type")
fun itemType() {
val type = parse<XPathParenthesizedItemType>("() instance of ( text ( (::) ) )")[0] as XdmSequenceType
assertThat(type.typeName, `is`("(text())"))
assertThat(type.itemType?.typeName, `is`("text()"))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("error recovery: missing type")
fun missingType() {
val type = parse<XPathParenthesizedItemType>("() instance of ( (::) )")[0] as XdmSequenceType
assertThat(type.typeName, `is`("(empty-sequence())"))
assertThat(type.itemType, `is`(nullValue()))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(0))
}
@Test
@DisplayName("error recovery: empty sequence")
fun emptySequence() {
val type = parse<XPathParenthesizedItemType>("() instance of ( empty-sequence ( (::) ) )")[0] as XdmSequenceType
assertThat(type.typeName, `is`("(empty-sequence())"))
assertThat(type.itemType, `is`(nullValue()))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(0))
}
@Test
@DisplayName("error recovery: optional item")
fun optionalItem() {
val type = parse<XPathParenthesizedItemType>("() instance of ( xs:string ? ) )")[0] as XdmSequenceType
assertThat(type.typeName, `is`("(xs:string?)"))
assertThat(type.itemType?.typeName, `is`("xs:string"))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("error recovery: optional sequence")
fun optionalSequence() {
val type = parse<XPathParenthesizedItemType>("() instance of ( xs:string * ) )")[0] as XdmSequenceType
assertThat(type.typeName, `is`("(xs:string*)"))
assertThat(type.itemType?.typeName, `is`("xs:string"))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
@Test
@DisplayName("error recovery: optional item")
fun sequence() {
val type = parse<XPathParenthesizedItemType>("() instance of ( xs:string + ) )")[0] as XdmSequenceType
assertThat(type.typeName, `is`("(xs:string+)"))
assertThat(type.itemType?.typeName, `is`("xs:string"))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.2.1) Local Union Types")
internal inner class AtomicAndUnionTypes {
@Nested
@DisplayName("XQuery 3.1 EBNF (187) AtomicOrUnionType")
internal inner class AtomicOrUnionType {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
() instance of test
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultType))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Type))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("item type")
fun itemType() {
val test = parse<XPathAtomicOrUnionType>("() instance of xs:string")[0]
assertThat(qname_presentation(test.type), `is`("xs:string"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("xs:string"))
assertThat(type.typeClass, `is`(sameInstance(XsAnySimpleType::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (206) TypeName")
internal inner class TypeName {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
() instance of element(*, test)
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultType))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Type))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
}
@Test
@DisplayName("item type")
fun itemType() {
val test = parse<XPathTypeName>("() instance of element( *, xs:string )")[0]
assertThat(test.type, `is`(sameInstance(test.children().filterIsInstance<XsQNameValue>().first())))
val type = test as XdmItemType
assertThat(type.typeName, `is`("xs:string"))
assertThat(type.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
@Test
@DisplayName("invalid QName")
fun invalidQName() {
val test = parse<XPathTypeName>("() instance of element( *, xs: )")[0]
assertThat(test.type, `is`(sameInstance(test.children().filterIsInstance<XsQNameValue>().first())))
val type = test as XdmItemType
assertThat(type.typeName, `is`(""))
assertThat(type.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.2.1) Local Union Types")
internal inner class LocalUnionTypes {
@Nested
@DisplayName("XQuery 4.0 ED EBNF (233) LocalUnionType")
internal inner class LocalUnionType {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
declare type decl = union(test);
"""
)[1] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultType))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Type))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("empty")
fun empty() {
val test = parse<XPathLocalUnionType>("() instance of union ( (::) )")[0]
val memberTypes = test.memberTypes.toList()
assertThat(memberTypes.size, `is`(0))
val type = test as XdmItemType
assertThat(type.typeName, `is`("union()"))
assertThat(type.typeClass, `is`(sameInstance(XdmAnyUnionType::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("one")
fun one() {
val test = parse<XPathLocalUnionType>("() instance of union ( xs:string )")[0]
val memberTypes = test.memberTypes.toList()
assertThat(memberTypes.size, `is`(1))
assertThat(memberTypes[0].typeName, `is`("xs:string"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("union(xs:string)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAnyUnionType::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("many")
fun many() {
val test = parse<XPathLocalUnionType>("() instance of union ( xs:string , xs:anyURI )")[0]
val memberTypes = test.memberTypes.toList()
assertThat(memberTypes.size, `is`(2))
assertThat(memberTypes[0].typeName, `is`("xs:string"))
assertThat(memberTypes[1].typeName, `is`("xs:anyURI"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("union(xs:string, xs:anyURI)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAnyUnionType::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.2.2) Enumeration Types")
internal inner class EnumerationTypes {
@Nested
@DisplayName("XQuery 4.0 ED EBNF (236) EnumerationType")
internal inner class LocalUnionType {
@Test
@DisplayName("empty")
fun empty() {
val test = parse<XPathEnumerationType>("() instance of enum ( (::) )")[0]
val values = test.values.toList()
assertThat(values.size, `is`(0))
val type = test as XdmItemType
assertThat(type.typeName, `is`("enum()"))
assertThat(type.typeClass, `is`(sameInstance(XsStringValue::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("one")
fun one() {
val test = parse<XPathEnumerationType>("() instance of enum ( \"one\" )")[0]
val values = test.values.toList()
assertThat(values.size, `is`(1))
assertThat(values[0].data, `is`("one"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("enum(\"one\")"))
assertThat(type.typeClass, `is`(sameInstance(XsStringValue::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("many")
fun many() {
val test = parse<XPathEnumerationType>("() instance of enum ( \"one\" , \"two\" )")[0]
val values = test.values.toList()
assertThat(values.size, `is`(2))
assertThat(values[0].data, `is`("one"))
assertThat(values[1].data, `is`("two"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("enum(\"one\", \"two\")"))
assertThat(type.typeClass, `is`(sameInstance(XsStringValue::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.3.1) Simple Node Tests")
internal inner class SimpleNodeTests {
@Test
@DisplayName("XQuery 3.1 EBNF (189) AnyKindTest")
fun anyKindTest() {
val type = parse<XPathAnyKindTest>("() instance of node ( (::) )")[0] as XdmItemType
assertThat(type.typeName, `is`("node()"))
assertThat(type.typeClass, `is`(sameInstance(XdmNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (190) DocumentTest")
internal inner class DocumentTest {
@Test
@DisplayName("any")
fun any() {
val test = parse<XPathDocumentTest>("() instance of document-node ( (::) )")[0]
assertThat(test.rootNodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("document-node()"))
assertThat(type.typeClass, `is`(sameInstance(XdmDocumentNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("element test")
fun elementTest() {
val test = parse<XPathDocumentTest>("() instance of document-node ( element ( (::) ) )")[0]
assertThat(test.rootNodeType, `is`(instanceOf(XPathElementTest::class.java)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("document-node(element())"))
assertThat(type.typeClass, `is`(sameInstance(XdmDocumentNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("schema element test")
fun schemaElementTest() {
val test = parse<XPathDocumentTest>("() instance of document-node ( schema-element ( test ) )")[0]
assertThat(test.rootNodeType, `is`(instanceOf(XPathSchemaElementTest::class.java)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("document-node(schema-element(test))"))
assertThat(type.typeClass, `is`(sameInstance(XdmDocumentNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Test
@DisplayName("XQuery 3.1 EBNF (191) TextTest")
fun textTest() {
val type = parse<PluginAnyTextTest>("() instance of text ( (::) )")[0] as XdmItemType
assertThat(type.typeName, `is`("text()"))
assertThat(type.typeClass, `is`(sameInstance(XdmTextNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("XQuery 3.1 EBNF (192) CommentTest")
fun commentTest() {
val type = parse<XPathCommentTest>("() instance of comment ( (::) )")[0] as XdmItemType
assertThat(type.typeName, `is`("comment()"))
assertThat(type.typeClass, `is`(sameInstance(XdmCommentNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("XQuery 3.1 EBNF (193) NamespaceNodeTest")
fun namespaceNodeTest() {
val type = parse<XPathNamespaceNodeTest>("() instance of namespace-node ( (::) )")[0] as XdmItemType
assertThat(type.typeName, `is`("namespace-node()"))
assertThat(type.typeClass, `is`(sameInstance(XdmNamespaceNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (194) PITest")
internal inner class PITest {
@Test
@DisplayName("any")
fun any() {
val test = parse<XPathPITest>("() instance of processing-instruction ( (::) )")[0]
assertThat(test.nodeName, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("processing-instruction()"))
assertThat(type.typeClass, `is`(sameInstance(XdmProcessingInstructionNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("NCName")
fun ncname() {
val test = parse<XPathPITest>("() instance of processing-instruction ( test )")[0]
assertThat(test.nodeName, `is`(instanceOf(XsNCNameValue::class.java)))
assertThat((test.nodeName as XsNCNameValue).data, `is`("test"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("processing-instruction(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmProcessingInstructionNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("StringLiteral")
fun stringLiteral() {
val test = parse<XPathPITest>("() instance of processing-instruction ( \" test \" )")[0]
val nodeName = test.nodeName as XsNCNameValue
assertThat(nodeName.data, `is`("test"))
assertThat(nodeName.element, `is`(sameInstance(test.children().filterIsInstance<XPathStringLiteral>().firstOrNull())))
val type = test as XdmItemType
assertThat(type.typeName, `is`("processing-instruction(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmProcessingInstructionNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.3.2) Element Test ; XQuery 3.1 (2.5.5.3) Element Test")
internal inner class ElementTest {
@Nested
@DisplayName("XQuery 3.1 EBNF (199) ElementTest")
internal inner class ElementTest {
@Test
@DisplayName("any; empty")
fun anyEmpty() {
val test = parse<XPathElementTest>("() instance of element ( (::) )")[0]
assertThat(test.nodeName, `is`(nullValue()))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element()"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("any; wildcard")
fun anyWildcard() {
val test = parse<XPathElementTest>("() instance of element ( * )")[0]
assertThat(test.nodeName, `is`(nullValue()))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element()"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("name only")
fun nameOnly() {
val test = parse<XPathElementTest>("() instance of element ( test )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("type only")
fun typeOnly() {
val test = parse<XPathElementTest>("() instance of element ( * , elem-type )")[0]
assertThat(test.nodeName, `is`(nullValue()))
val nodeType = test.nodeType!!
assertThat(nodeType.typeName, `is`("elem-type"))
assertThat(nodeType.itemType?.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(nodeType.lowerBound, `is`(1))
assertThat(nodeType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element(*,elem-type)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("nillable type only")
fun nillableTypeOnly() {
val test = parse<XPathElementTest>("() instance of element ( * , elem-type ? )")[0]
assertThat(test.nodeName, `is`(nullValue()))
val nodeType = test.nodeType!!
assertThat(nodeType.typeName, `is`("elem-type?"))
assertThat(nodeType.itemType?.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(nodeType.lowerBound, `is`(0))
assertThat(nodeType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element(*,elem-type?)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("name and type")
fun nameAndType() {
val test = parse<XPathElementTest>("() instance of element ( test , elem-type )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
val nodeType = test.nodeType!!
assertThat(nodeType.typeName, `is`("elem-type"))
assertThat(nodeType.itemType?.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(nodeType.lowerBound, `is`(1))
assertThat(nodeType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element(test,elem-type)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("name and nillable type")
fun nameAndNillableType() {
val test = parse<XPathElementTest>("() instance of element ( test , elem-type ? )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
val nodeType = test.nodeType!!
assertThat(nodeType.typeName, `is`("elem-type?"))
assertThat(nodeType.itemType?.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(nodeType.lowerBound, `is`(0))
assertThat(nodeType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element(test,elem-type?)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("invalid TypeName")
fun invalidTypeName() {
val test = parse<XPathElementTest>("() instance of element ( test , xs: )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Test
@DisplayName("XQuery 4.0 ED EBNF (215) ElementTest ; XQuery 4.0 ED EBNF (128) NameTest")
fun elementTest_nameTest() {
val test = parse<XPathElementTest>("() instance of element ( *:test )")[0]
assertThat(qname_presentation(test.nodeName!!), `is`("*:test"))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("element(*:test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (204) ElementName")
internal inner class ElementName {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
() instance of element(test)
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultElement))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Element))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.3.3) Schema Element Test ; XQuery 3.1 (2.5.5.4) Schema Element Test")
internal inner class SchemaElementTest {
@Nested
@DisplayName("XQuery 3.1 EBNF (201) SchemaElementTest")
internal inner class SchemaElementTest {
@Test
@DisplayName("missing element declaration")
fun missingElementDeclaration() {
val test = parse<XPathSchemaElementTest>("() instance of schema-element ( (::) )")[0]
assertThat(test.nodeName, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("schema-element(<unknown>)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("element declaration")
fun elementDeclaration() {
val test = parse<XPathSchemaElementTest>("() instance of schema-element ( test )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("schema-element(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmElementNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (202) ElementDeclaration")
internal inner class ElementDeclaration {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
() instance of schema-element(test)
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultElement))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Element))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.3.4) Attribute Test ; XQuery 3.1 (2.5.5.5) Attribute Test")
internal inner class AttributeTest {
@Nested
@DisplayName("XQuery 3.1 EBNF (195) AttributeTest")
internal inner class AttributeTest {
@Test
@DisplayName("any; empty")
fun anyEmpty() {
val test = parse<XPathAttributeTest>("() instance of attribute ( (::) )")[0]
assertThat(test.nodeName, `is`(nullValue()))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("attribute()"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("any; wildcard")
fun anyWildcard() {
val test = parse<XPathAttributeTest>("() instance of attribute ( * )")[0]
assertThat(test.nodeName, `is`(nullValue()))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("attribute()"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("name only")
fun nameOnly() {
val test = parse<XPathAttributeTest>("() instance of attribute ( test )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("attribute(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("type only")
fun typeOnly() {
val test = parse<XPathAttributeTest>("() instance of attribute ( * , attr-type )")[0]
assertThat(test.nodeName, `is`(nullValue()))
val nodeType = test.nodeType!!
assertThat(nodeType.typeName, `is`("attr-type"))
assertThat(nodeType.itemType?.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(nodeType.lowerBound, `is`(1))
assertThat(nodeType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("attribute(*,attr-type)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("name and type")
fun nameAndType() {
val test = parse<XPathAttributeTest>("() instance of attribute ( test , attr-type )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
val nodeType = test.nodeType!!
assertThat(nodeType.typeName, `is`("attr-type"))
assertThat(nodeType.itemType?.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(nodeType.lowerBound, `is`(1))
assertThat(nodeType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("attribute(test,attr-type)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("invalid TypeName")
fun invalidTypeName() {
val test = parse<XPathAttributeTest>("() instance of attribute ( test , xs: )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("attribute(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Test
@DisplayName("XQuery 4.0 ED EBNF (109) AttributeTest ; XQuery 4.0 ED EBNF (55) NameTest")
fun attributeTest_nameTest() {
val test = parse<XPathAttributeTest>("() instance of attribute ( *:test )")[0]
assertThat(qname_presentation(test.nodeName!!), `is`("*:test"))
assertThat(test.nodeType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("attribute(*:test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (203) AttributeName")
internal inner class AttributeName {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>("() instance of attribute(test)")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Attribute))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.3.5) Schema Attribute Test ; XQuery 3.1 (2.5.5.6) Schema Attribute Test")
internal inner class SchemaAttributeTest {
@Nested
@DisplayName("XQuery 3.1 EBNF (197) SchemaAttributeTest")
internal inner class SchemaAttributeTest {
@Test
@DisplayName("missing attribute declaration")
fun missingAttributeDeclaration() {
val test = parse<XPathSchemaAttributeTest>("() instance of schema-attribute ( (::) )")[0]
assertThat(test.nodeName, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("schema-attribute(<unknown>)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("attribute declaration")
fun attributeDeclaration() {
val test = parse<XPathSchemaAttributeTest>("() instance of schema-attribute ( test )")[0]
assertThat(test.nodeName?.localName!!.data, `is`("test"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("schema-attribute(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmAttributeNode::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (198) AttributeDeclaration")
internal inner class AttributeDeclaration {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>("() instance of schema-attribute(test)")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Attribute))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.4.1) Element Test ; XQuery 3.1 (2.5.5.7) Function Test")
internal inner class FunctionTest {
@Nested
@DisplayName("XQuery 3.1 EBNF (207) FunctionTest")
internal inner class FunctionTest {
@Test
@DisplayName("one annotation ; any function test")
fun oneAnnotation() {
val test = parse<XPathAnyFunctionTest>("() instance of % test function ( * )")[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(1))
assertThat(qname_presentation(annotations[0].name!!), `is`("test"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("%test function(*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmFunction::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("multiple annotations ; typed function test")
fun multipleAnnotations() {
val test = parse<XPathTypedFunctionTest>(
"() instance of % one % two function ( xs:long ) as xs:long"
)[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(2))
assertThat(qname_presentation(annotations[0].name!!), `is`("one"))
assertThat(qname_presentation(annotations[1].name!!), `is`("two"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("%one %two function(xs:long) as xs:long"))
assertThat(type.typeClass, `is`(sameInstance(XdmFunction::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("annotation with missing name")
fun annotationWithoutName() {
val test = parse<XPathTypedFunctionTest>("() instance of % % two function ( xs:long ) as xs:long")[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(2))
assertThat(annotations[0].name, `is`(nullValue()))
assertThat(qname_presentation(annotations[1].name!!), `is`("two"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("%two function(xs:long) as xs:long"))
assertThat(type.typeClass, `is`(sameInstance(XdmFunction::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Test
@DisplayName("XQuery 3.1 EBNF (208) AnyFunctionTest")
fun anyFunctionTest() {
val test = parse<XPathAnyFunctionTest>("() instance of function ( * )")[0]
assertThat(test.annotations.count(), `is`(0))
val type = test as XdmItemType
assertThat(type.typeName, `is`("function(*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmFunction::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (209) TypedFunctionTest")
internal inner class TypedFunctionTest {
@Test
@DisplayName("no parameters")
fun noParameters() {
val test = parse<XPathTypedFunctionTest>(
"() instance of function ( ) as empty-sequence ( (::) )"
)[0]
assertThat(test.returnType?.typeName, `is`("empty-sequence()"))
assertThat(test.annotations.count(), `is`(0))
val paramTypes = test.paramTypes.toList()
assertThat(paramTypes.size, `is`(0))
val type = test as XdmItemType
assertThat(type.typeName, `is`("function() as empty-sequence()"))
assertThat(type.typeClass, `is`(sameInstance(XdmFunction::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("one parameter")
fun oneParameter() {
val test = parse<XPathTypedFunctionTest>("() instance of function ( xs:float ) as xs:integer")[0]
assertThat(test.returnType?.typeName, `is`("xs:integer"))
assertThat(test.annotations.count(), `is`(0))
val paramTypes = test.paramTypes.toList()
assertThat(paramTypes.size, `is`(1))
assertThat(paramTypes[0].typeName, `is`("xs:float"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("function(xs:float) as xs:integer"))
assertThat(type.typeClass, `is`(sameInstance(XdmFunction::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("multiple parameters")
fun multipleParameters() {
val test = parse<XPathTypedFunctionTest>(
"() instance of function ( xs:long , array ( * ) ) as xs:double +"
)[0]
assertThat(test.returnType?.typeName, `is`("xs:double+"))
assertThat(test.annotations.count(), `is`(0))
val paramTypes = test.paramTypes.toList()
assertThat(paramTypes.size, `is`(2))
assertThat(paramTypes[0].typeName, `is`("xs:long"))
assertThat(paramTypes[1].typeName, `is`("array(*)"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("function(xs:long, array(*)) as xs:double+"))
assertThat(type.typeClass, `is`(sameInstance(XdmFunction::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("missing return type")
fun missingReturnType() {
val test = parse<XPathTypedFunctionTest>("() instance of function ( map ( * ) )")[0]
assertThat(test.returnType, `is`(nullValue()))
assertThat(test.annotations.count(), `is`(0))
val paramTypes = test.paramTypes.toList()
assertThat(paramTypes.size, `is`(1))
assertThat(paramTypes[0].typeName, `is`("map(*)"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("function(map(*)) as item()*"))
assertThat(type.typeClass, `is`(sameInstance(XdmFunction::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.4.2) Map Test ; XQuery 3.1 (2.5.5.8) Map Test")
internal inner class MapTest {
@Test
@DisplayName("XQuery 3.1 EBNF (211) AnyMapTest")
fun anyMapTest() {
val type = parse<XPathAnyMapTest>("() instance of map ( * )")[0] as XdmItemType
assertThat(type.typeName, `is`("map(*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (212) TypedMapTest")
internal inner class TypedMapTest {
@Test
@DisplayName("key and value type")
fun keyAndValueType() {
val test = parse<XPathTypedMapTest>("() instance of map ( xs:string , xs:int )")[0]
assertThat(test.keyType?.typeName, `is`("xs:string"))
assertThat(test.valueType?.typeName, `is`("xs:int"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("map(xs:string, xs:int)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("missing key type")
fun missingKeyType() {
val test = parse<XPathTypedMapTest>("() instance of map ( , xs:int )")[0]
assertThat(test.keyType, `is`(nullValue()))
assertThat(test.valueType?.typeName, `is`("xs:int"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("map(xs:anyAtomicType, xs:int)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("missing value type")
fun missingValueType() {
val test = parse<XPathTypedMapTest>("() instance of map ( xs:string , )")[0]
assertThat(test.keyType?.typeName, `is`("xs:string"))
assertThat(test.valueType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("map(xs:string, item()*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("missing key and value type")
fun missingKeyAndValueType() {
val test = parse<XPathTypedMapTest>("() instance of map ( , )")[0]
assertThat(test.keyType, `is`(nullValue()))
assertThat(test.valueType, `is`(nullValue()))
val type = test as XdmItemType
assertThat(type.typeName, `is`("map(*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (227) TypedMapTest ; XQuery 4.0 ED EBNF (233) LocalUnionType")
internal inner class TypedMapTest_LocalUnionType {
@Test
@DisplayName("union key type")
fun unionKeyType() {
val test = parse<XPathTypedMapTest>("() instance of map ( union ( xs:string , xs:float ) , xs:int )")[0]
assertThat(test.keyType?.typeName, `is`("union(xs:string, xs:float)"))
assertThat(test.valueType?.typeName, `is`("xs:int"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("map(union(xs:string, xs:float), xs:int)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.4.3) Record Test")
internal inner class RecordTest {
@Nested
@DisplayName("XQuery 4.0 ED EBNF (230) RecordTest")
internal inner class RecordTest {
@Test
@DisplayName("empty")
fun empty() {
val test = parse<XPathRecordTest>("() instance of record ( (::) )")[0]
assertThat(test.fields.count(), `is`(0))
assertThat(test.isExtensible, `is`(true))
val type = test as XdmItemType
assertThat(type.typeName, `is`("map(*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("one field")
fun one() {
val test = parse<XPathRecordTest>("() instance of record ( test )")[0]
assertThat(test.fields.count(), `is`(1))
assertThat(test.isExtensible, `is`(false))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("multiple fields")
fun multiple() {
val test = parse<XPathRecordTest>("() instance of record ( x as xs:float , y as xs:float )")[0]
assertThat(test.fields.count(), `is`(2))
assertThat(test.isExtensible, `is`(false))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(x as xs:float, y as xs:float)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("empty; extensible")
fun emptyExtensible() {
val test = parse<XPathRecordTest>("() instance of record ( * )")[0]
assertThat(test.fields.count(), `is`(0))
assertThat(test.isExtensible, `is`(true))
val type = test as XdmItemType
assertThat(type.typeName, `is`("map(*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("multiple fields; extensible")
fun multipleExtensible() {
val test = parse<XPathRecordTest>("() instance of record ( x as xs:float , y as xs:float , * )")[0]
assertThat(test.fields.count(), `is`(2))
assertThat(test.isExtensible, `is`(true))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(x as xs:float, y as xs:float, *)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (231) FieldDeclaration")
internal inner class FieldDeclaration {
@Test
@DisplayName("required; unspecified type")
fun nameOnlyRequired() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldType, `is`(nullValue()))
assertThat(field.fieldSeparator, `is`(nullValue()))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional; unspecified type")
fun nameOnlyOptional() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test ? )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldType, `is`(nullValue()))
assertThat(field.fieldSeparator, `is`(nullValue()))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test?)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("StringLiteral name; no space in name")
fun stringLiteralName_noSpace() {
val field = parse<XPathFieldDeclaration>("() instance of record ( 'test' )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldType, `is`(nullValue()))
assertThat(field.fieldSeparator, `is`(nullValue()))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("StringLiteral name; space in name")
fun stringLiteralName_withSpace() {
val field = parse<XPathFieldDeclaration>("() instance of record ( 'test key name' )")[0]
assertThat(field.fieldName.data, `is`("test key name"))
assertThat(field.fieldType, `is`(nullValue()))
assertThat(field.fieldSeparator, `is`(nullValue()))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(\"test key name\")"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (231) FieldDeclaration ; XQuery 4.0 ED EBNF (202) SequenceType")
internal inner class FieldDeclaration_SequenceType {
@Test
@DisplayName("required field")
fun requiredField() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test as xs:string )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldType?.typeName, `is`("xs:string"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test as xs:string)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field")
fun optionalField() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test ? as xs:string )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldType?.typeName, `is`("xs:string"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as xs:string)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("required field; colon type separator")
fun requiredField_colon() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test : xs:string )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldType?.typeName, `is`("xs:string"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.Colon))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test as xs:string)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field; colon type separator")
fun optionalField_colon() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test ? : xs:string )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldType?.typeName, `is`("xs:string"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.Colon))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as xs:string)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field; colon type separator; compact whitespace")
fun optionalField_colon_compactWhitepace() {
val field = parse<XPathFieldDeclaration>("() instance of record(test?:xs:string)")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldType?.typeName, `is`("xs:string"))
assertThat(field.fieldSeparator, `is`(XPathTokenType.ELVIS))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as xs:string)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (231) FieldDeclaration ; XQuery 4.0 ED EBNF (233) SelfReference")
internal inner class FieldDeclaration_SelfReference {
@Test
@DisplayName("required field; item type (T)")
fun requiredField_itemType() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test as .. )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`(".."))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(1))
assertThat(fieldType.upperBound, `is`(1))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test as ..)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("required field; optional item type (T?)")
fun requiredField_optionalItemType() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test as .. ? )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`("..?"))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(0))
assertThat(fieldType.upperBound, `is`(1))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test as ..?)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("required field; sequence type (T*)")
fun requiredField_sequenceType() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test as .. * )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`("..*"))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(0))
assertThat(fieldType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test as ..*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("required field; required sequence type (T+)")
fun requiredField_requiredSequenceType() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test as .. + )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`("..+"))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(1))
assertThat(fieldType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test as ..+)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field; item type (T)")
fun optionalField_itemType() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test ? as .. )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`(".."))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(1))
assertThat(fieldType.upperBound, `is`(1))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as ..)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field; optional item type (T?)")
fun optionalField_optionalItemType() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test ? as .. ? )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`("..?"))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(0))
assertThat(fieldType.upperBound, `is`(1))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as ..?)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field; sequence type (T*)")
fun optionalField_sequenceType() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test ? as .. * )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`("..*"))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(0))
assertThat(fieldType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as ..*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field; required sequence type (T+)")
fun optionalField_requiredSequenceType() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test ? as .. + )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.KAs))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`("..+"))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(1))
assertThat(fieldType.upperBound, `is`(Int.MAX_VALUE))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as ..+)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("required field; colon type separator")
fun requiredField_colon() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test : .. )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.Colon))
assertThat(field.isOptional, `is`(false))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`(".."))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(1))
assertThat(fieldType.upperBound, `is`(1))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test as ..)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field; colon type separator")
fun optionalField_colon() {
val field = parse<XPathFieldDeclaration>("() instance of record ( test ? : .. )")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenProvider.Colon))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`(".."))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(1))
assertThat(fieldType.upperBound, `is`(1))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as ..)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("optional field; colon type separator; compact whitespace")
fun optionalField_colon_compactWhitespace() {
val field = parse<XPathFieldDeclaration>("() instance of record(test?:..)")[0]
assertThat(field.fieldName.data, `is`("test"))
assertThat(field.fieldSeparator, `is`(XPathTokenType.ELVIS))
assertThat(field.isOptional, `is`(true))
val test = field.parent as XPathRecordTest
assertThat(test.fields.first(), `is`(sameInstance(field)))
val fieldType = field.fieldType as XdmSequenceType
assertThat(fieldType.typeName, `is`(".."))
assertThat(fieldType.itemType, `is`(sameInstance(test)))
assertThat(fieldType.lowerBound, `is`(1))
assertThat(fieldType.upperBound, `is`(1))
val type = test as XdmItemType
assertThat(type.typeName, `is`("record(test? as ..)"))
assertThat(type.typeClass, `is`(sameInstance(XdmMap::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (3.6.4.4) Element Test ; XQuery 3.1 (2.5.5.9) Array Test")
internal inner class ArrayTest {
@Nested
@DisplayName("XQuery 3.1 EBNF (214) AnyArrayTest")
internal inner class AnyArrayTest {
@Test
@DisplayName("any array test")
fun anyArrayTest() {
val type = parse<XPathAnyArrayTest>("() instance of array ( * )")[0] as XdmItemType
assertThat(type.typeName, `is`("array(*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmArray::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
@Test
@DisplayName("missing star or sequence type")
fun missingStarOrSequenceType() {
val type = parse<XPathAnyArrayTest>("() instance of array ( )")[0] as XdmItemType
assertThat(type.typeName, `is`("array(*)"))
assertThat(type.typeClass, `is`(sameInstance(XdmArray::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
@Test
@DisplayName("XQuery 3.1 EBNF (215) TypedArrayTest")
fun typedArrayTest() {
val test = parse<XPathTypedArrayTest>("() instance of array ( node ( ) )")[0]
assertThat(test.memberType.typeName, `is`("node()"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("array(node())"))
assertThat(type.typeClass, `is`(sameInstance(XdmArray::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4) Expressions ; XQuery 3.1 (3) Expressions")
internal inner class Expressions {
@Nested
@DisplayName("XQuery 4.0 ED (4.1) Setting Namespace Context")
internal inner class SettingNamespaceContext {
@Nested
@DisplayName("XQuery 4.0 ED EBNF (43) WithExpr")
internal inner class WithExpr {
@Test
@DisplayName("empty")
fun empty() {
val expr = parse<XPathWithExpr>("with xmlns=\"\" {}")[0] as XpmConcatenatingExpression
assertThat(expr.expressionElement, `is`(sameInstance(expr)))
val exprs = expr.expressions.toList()
assertThat(exprs.size, `is`(0))
}
@Test
@DisplayName("single")
fun single() {
val expr = parse<XPathWithExpr>("with xmlns=\"\" { 1 }")[0] as XpmConcatenatingExpression
assertThat(expr.expressionElement, `is`(sameInstance(expr)))
val exprs = expr.expressions.toList()
assertThat(exprs.size, `is`(1))
assertThat(exprs[0].text, `is`("1"))
}
@Test
@DisplayName("multiplw")
fun multiple() {
val expr = parse<XPathWithExpr>("with xmlns=\"\" { 1, 2 + 3, 4 }")[0] as XpmConcatenatingExpression
assertThat(expr.expressionElement, `is`(sameInstance(expr)))
val exprs = expr.expressions.toList()
assertThat(exprs.size, `is`(3))
assertThat(exprs[0].text, `is`("1"))
assertThat(exprs[1].text, `is`("2 + 3"))
assertThat(exprs[2].text, `is`("4"))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (44) NamespaceDeclaration")
internal inner class NamespaceDeclaration {
@Test
@DisplayName("namespace prefix")
fun namespacePrefix() {
val expr = parse<XPathNamespaceDeclaration>(
"with xmlns:b=\"http://www.example.com\" {}"
)[0] as XpmNamespaceDeclaration
assertThat(expr.namespacePrefix!!.data, `is`("b"))
val uri = expr.namespaceUri!!
assertThat(uri.data, `is`("http://www.example.com"))
assertThat(uri.context, `is`(XdmUriContext.NamespaceDeclaration))
assertThat(uri.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(uri.element, `is`(uri as PsiElement))
assertThat(expr.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.None), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(expr.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("default element/type namespace")
fun defaultElementTypeNamespace() {
val expr = parse<XPathNamespaceDeclaration>(
"with xmlns=\"http://www.example.com\" {}"
)[0] as XpmNamespaceDeclaration
assertThat(expr.namespacePrefix?.data, `is`(""))
val uri = expr.namespaceUri!!
assertThat(uri.data, `is`("http://www.example.com"))
assertThat(uri.context, `is`(XdmUriContext.NamespaceDeclaration))
assertThat(uri.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(uri.element, `is`(uri as PsiElement))
assertThat(expr.accepts(XdmNamespaceType.DefaultElement), `is`(true))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.None), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.Prefixed), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("other (invalid) QName")
fun otherQName() {
val expr = parse<XPathNamespaceDeclaration>(
"with b=\"http://www.example.com\" {}"
)[0] as XpmNamespaceDeclaration
assertThat(expr.namespacePrefix?.data, `is`(""))
val uri = expr.namespaceUri!!
assertThat(uri.data, `is`("http://www.example.com"))
assertThat(uri.context, `is`(XdmUriContext.NamespaceDeclaration))
assertThat(uri.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(uri.element, `is`(uri as PsiElement))
assertThat(expr.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.None), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.Prefixed), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.Undefined), `is`(true))
assertThat(expr.accepts(XdmNamespaceType.XQuery), `is`(false))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.3) Primary Expressions ; XQuery 3.1 (3.1) Primary Expressions")
internal inner class PrimaryExpressions {
@Nested
@DisplayName("XQuery 3.1 (3.1.1) Literals")
internal inner class Literals {
@Test
@DisplayName("XQuery 3.1 EBNF (219) IntegerLiteral")
fun integerLiteral() {
val literal = parse<XPathIntegerLiteral>("123")[0] as XsIntegerValue
assertThat(literal.data, `is`(BigInteger.valueOf(123)))
assertThat(literal.toInt(), `is`(123))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (220) DecimalLiteral")
fun decimalLiteral() {
val literal = parse<XPathDecimalLiteral>("12.34")[0] as XsDecimalValue
assertThat(literal.data, `is`(BigDecimal(BigInteger.valueOf(1234), 2)))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (221) DoubleLiteral")
fun doubleLiteral() {
val literal = parse<XPathDoubleLiteral>("1e3")[0] as XsDoubleValue
assertThat(literal.data, `is`(1e3))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (222) StringLiteral")
internal inner class StringLiteral {
@Test
@DisplayName("string literal content")
fun stringLiteral() {
val literal = parse<XPathStringLiteral>("\"Lorem ipsum.\uFFFF\"")[0] as XsStringValue
assertThat(literal.data, `is`("Lorem ipsum.\uFFFF")) // U+FFFF = BAD_CHARACTER token.
assertThat(literal.element, sameInstance(literal as PsiElement))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("unclosed string literal content")
fun unclosedStringLiteral() {
val literal = parse<XPathStringLiteral>("\"Lorem ipsum.")[0] as XsStringValue
assertThat(literal.data, `is`("Lorem ipsum."))
assertThat(literal.element, sameInstance(literal as PsiElement))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("EscapeApos tokens")
fun escapeApos() {
val literal = parse<XPathStringLiteral>("'''\"\"'")[0] as XsStringValue
assertThat(literal.data, `is`("'\"\""))
assertThat(literal.element, sameInstance(literal as PsiElement))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("EscapeQuot tokens")
fun escapeQuot() {
val literal = parse<XPathStringLiteral>("\"''\"\"\"")[0] as XsStringValue
assertThat(literal.data, `is`("''\""))
assertThat(literal.element, sameInstance(literal as PsiElement))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("PredefinedEntityRef tokens")
fun predefinedEntityRef() {
// entity reference types: XQuery, HTML4, HTML5, UTF-16 surrogate pair, multi-character entity, empty, partial
val literal = parse<XPathStringLiteral>(
"\"<áā𝔄≪̸&;>\""
)[0] as XsStringValue
assertThat(literal.data, `is`("<áā\uD835\uDD04≪\u0338"))
assertThat(literal.element, sameInstance(literal as PsiElement))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("CharRef tokens")
fun charRef() {
val literal = parse<XPathStringLiteral>("\"   𝔠\"")[0] as XsStringValue
assertThat(literal.data, `is`("\u00A0\u00A0\u0020\uD835\uDD20"))
assertThat(literal.element, sameInstance(literal as PsiElement))
val expr = literal as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.1.2) Variable References")
internal inner class VariableReferences {
@Nested
@DisplayName("XQuery 3.1 EBNF (131) VarRef")
internal inner class VarRef {
@Test
@DisplayName("NCName")
fun ncname() {
val ref = parse<XPathVarRef>("let \$x := 2 return \$y")[0] as XpmVariableReference
val qname = ref.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("y"))
val expr = ref as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("QName")
fun qname() {
val ref = parse<XPathVarRef>("let \$a:x := 2 return \$a:y")[0] as XpmVariableReference
val qname = ref.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("y"))
val expr = ref as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val ref = parse<XPathVarRef>(
"let \$Q{http://www.example.com}x := 2 return \$Q{http://www.example.com}y"
)[0] as XpmVariableReference
val qname = ref.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("y"))
val expr = ref as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.1.3) Parenthesized Expressions")
internal inner class ParenthesizedExpressions {
@Test
@DisplayName("XQuery 3.1 EBNF (133) ParenthesizedExpr ; XQuery IntelliJ Plugin XQuery EBNF (134) EmptyExpr")
fun emptyExpr() {
val expr = parse<PluginEmptyExpr>("()")[0] as XpmConcatenatingExpression
assertThat(expr.expressionElement, `is`(nullValue()))
assertThat(expr.expressions.count(), `is`(0))
}
}
@Nested
@DisplayName("XQuery 3.1 (3.1.4) Context Item Expression")
internal inner class ContextItemExpression {
@Test
@DisplayName("XQuery 3.1 EBNF (134) ContextItemExpr")
fun contextItemExpr() {
val expr = parse<XPathContextItemExpr>("() ! .")[0] as XpmContextItemExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.4) Functions ; XQuery 3.1 (3.1) Primary Expressions")
internal inner class Functions {
@Nested
@DisplayName("XQuery 4.0 ED (4.4.1) Static Functions ; XQuery 3.1 (3.1.5) Static Function Calls")
internal inner class StaticFunctions {
@Nested
@DisplayName("%variadic(\"no\"); empty parameters")
internal inner class VariadicNo_EmptyParameters {
@Test
@DisplayName("XQuery 3.1 EBNF (32) FunctionDecl")
fun functionDecl() {
val decl = parse<XpmFunctionDeclaration>("declare function fn:true() external;")[0]
assertThat(decl.variadicType, `is`(XpmVariadic.No))
assertThat(decl.declaredArity, `is`(0))
assertThat(decl.requiredArity, `is`(0))
}
@Test
@DisplayName("XQuery 3.1 EBNF (169) InlineFunctionExpr")
fun inlineFunctionExpr() {
val decl = parse<XpmFunctionDeclaration>("function () {}")[0]
assertThat(decl.variadicType, `is`(XpmVariadic.No))
assertThat(decl.declaredArity, `is`(0))
assertThat(decl.requiredArity, `is`(0))
}
}
@Nested
@DisplayName("%variadic(\"no\"); multiple parameters")
internal inner class VariadicNo_MultipleParameters {
@Test
@DisplayName("XQuery 3.1 EBNF (32) FunctionDecl")
fun functionDecl() {
val decl = parse<XpmFunctionDeclaration>("declare function test(\$one, \$two) external;")[0]
assertThat(decl.variadicType, `is`(XpmVariadic.No))
assertThat(decl.declaredArity, `is`(2))
assertThat(decl.requiredArity, `is`(2))
}
@Test
@DisplayName("XQuery 3.1 EBNF (169) InlineFunctionExpr")
fun inlineFunctionExpr() {
val decl = parse<XpmFunctionDeclaration>("function (\$one, \$two) {}")[0]
assertThat(decl.variadicType, `is`(XpmVariadic.No))
assertThat(decl.declaredArity, `is`(2))
assertThat(decl.requiredArity, `is`(2))
}
}
@Nested
@DisplayName("%variadic(\"sequence\"); ellipsis")
internal inner class VariadicSequence_Ellipsis {
@Test
@DisplayName("XQuery 3.1 EBNF (32) FunctionDecl")
fun functionDecl() {
val decl = parse<XpmFunctionDeclaration>("declare function test(\$one, \$two ...) external;")[0]
assertThat(decl.variadicType, `is`(XpmVariadic.Ellipsis))
assertThat(decl.declaredArity, `is`(2))
assertThat(decl.requiredArity, `is`(1))
}
@Test
@DisplayName("XQuery 3.1 EBNF (169) InlineFunctionExpr")
fun inlineFunctionExpr() {
val decl = parse<XpmFunctionDeclaration>("function (\$one, \$two ...) {}")[0]
assertThat(decl.variadicType, `is`(XpmVariadic.Ellipsis))
assertThat(decl.declaredArity, `is`(2))
assertThat(decl.requiredArity, `is`(1))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.4.1.1) Static Function Call Syntax ; XQuery 3.1 (3.1.5) Static Function Calls")
internal inner class StaticFunctionCallSyntax {
@Nested
@DisplayName("XQuery 4.0 ED EBNF (137) KeywordArgument")
internal inner class KeywordArgument {
@Test
@DisplayName("ncname")
fun ncname() {
val f = parse<XPathKeywordArgument>("fn:matches(input: \"test\", pattern: \".*\")")[0]
assertThat((f.keyExpression as XsNCNameValue).data, `is`("input"))
assertThat((f.valueExpression as XPathStringLiteral).data, `is`("test"))
assertThat(f.keyName, `is`("input"))
}
@Test
@DisplayName("missing value")
fun missingValue() {
val f = parse<XPathKeywordArgument>("fn:matches(input: , \".*\")")[0]
assertThat((f.keyExpression as XsNCNameValue).data, `is`("input"))
assertThat(f.valueExpression, `is`(nullValue()))
assertThat(f.keyName, `is`("input"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (137) FunctionCall")
internal inner class FunctionCall {
@Test
@DisplayName("positional arguments")
fun positionalArguments() {
val f = parse<XPathFunctionCall>("math:pow(2, 8)")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(2))
assertThat(ref.keywordArity, `is`(0))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("math"))
assertThat(qname.localName!!.data, `is`("pow"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(2))
assertThat(f.keywordArguments.size, `is`(0))
assertThat(f.positionalArguments[0].text, `is`("2"))
assertThat(f.positionalArguments[1].text, `is`("8"))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("positional and keyword arguments")
fun positionalAndKeywordArguments() {
val f = parse<XPathFunctionCall>("math:pow(2, y: 8)")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(1))
assertThat(ref.keywordArity, `is`(1))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("math"))
assertThat(qname.localName!!.data, `is`("pow"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(1))
assertThat(f.positionalArguments[0].text, `is`("2"))
assertThat(f.keywordArguments.size, `is`(1))
assertThat(f.keywordArguments[0].keyName, `is`("y"))
assertThat(f.keywordArguments[0].valueExpression?.text, `is`("8"))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("keyword arguments")
fun keywordArguments() {
val f = parse<XPathFunctionCall>("math:pow(x: 2, y: 8)")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(0))
assertThat(ref.keywordArity, `is`(2))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("math"))
assertThat(qname.localName!!.data, `is`("pow"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(0))
assertThat(f.keywordArguments.size, `is`(2))
assertThat(f.keywordArguments[0].keyName, `is`("x"))
assertThat(f.keywordArguments[1].keyName, `is`("y"))
assertThat(f.keywordArguments[0].valueExpression?.text, `is`("2"))
assertThat(f.keywordArguments[1].valueExpression?.text, `is`("8"))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("empty arguments")
fun emptyArguments() {
val f = parse<XPathFunctionCall>("fn:true()")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(0))
assertThat(ref.keywordArity, `is`(0))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(0))
assertThat(f.keywordArguments.size, `is`(0))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("partial function application")
fun partialFunctionApplication() {
val f = parse<XPathFunctionCall>("math:sin(?)")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(1))
assertThat(ref.keywordArity, `is`(0))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("math"))
assertThat(qname.localName!!.data, `is`("sin"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(1))
assertThat(f.keywordArguments.size, `is`(0))
assertThat(f.positionalArguments[0].text, `is`("?"))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARGUMENT_LIST))
assertThat(expr.expressionElement?.textOffset, `is`(8))
}
@Test
@DisplayName("invalid EQName")
fun invalidEQName() {
val f = parse<XPathFunctionCall>(":true(1)")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(1))
assertThat(ref.keywordArity, `is`(0))
assertThat(ref.functionName, `is`(nullValue()))
assertThat(f.positionalArguments.size, `is`(1))
assertThat(f.positionalArguments[0].text, `is`("1"))
assertThat(f.keywordArguments.size, `is`(0))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
test()
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultFunctionRef))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.FunctionRef))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/function"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("reference rename")
fun referenceRename() {
val expr = parse<XPathFunctionCall>("test()")[0] as XpmFunctionReference
val ref = (expr.functionName as PsiElement).reference!!
assertThat(ref, `is`(instanceOf(XPathFunctionNameReference::class.java)))
DebugUtil.performPsiModification<Throwable>("rename") {
val renamed = ref.handleElementRename("lorem-ipsum")
assertThat(renamed, `is`(instanceOf(XPathNCName::class.java)))
assertThat(renamed.text, `is`("lorem-ipsum"))
assertThat((renamed as PsiNameIdentifierOwner).name, `is`("lorem-ipsum"))
}
assertThat((expr.functionName as PsiElement).text, `is`("lorem-ipsum"))
}
}
@Test
@DisplayName("XQuery 3.1 EBNF (139) ArgumentPlaceholder")
fun argumentPlaceholder() {
val arg = parse<XPathArgumentPlaceholder>("math:sin(?)")[0] as XpmExpression
assertThat(arg.expressionElement?.elementType, `is`(XPathTokenProvider.QuestionMark))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.4.1.2) Evaluating Static Function Calls ; XQuery 3.1 (3.1.5.1) Evaluating Static and Dynamic Function Calls")
internal inner class EvaluatingStaticFunctionCalls {
@Nested
@DisplayName("For non-variadic functions")
internal inner class ForNonVariadicFunctions {
@Test
@DisplayName("positional arguments")
fun positionalArguments() {
val f = parse<XPathFunctionCall>("math:pow(2, 8)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("math:pow"))
assertThat(bindings.size, `is`(2))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("x"))
assertThat(arg.variableType?.typeName, `is`("xs:double?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("y"))
assertThat(arg.variableType?.typeName, `is`("xs:numeric"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[1]))
}
@Test
@DisplayName("positional and keyword arguments")
fun positionalAndKeywordArguments() {
val f = parse<XPathFunctionCall>("math:pow(2, y: 8)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("math:pow"))
assertThat(bindings.size, `is`(2))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("x"))
assertThat(arg.variableType?.typeName, `is`("xs:double?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("y"))
assertThat(arg.variableType?.typeName, `is`("xs:numeric"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[0].valueExpression))
}
@Test
@DisplayName("keyword arguments")
fun keywordArguments() {
val f = parse<XPathFunctionCall>("math:pow(y: 2, x: 8)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("math:pow"))
assertThat(bindings.size, `is`(2))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("x"))
assertThat(arg.variableType?.typeName, `is`("xs:double?"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[1].valueExpression))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("y"))
assertThat(arg.variableType?.typeName, `is`("xs:numeric"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[0].valueExpression))
}
@Test
@DisplayName("keyword argument not matching any parameter names")
fun keywordArgumentNotMatchingAnyParameterNames() {
val f = parse<XPathFunctionCall>("math:pow(y: 2, z: 8)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("math:pow"))
assertThat(bindings.size, `is`(2))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("x"))
assertThat(arg.variableType?.typeName, `is`("xs:double?"))
assertThat(arg.variableExpression, sameInstance(XpmMissingArgument))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("y"))
assertThat(arg.variableType?.typeName, `is`("xs:numeric"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[0].valueExpression))
}
@Test
@DisplayName("empty arguments")
fun emptyArguments() {
val f = parse<XPathFunctionCall>("fn:true()")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:true"))
assertThat(bindings.size, `is`(0))
}
}
@Nested
@DisplayName("For non-variadic arrow functions")
internal inner class ForNonVariadicArrowFunctions {
@Test
@DisplayName("positional arguments")
fun positionalArguments() {
val f = parse<PluginArrowFunctionCall>("\$x => format-date(1, 2, 3, 4)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:format-date"))
assertThat(bindings.size, `is`(5))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value"))
assertThat(arg.variableType?.typeName, `is`("xs:date?"))
assertThat(arg.variableExpression, sameInstance(f.sourceExpression))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("picture"))
assertThat(arg.variableType?.typeName, `is`("xs:string"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
arg = bindings[2]
assertThat(qname_presentation(arg.variableName!!), `is`("language"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[1]))
arg = bindings[3]
assertThat(qname_presentation(arg.variableName!!), `is`("calendar"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[2]))
arg = bindings[4]
assertThat(qname_presentation(arg.variableName!!), `is`("place"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[3]))
}
@Test
@DisplayName("positional and keyword arguments")
fun positionalAndKeywordArguments() {
val f = parse<PluginArrowFunctionCall>(
"\$x => format-date(1, 2, place: 3, calendar: 4)"
)[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:format-date"))
assertThat(bindings.size, `is`(5))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value"))
assertThat(arg.variableType?.typeName, `is`("xs:date?"))
assertThat(arg.variableExpression, sameInstance(f.sourceExpression))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("picture"))
assertThat(arg.variableType?.typeName, `is`("xs:string"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
arg = bindings[2]
assertThat(qname_presentation(arg.variableName!!), `is`("language"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[1]))
arg = bindings[3]
assertThat(qname_presentation(arg.variableName!!), `is`("calendar"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[1].valueExpression))
arg = bindings[4]
assertThat(qname_presentation(arg.variableName!!), `is`("place"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[0].valueExpression))
}
@Test
@DisplayName("keyword arguments")
fun keywordArguments() {
val f = parse<PluginArrowFunctionCall>(
"\$x => format-date(calendar: 1, language: 2, picture: 3, place: 4)"
)[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:format-date"))
assertThat(bindings.size, `is`(5))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value"))
assertThat(arg.variableType?.typeName, `is`("xs:date?"))
assertThat(arg.variableExpression, sameInstance(f.sourceExpression))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("picture"))
assertThat(arg.variableType?.typeName, `is`("xs:string"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[2].valueExpression))
arg = bindings[2]
assertThat(qname_presentation(arg.variableName!!), `is`("language"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[1].valueExpression))
arg = bindings[3]
assertThat(qname_presentation(arg.variableName!!), `is`("calendar"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[0].valueExpression))
arg = bindings[4]
assertThat(qname_presentation(arg.variableName!!), `is`("place"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[3].valueExpression))
}
@Test
@DisplayName("keyword argument not matching any parameter names")
fun keywordArgumentNotMatchingAnyParameterNames() {
val f = parse<PluginArrowFunctionCall>(
"\$x => format-date(calender: 1, language: 2, picture: 3, place: 4)"
)[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:format-date"))
assertThat(bindings.size, `is`(5))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value"))
assertThat(arg.variableType?.typeName, `is`("xs:date?"))
assertThat(arg.variableExpression, sameInstance(f.sourceExpression))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("picture"))
assertThat(arg.variableType?.typeName, `is`("xs:string"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[2].valueExpression))
arg = bindings[2]
assertThat(qname_presentation(arg.variableName!!), `is`("language"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[1].valueExpression))
arg = bindings[3]
assertThat(qname_presentation(arg.variableName!!), `is`("calendar"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(XpmMissingArgument))
arg = bindings[4]
assertThat(qname_presentation(arg.variableName!!), `is`("place"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.keywordArguments[3].valueExpression))
}
@Test
@DisplayName("empty arguments")
fun emptyArguments() {
val f = parse<PluginArrowFunctionCall>("\$x => upper-case()")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:upper-case"))
assertThat(bindings.size, `is`(1))
val arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.sourceExpression))
}
@Test
@DisplayName("chained arrows")
fun chainedArrows() {
val f = parse<PluginArrowFunctionCall>("\$x => upper-case() => string-to-codepoints()")[1]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:string-to-codepoints"))
assertThat(bindings.size, `is`(1))
val arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value"))
assertThat(arg.variableType?.typeName, `is`("xs:string?"))
assertThat(arg.variableExpression, sameInstance(f.sourceExpression))
}
}
@Nested
@DisplayName("For ellipsis-variadic functions")
internal inner class ForEllipsisVariadicFunctions {
@Test
@DisplayName("no arguments specified for the variadic parameter")
fun empty() {
val f = parse<XPathFunctionCall>("fn:concat(2, 4)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:concat"))
assertThat(bindings.size, `is`(3))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value1"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("value2"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[1]))
arg = bindings[2]
assertThat(qname_presentation(arg.variableName!!), `is`("values"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
assertThat(arg.variableExpression, sameInstance(XpmEmptyExpression))
}
@Test
@DisplayName("single argument specified for the variadic parameter")
fun single() {
val f = parse<XPathFunctionCall>("fn:concat(2, 4, 6)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:concat"))
assertThat(bindings.size, `is`(3))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value1"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("value2"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[1]))
arg = bindings[2]
assertThat(qname_presentation(arg.variableName!!), `is`("values"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[2]))
}
@Test
@DisplayName("multiple arguments specified for the variadic parameter")
fun multiple() {
val f = parse<XPathFunctionCall>("fn:concat(2, 4, 6, 8)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:concat"))
assertThat(bindings.size, `is`(3))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value1"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("value2"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[1]))
arg = bindings[2]
assertThat(qname_presentation(arg.variableName!!), `is`("values"))
assertThat(arg.variableType?.typeName, `is`("xs:anyAtomicType?"))
val rest = (arg.variableExpression as XpmConcatenatingExpression).expressions.toList()
assertThat(rest.size, `is`(2))
assertThat(rest[0], sameInstance(f.positionalArguments[2]))
assertThat(rest[1], sameInstance(f.positionalArguments[3]))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.4.2.1) Evaluating Dynamic Function Calls ; XQuery 3.1 (3.1.5.1) Evaluating Static and Dynamic Function Calls")
internal inner class EvaluatingDynamicFunctionCalls {
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (129) DynamicFunctionCall")
internal inner class DynamicFunctionCall {
@Test
@DisplayName("positional arguments")
fun positionalArguments() {
val f = parse<PluginDynamicFunctionCall>("math:pow#2(2, 8)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("math:pow"))
assertThat(bindings.size, `is`(2))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("x"))
assertThat(arg.variableType?.typeName, `is`("xs:double?"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("y"))
assertThat(arg.variableType?.typeName, `is`("xs:numeric"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[1]))
}
@Test
@DisplayName("empty arguments")
fun emptyArguments() {
val f = parse<PluginDynamicFunctionCall>("fn:true#0()")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:true"))
assertThat(bindings.size, `is`(0))
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (119) ArrowDynamicFunctionCall")
internal inner class ArrowDynamicFunctionCall {
@Test
@DisplayName("positional arguments")
fun positionalArguments() {
val f = parse<PluginArrowDynamicFunctionCall>("2 => (math:pow#2)(8)")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("math:pow"))
assertThat(bindings.size, `is`(2))
var arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("x"))
assertThat(arg.variableType?.typeName, `is`("xs:double?"))
assertThat(arg.variableExpression, sameInstance(f.sourceExpression))
arg = bindings[1]
assertThat(qname_presentation(arg.variableName!!), `is`("y"))
assertThat(arg.variableType?.typeName, `is`("xs:numeric"))
assertThat(arg.variableExpression, sameInstance(f.positionalArguments[0]))
}
@Test
@DisplayName("empty arguments")
fun emptyArguments() {
val f = parse<PluginArrowDynamicFunctionCall>("2 => (fn:abs#1)()")[0]
val (decl, bindings) = f.resolve!!
assertThat(qname_presentation(decl.functionName!!), `is`("fn:abs"))
assertThat(bindings.size, `is`(1))
val arg = bindings[0]
assertThat(qname_presentation(arg.variableName!!), `is`("value"))
assertThat(arg.variableType?.typeName, `is`("xs:numeric?"))
assertThat(arg.variableExpression, sameInstance(f.sourceExpression))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.4.2.3) Named Function References ; XQuery 3.1 (3.1.6) Named Function References")
internal inner class NamedFunctionReferences {
@Nested
@DisplayName("XQuery 3.1 EBNF (168) NamedFunctionRef")
internal inner class NamedFunctionRef {
@Test
@DisplayName("named function reference")
fun namedFunctionRef() {
val f = parse<XPathNamedFunctionRef>("true#3")[0] as XpmFunctionReference
assertThat(f.positionalArity, `is`(3))
assertThat(f.keywordArity, `is`(0))
val qname = f.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.NAMED_FUNCTION_REF))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("missing arity")
fun missingArity() {
val f = parse<XPathNamedFunctionRef>("true#")[0] as XpmFunctionReference
assertThat(f.positionalArity, `is`(0))
assertThat(f.keywordArity, `is`(0))
val qname = f.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.NAMED_FUNCTION_REF))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("invalid EQName")
fun invalidEQName() {
val f = parse<XPathNamedFunctionRef>(":true#0")[0] as XpmFunctionReference
assertThat(f.positionalArity, `is`(0))
assertThat(f.keywordArity, `is`(0))
assertThat(f.functionName, `is`(nullValue()))
val expr = f as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.NAMED_FUNCTION_REF))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
test#1
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultFunctionRef))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.FunctionRef))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/function"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("reference rename")
fun referenceRename() {
val expr = parse<XPathNamedFunctionRef>("test#1")[0] as XpmFunctionReference
val ref = (expr.functionName as PsiElement).reference!!
assertThat(ref, `is`(instanceOf(XPathFunctionNameReference::class.java)))
DebugUtil.performPsiModification<Throwable>("rename") {
val renamed = ref.handleElementRename("lorem-ipsum")
assertThat(renamed, `is`(instanceOf(XPathNCName::class.java)))
assertThat(renamed.text, `is`("lorem-ipsum"))
assertThat((renamed as PsiNameIdentifierOwner).name, `is`("lorem-ipsum"))
}
assertThat((expr.functionName as PsiElement).text, `is`("lorem-ipsum"))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.4.2.3) Inline Function Expressions ; XQuery 3.1 (3.1.7) Inline Function Expressions")
internal inner class InlineFunctionExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (169) InlineFunctionExpr")
internal inner class InlineFunctionExpr {
@Test
@DisplayName("empty ParamList")
fun emptyParamList() {
val decl = parse<XpmFunctionDeclaration>("function () {}")[0]
assertThat(decl.functionName, `is`(nullValue()))
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody, sameInstance(XpmEmptyExpression))
val expr = decl as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("non-empty ParamList")
fun nonEmptyParamList() {
val decl = parse<XpmFunctionDeclaration>("function (\$one, \$two) {}")[0]
assertThat(decl.functionName, `is`(nullValue()))
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.functionBody, sameInstance(XpmEmptyExpression))
assertThat(decl.parameters.size, `is`(2))
assertThat(qname_presentation(decl.parameters[0].variableName!!), `is`("one"))
assertThat(qname_presentation(decl.parameters[1].variableName!!), `is`("two"))
val expr = decl as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("non-empty ParamList with types")
fun nonEmptyParamListWithTypes() {
val decl = parse<XpmFunctionDeclaration>(
"function (\$one as array ( * ), \$two as node((::))) {}"
)[0]
assertThat(decl.functionName, `is`(nullValue()))
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.functionBody, sameInstance(XpmEmptyExpression))
assertThat(decl.parameters.size, `is`(2))
assertThat(qname_presentation(decl.parameters[0].variableName!!), `is`("one"))
assertThat(qname_presentation(decl.parameters[1].variableName!!), `is`("two"))
val expr = decl as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("return type")
fun returnType() {
val decl = parse<XpmFunctionDeclaration>("function () as xs:boolean {}")[0]
assertThat(decl.functionName, `is`(nullValue()))
assertThat(decl.returnType?.typeName, `is`("xs:boolean"))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody, sameInstance(XpmEmptyExpression))
val expr = decl as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("function body expression")
fun functionBodyExpression() {
val decl = parse<XpmFunctionDeclaration>("function () { 2 + 3 }")[0]
assertThat(decl.functionName, `is`(nullValue()))
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody?.text, `is`("2 + 3 "))
val expr = decl as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.5) Postfix Expressions ; XQuery 3.1 (3.2) Postfix Expressions")
internal inner class PostfixExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (121) PostfixExpr")
internal inner class PostfixExpr {
@Test
@DisplayName("initial step")
fun initialStep() {
val step = parse<XPathPostfixExpr>("\$x/test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
val expr = step as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("intermediate step")
fun intermediateStep() {
val step = parse<XPathPostfixExpr>("/test/./self::node()")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
val expr = step as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("final step")
fun finalStep() {
val step = parse<XPathPostfixExpr>("/test/string()")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
val expr = step as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
@Nested
@DisplayName("XQuery 3.1 (3.2.1) Filter Expressions")
internal inner class FilterExpressions {
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (128) FilterExpr")
internal inner class FilterExpr {
@Test
@DisplayName("single predicate; null PrimaryExpr expressionElement")
fun singlePredicate_nullExpressionElement() {
val step = parse<XPathPostfixExpr>("\$x[1]")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.ONE))
val expr = step as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.VAR_REF))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("single predicate; non-null PrimaryExpr expressionElement")
fun singlePredicate_nonNullExpressionElement() {
val step = parse<XPathPostfixExpr>("map { \"one\": 1 }[1]")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.ONE))
val expr = step as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.MAP_CONSTRUCTOR_ENTRY))
assertThat(expr.expressionElement?.textOffset, `is`(6))
}
@Test
@DisplayName("multiple predicates; inner")
fun multiplePredicatesInner() {
val step = parse<XPathPostfixExpr>("\$x[1][2]")[1] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.ONE))
val expr = step as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.VAR_REF))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("multiple predicates; outer")
fun multiplePredicatesOuter() {
val step = parse<XPathPostfixExpr>("\$x[1][2]")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.valueOf(2)))
val expr = step as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.VAR_REF))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.2.2) Dynamic Function Calls")
internal inner class DynamicFunctionCalls {
@Test
@DisplayName("path step")
fun pathStep() {
val step = parse<XPathPostfixExpr>("\$x(1)")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
val expr = step as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.POSITIONAL_ARGUMENT_LIST))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("XQuery 3.1 EBNF (168) NamedFunctionRef")
fun namedFunctionRef() {
val f = parse<PluginDynamicFunctionCall>("fn:abs#1(1)")[0]
assertThat(f.positionalArguments.size, `is`(1))
assertThat(f.positionalArguments[0].text, `is`("1"))
val ref = f.functionReference
assertThat(qname_presentation(ref?.functionName!!), `is`("fn:abs"))
assertThat(ref.positionalArity, `is`(1))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (133) ParenthesizedExpr ; XQuery 3.1 EBNF (168) NamedFunctionRef")
internal inner class ParenthesizedExprWithNamedFunctionRef {
@Test
@DisplayName("single")
fun single() {
val f = parse<PluginDynamicFunctionCall>("(fn:abs#1)(1)")[0] as XpmFunctionCall
assertThat(f.positionalArguments.size, `is`(1))
assertThat(f.positionalArguments[0].text, `is`("1"))
val ref = f.functionReference
assertThat(qname_presentation(ref?.functionName!!), `is`("fn:abs"))
assertThat(ref.positionalArity, `is`(1))
}
@Test
@DisplayName("multiple")
fun multiple() {
val f = parse<PluginDynamicFunctionCall>("(fn:abs#1, fn:count#1)(1)")[0] as XpmFunctionCall
assertThat(f.functionReference, `is`(nullValue()))
assertThat(f.positionalArguments.size, `is`(1))
assertThat(f.positionalArguments[0].text, `is`("1"))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.6) Path Expressions ; XQuery 3.1 (3.3) Path Expressions")
internal inner class PathExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (108) PathExpr")
internal inner class PathExpr {
@Test
@DisplayName("last step is ForwardStep")
fun lastStepIsForwardStep() {
val expr = parse<XPathPathExpr>("/lorem/ipsum/parent::dolor")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.REVERSE_STEP))
assertThat(expr.expressionElement?.textOffset, `is`(13))
}
@Test
@DisplayName("last step is ReverseStep")
fun lastStepIsReverseStep() {
val expr = parse<XPathPathExpr>("/lorem/ipsum/parent::dolor")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.REVERSE_STEP))
assertThat(expr.expressionElement?.textOffset, `is`(13))
}
@Test
@DisplayName("last step is FilterStep")
fun lastStepIsFilterStep() {
val expr = parse<XPathPathExpr>("/lorem/ipsum/dolor[1]")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.FILTER_STEP))
assertThat(expr.expressionElement?.textOffset, `is`(13))
}
@Test
@DisplayName("last step is PrimaryExpr")
fun lastStepIsPrimaryExpr() {
val expr = parse<XPathPathExpr>("/lorem/ipsum/dolor/.")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.NAME_TEST))
assertThat(expr.expressionElement?.textOffset, `is`(13))
}
@Test
@DisplayName("last step is FilterExpr")
fun lastStepIsFilterExpr() {
val expr = parse<XPathPathExpr>("/lorem/ipsum/dolor/.[1]")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.NAME_TEST))
assertThat(expr.expressionElement?.textOffset, `is`(13))
}
@Test
@DisplayName("last step is DynamicFunctionCall")
fun lastStepIsDynamicFunctionCall() {
val expr = parse<XPathPathExpr>("/lorem/ipsum/dolor/.(1)")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.NAME_TEST))
assertThat(expr.expressionElement?.textOffset, `is`(13))
}
@Test
@DisplayName("last step is PostfixLookup")
fun lastStepIsPostfixLookup() {
val expr = parse<XPathPathExpr>("/lorem/ipsum/dolor/.?test")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.NAME_TEST))
assertThat(expr.expressionElement?.textOffset, `is`(13))
}
}
@Nested
@DisplayName("A '//' at the beginning of a path expression")
internal inner class LeadingDoubleForwardSlash {
@Test
@DisplayName("XQuery IntelliJ Plugin EBNF (126) AbbrevDescendantOrSelfStep")
fun abbrevDescendantOrSelfStep() {
val step = parse<PluginAbbrevDescendantOrSelfStep>("//test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.DescendantOrSelf))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
}
}
@Nested
@DisplayName("XQuery 3.1 (3.3.2) Steps")
internal inner class Steps {
@Nested
@DisplayName("XQuery 3.1 EBNF (39) AxisStep")
internal inner class AxisStep {
@Test
@DisplayName("multiple predicates; inner")
fun multiplePredicatesInner() {
val step = parse<XPathAxisStep>("child::test[1][2]")[1] as XpmPathStep
val qname = (step as PsiElement).walkTree().filterIsInstance<XsQNameValue>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, sameInstance(qname))
assertThat(step.nodeType, sameInstance(XdmElementItem))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.ONE))
}
@Test
@DisplayName("multiple predicates; outer")
fun multiplePredicatesOuter() {
val step = parse<XPathAxisStep>("child::test[1][2]")[0] as XpmPathStep
val qname = (step as PsiElement).walkTree().filterIsInstance<XsQNameValue>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, sameInstance(qname))
assertThat(step.nodeType, sameInstance(XdmElementItem))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.valueOf(2)))
}
@Test
@DisplayName("XQuery 3.1 EBNF (117) AbbrevReverseStep")
fun abbrevReverseStep() {
val step = parse<XPathAxisStep>("..[1]")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Parent))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.ONE))
}
@Test
@DisplayName("XQuery 3.1 EBNF (119) NameTest")
fun nameTest() {
val step = parse<XPathAxisStep>("child::test[1]")[0] as XpmPathStep
val qname = (step as PsiElement).walkTree().filterIsInstance<XsQNameValue>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, sameInstance(qname))
assertThat(step.nodeType, sameInstance(XdmElementItem))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.ONE))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest")
fun kindTest() {
val step = parse<XPathAxisStep>("child::node()[1]")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat((step.predicateExpression as? XsIntegerValue)?.data, `is`(BigInteger.ONE))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.3.2.1) Axes")
internal inner class Axes {
@Nested
@DisplayName("XQuery 3.1 EBNF (113) ForwardAxis")
internal inner class ForwardAxis {
@Test
@DisplayName("XQuery 3.1 EBNF (119) NameTest")
fun nameTest() {
val step = parse<XPathForwardStep>("child::test")[0] as XpmPathStep
val qname = (step as PsiElement).walkTree().filterIsInstance<XsQNameValue>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, sameInstance(qname))
assertThat(step.nodeType, sameInstance(XdmElementItem))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest")
fun kindTest() {
val step = parse<XPathForwardStep>("child::node()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("attribute axis")
fun attributeAxis() {
val step = parse<XPathForwardStep>("attribute::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Attribute))
assertThat(step.nodeType, sameInstance(XdmAttributeItem))
}
@Test
@DisplayName("child axis")
fun childAxis() {
val step = parse<XPathForwardStep>("child::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("descendant axis")
fun descendantAxis() {
val step = parse<XPathForwardStep>("descendant::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Descendant))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("descendant-or-self axis")
fun descendantOrSelfAxis() {
val step = parse<XPathForwardStep>("descendant-or-self::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.DescendantOrSelf))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("following axis")
fun followingAxis() {
val step = parse<XPathForwardStep>("following::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Following))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("following-sibling axis")
fun followingSiblingAxis() {
val step = parse<XPathForwardStep>("following-sibling::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.FollowingSibling))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("self axis")
fun selfAxis() {
val step = parse<XPathForwardStep>("self::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("principal node kind")
fun principalNodeKind() {
val steps = parse<XPathNameTest>(
"""
child::one, descendant::two, attribute::three, self::four, descendant-or-self::five,
following-sibling::six, following::seven, namespace::eight
"""
)
assertThat(steps.size, `is`(8))
assertThat(steps[0].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // child
assertThat(steps[1].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // descendant
assertThat(steps[2].getPrincipalNodeKind(), `is`(XpmUsageType.Attribute)) // attribute
assertThat(steps[3].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // self
assertThat(steps[4].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // descendant-or-self
assertThat(steps[5].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // following-sibling
assertThat(steps[6].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // following
assertThat(steps[7].getPrincipalNodeKind(), `is`(XpmUsageType.Namespace)) // namespace
}
@Test
@DisplayName("usage type")
fun usageType() {
val steps = parse<XPathNameTest>(
"""
child::one, descendant::two, attribute::three, self::four, descendant-or-self::five,
following-sibling::six, following::seven, namespace::eight
"""
).map { it.walkTree().filterIsInstance<XsQNameValue>().first().element!! }
assertThat(steps.size, `is`(8))
assertThat(steps[0].getUsageType(), `is`(XpmUsageType.Element)) // child
assertThat(steps[1].getUsageType(), `is`(XpmUsageType.Element)) // descendant
assertThat(steps[2].getUsageType(), `is`(XpmUsageType.Attribute)) // attribute
assertThat(steps[3].getUsageType(), `is`(XpmUsageType.Element)) // self
assertThat(steps[4].getUsageType(), `is`(XpmUsageType.Element)) // descendant-or-self
assertThat(steps[5].getUsageType(), `is`(XpmUsageType.Element)) // following-sibling
assertThat(steps[6].getUsageType(), `is`(XpmUsageType.Element)) // following
assertThat(steps[7].getUsageType(), `is`(XpmUsageType.Namespace)) // namespace
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (116) ReverseAxis")
internal inner class ReverseAxis {
@Test
@DisplayName("XQuery 3.1 EBNF (119) NameTest")
fun nameTest() {
val step = parse<XPathReverseStep>("parent::test")[0] as XpmPathStep
val qname = (step as PsiElement).walkTree().filterIsInstance<XsQNameValue>().first()
assertThat(step.axisType, `is`(XpmAxisType.Parent))
assertThat(step.nodeName, sameInstance(qname))
assertThat(step.nodeType, sameInstance(XdmElementItem))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest")
fun kindTest() {
val step = parse<XPathReverseStep>("parent::node()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Parent))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("ancestor axis")
fun ancestorAxis() {
val step = parse<XPathReverseStep>("ancestor::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Ancestor))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("child axis")
fun ancestorOrSelfAxis() {
val step = parse<XPathReverseStep>("ancestor-or-self::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.AncestorOrSelf))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("parent axis")
fun parentAxis() {
val step = parse<XPathReverseStep>("parent::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Parent))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("preceding axis")
fun precedingAxis() {
val step = parse<XPathReverseStep>("preceding::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Preceding))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("preceding-sibling axis")
fun precedingSiblingAxis() {
val step = parse<XPathReverseStep>("preceding-sibling::test")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.PrecedingSibling))
assertThat(step.nodeType, sameInstance(XdmElementItem))
}
@Test
@DisplayName("principal node kind")
fun principalNodeKind() {
val steps = parse<XPathNameTest>(
"parent::one, ancestor::two, preceding-sibling::three, preceding::four, ancestor-or-self::five"
)
assertThat(steps.size, `is`(5))
assertThat(steps[0].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // parent
assertThat(steps[1].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // ancestor
assertThat(steps[2].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // preceding-sibling
assertThat(steps[3].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // preceding
assertThat(steps[4].getPrincipalNodeKind(), `is`(XpmUsageType.Element)) // ancestor-or-self
}
@Test
@DisplayName("usage type")
fun usageType() {
val steps = parse<XPathNameTest>(
"parent::one, ancestor::two, preceding-sibling::three, preceding::four, ancestor-or-self::five"
).map { it.walkTree().filterIsInstance<XsQNameValue>().first().element!! }
assertThat(steps.size, `is`(5))
assertThat(steps[0].getUsageType(), `is`(XpmUsageType.Element)) // parent
assertThat(steps[1].getUsageType(), `is`(XpmUsageType.Element)) // ancestor
assertThat(steps[2].getUsageType(), `is`(XpmUsageType.Element)) // preceding-sibling
assertThat(steps[3].getUsageType(), `is`(XpmUsageType.Element)) // preceding
assertThat(steps[4].getUsageType(), `is`(XpmUsageType.Element)) // ancestor-or-self
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.3.2.2) Node Tests")
internal inner class NodeTests {
@Nested
@DisplayName("XQuery 3.1 EBNF (119) NameTest")
internal inner class NameTest {
@Test
@DisplayName("NCName namespace resolution; element principal node kind")
fun elementNcname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
ancestor::test
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultElement))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Element))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("NCName namespace resolution; attribute principal node kind")
fun attributeNcname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
attribute::test
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Attribute))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("NCName namespace resolution; namespace principal node kind")
fun namespaceNcname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
namespace::test
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Namespace))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (120) Wildcard")
internal inner class Wildcard {
@Test
@DisplayName("any")
fun any() {
val qname = parse<XPathWildcard>("*")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.prefix, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.prefix!!.data, `is`("*"))
assertThat(qname.localName, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.localName!!.data, `is`("*"))
}
@Test
@DisplayName("wildcard prefix; wildcard local name")
fun bothWildcard() {
val qname = parse<XPathWildcard>("*:*")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.prefix, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.prefix!!.data, `is`("*"))
assertThat(qname.localName, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.localName!!.data, `is`("*"))
}
@Test
@DisplayName("wildcard prefix; non-wildcard local name")
fun wildcardPrefix() {
val qname = parse<XPathWildcard>("*:test")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.prefix, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.prefix!!.data, `is`("*"))
assertThat(qname.localName, `is`(not(instanceOf(XdmWildcardValue::class.java))))
assertThat(qname.localName!!.data, `is`("test"))
}
@Test
@DisplayName("non-wildcard prefix; wildcard local name")
fun wildcardLocalName() {
val qname = parse<XPathWildcard>("test:*")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.prefix, `is`(not(instanceOf(XdmWildcardValue::class.java))))
assertThat(qname.prefix!!.data, `is`("test"))
assertThat(qname.localName, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.localName!!.data, `is`("*"))
}
@Test
@DisplayName("missing local name")
fun noLocalName() {
val qname = parse<XPathWildcard>("*:")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.prefix, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.prefix!!.data, `is`("*"))
assertThat(qname.localName, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.localName!!.data, `is`("*"))
}
@Test
@DisplayName("URIQualifiedName")
fun keyword() {
val qname = parse<XPathWildcard>("Q{http://www.example.com}*")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.localName, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.localName!!.data, `is`("*"))
}
@Test
@DisplayName("URIQualifiedName with an empty namespace")
fun emptyNamespace() {
val qname = parse<XPathWildcard>("Q{}*")[0] as XsQNameValue
assertThat(qname.isLexicalQName, `is`(false))
assertThat(qname.namespace!!.data, `is`(""))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(qname.localName, `is`(instanceOf(XdmWildcardValue::class.java)))
assertThat(qname.localName!!.data, `is`("*"))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.3.3) Predicates within Steps")
internal inner class PredicatesWithinSteps {
@Nested
@DisplayName("XQuery 3.1 EBNF (124) Predicate")
internal inner class Predicate {
@Test
@DisplayName("single")
fun single() {
val expr = parse<PluginFilterStep>("/test[1]")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("multiple")
fun multiple() {
val exprs = parse<PluginFilterStep>("/test[1][2]")
assertThat(exprs[0].expressionElement, `is`(nullValue()))
assertThat(exprs[1].expressionElement, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.3.5) Abbreviated Syntax")
internal inner class AbbreviatedSyntax {
@Nested
@DisplayName("1. The attribute axis attribute:: can be abbreviated by @.")
internal inner class AbbreviatedAttributeAxis {
@Test
@DisplayName("XQuery 3.1 EBNF (119) NameTest")
fun nameTest() {
val step = parse<XPathAbbrevForwardStep>("@test")[0] as XpmPathStep
val qname = (step as PsiElement).walkTree().filterIsInstance<XsQNameValue>().first()
assertThat(step.axisType, `is`(XpmAxisType.Attribute))
assertThat(step.nodeName, sameInstance(qname))
assertThat(step.nodeType, sameInstance(XdmAttributeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (189) AnyKindTest")
fun anyKindTest() {
val step = parse<XPathAbbrevForwardStep>("@node()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Attribute))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
}
@Nested
@DisplayName("2. If the axis name is omitted from an axis step")
internal inner class AxisNameOmittedFromAxisStep {
@Nested
@DisplayName("the default axis is child")
internal inner class DefaultAxis {
@Test
@DisplayName("XQuery 3.1 EBNF (119) NameTest")
fun nameTest() {
val step = parse<XPathNameTest>("test")[0] as XpmPathStep
val qname = (step as PsiElement).walkTree().filterIsInstance<XsQNameValue>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, sameInstance(qname))
assertThat(step.nodeType, sameInstance(XdmElementItem))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (189) AnyKindTest")
fun anyKindTest() {
val step = parse<XPathNodeTest>("node()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (190) DocumentTest")
fun documentTest() {
val step = parse<XPathNodeTest>("document-node()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (191) TextTest")
fun textTest() {
val step = parse<XPathNodeTest>("text()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (192) CommentTest")
fun commentTest() {
val step = parse<XPathNodeTest>("comment()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (194) PITest")
fun piTest() {
val step = parse<XPathNodeTest>("processing-instruction()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (199) ElementTest")
fun elementTest() {
val step = parse<XPathNodeTest>("element()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (201) SchemaElementTest")
fun schemaElementTest() {
val step = parse<XPathNodeTest>("schema-element(test)")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Child))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
}
@Nested
@DisplayName("(1) if the NodeTest in an axis step contains an AttributeTest or SchemaAttributeTest then the default axis is attribute")
internal inner class AttributeAxis {
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (195) AttributeTest")
fun attributeTest() {
val step = parse<XPathNodeTest>("attribute()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Attribute))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (188) KindTest ; XQuery 3.1 EBNF (197) SchemaAttributeTest")
fun schemaAttributeTest() {
val step = parse<XPathNodeTest>("schema-attribute(test)")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Attribute))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
}
@Test
@DisplayName("(2) if the NodeTest in an axis step is a NamespaceNodeTest then the default axis is namespace")
fun namespaceNodeTest() {
val step = parse<XPathNodeTest>("namespace-node()")[0] as XpmPathStep
val itemType = (step as PsiElement).walkTree().filterIsInstance<XdmItemType>().first()
assertThat(step.axisType, `is`(XpmAxisType.Namespace))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(itemType))
assertThat(step.predicateExpression, `is`(nullValue()))
}
}
@Test
@DisplayName("3. Each non-initial occurrence of // is effectively replaced by /descendant-or-self::node()/ during processing of a path expression.")
fun abbrevDescendantOrSelfStep() {
val step = parse<PluginAbbrevDescendantOrSelfStep>("lorem//ipsum")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.DescendantOrSelf))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Test
@DisplayName("4. A step consisting of .. is short for parent::node().")
fun abbrevReverseStep() {
val step = parse<XPathAbbrevReverseStep>("..")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Parent))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (114) AbbrevForwardStep")
internal inner class AbbrevForwardStep {
@Test
@DisplayName("principal node kind")
fun principalNodeKind() {
val steps = parse<XPathNameTest>("one, @two")
assertThat(steps.size, `is`(2))
assertThat(steps[0].getPrincipalNodeKind(), `is`(XpmUsageType.Element))
assertThat(steps[1].getPrincipalNodeKind(), `is`(XpmUsageType.Attribute))
}
@Test
@DisplayName("usage type")
fun usageType() {
val steps = parse<XPathNameTest>("one, @two").map {
it.walkTree().filterIsInstance<XsQNameValue>().first().element!!
}
assertThat(steps.size, `is`(2))
assertThat(steps[0].getUsageType(), `is`(XpmUsageType.Element))
assertThat(steps[1].getUsageType(), `is`(XpmUsageType.Attribute))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.7.1) Sequence Concatenation ; XQuery 3.1 (3.4.1) Constructing Sequences")
internal inner class SequenceConcatenation {
@Test
@DisplayName("XQuery 3.1 EBNF (39) Expr")
fun expr() {
val expr = parse<XPathExpr>("(1, 2 + 3, 4)")[0] as XpmConcatenatingExpression
assertThat(expr.expressionElement, `is`(nullValue()))
val exprs = expr.expressions.toList()
assertThat(exprs.size, `is`(3))
assertThat(exprs[0].text, `is`("1"))
assertThat(exprs[1].text, `is`("2 + 3"))
assertThat(exprs[2].text, `is`("4"))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.7.2) Range Expressions ; XQuery 3.1 (3.4.1) Constructing Sequences")
internal inner class RangeExpressions {
@Test
@DisplayName("XQuery 3.1 EBNF (20) RangeExpr")
fun rangeExpr() {
val expr = parse<XPathRangeExpr>("1 to 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KTo))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.7.3) Combining Node Sequences ; XQuery 3.1 (3.4.2) Combining Node Sequences")
internal inner class CombiningNodeSequences {
@Nested
@DisplayName("XQuery 3.1 EBNF (90) UnionExpr")
internal inner class UnionExpr {
@Test
@DisplayName("keyword")
fun keyword() {
val expr = parse<XPathUnionExpr>("1 union 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KUnion))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("symbol")
fun symbol() {
val expr = parse<XPathUnionExpr>("1 | 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.Union))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (91) IntersectExceptExpr")
internal inner class IntersectExceptExpr {
@Test
@DisplayName("intersect")
fun intersect() {
val expr = parse<XPathIntersectExceptExpr>("1 intersect 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KIntersect))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("except")
fun except() {
val expr = parse<XPathIntersectExceptExpr>("1 except 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KExcept))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.8) Arithmetic Expressions ; XQuery 3.1 (3.5) Arithmetic Expressions")
internal inner class ArithmeticExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (88) AdditiveExpr")
internal inner class AdditiveExpr {
@Test
@DisplayName("plus")
fun plus() {
val expr = parse<XPathAdditiveExpr>("1 + 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.Plus))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("minus")
fun minus() {
val expr = parse<XPathAdditiveExpr>("1 - 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.Minus))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (89) MultiplicativeExpr")
internal inner class MultiplicativeExpr {
@Test
@DisplayName("multiply")
fun multiply() {
val expr = parse<XPathMultiplicativeExpr>("1 * 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.Star))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("div")
fun div() {
val expr = parse<XPathMultiplicativeExpr>("1 div 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KDiv))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("idiv")
fun idiv() {
val expr = parse<XPathMultiplicativeExpr>("1 idiv 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KIDiv))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("mod")
fun mod() {
val expr = parse<XPathMultiplicativeExpr>("1 mod 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KMod))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (97) UnaryExpr")
internal inner class UnaryExpr {
@Test
@DisplayName("plus")
fun plus() {
val expr = parse<XPathUnaryExpr>("+3")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.Plus))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("minus")
fun minus() {
val expr = parse<XPathUnaryExpr>("-3")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.Minus))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.9) String Concatenation Expressions ; XQuery 3.1 (3.6) String Concatenation Expressions")
internal inner class StringConcatenationExpressions {
@Test
@DisplayName("XPath 3.1 EBNF (86) StringConcatExpr")
fun stringConcatExpr() {
val expr = parse<XPathStringConcatExpr>("1 || 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.Concatenation))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.10) Comparison Expressions ; XQuery 3.1 (3.7) Comparison Expressions")
internal inner class ComparisonExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (85) ComparisonExpr ; XQuery 3.1 EBNF (99) GeneralComp")
internal inner class ComparisonExpr_GeneralComp {
@Test
@DisplayName("eq")
fun eq() {
val expr = parse<XPathComparisonExpr>("1 = 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.Equals))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("ne")
fun ne() {
val expr = parse<XPathComparisonExpr>("1 != 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.NotEquals))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("lt")
fun lt() {
val expr = parse<XPathComparisonExpr>("1 < 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.LessThan))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("le")
fun le() {
val expr = parse<XPathComparisonExpr>("1 <= 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.LessThanOrEquals))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("gt")
fun gt() {
val expr = parse<XPathComparisonExpr>("1 > 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.GreaterThan))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("ge")
fun ge() {
val expr = parse<XPathComparisonExpr>("1 >= 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.GreaterThanOrEquals))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (85) ComparisonExpr ; XQuery 3.1 EBNF (100) ValueComp")
internal inner class ComparisonExpr_ValueComp {
@Test
@DisplayName("eq")
fun eq() {
val expr = parse<XPathComparisonExpr>("1 eq 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KEq))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("ne")
fun ne() {
val expr = parse<XPathComparisonExpr>("1 ne 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KNe))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("lt")
fun lt() {
val expr = parse<XPathComparisonExpr>("1 lt 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KLt))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("le")
fun le() {
val expr = parse<XPathComparisonExpr>("1 le 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KLe))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("gt")
fun gt() {
val expr = parse<XPathComparisonExpr>("1 gt 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KGt))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("ge")
fun ge() {
val expr = parse<XPathComparisonExpr>("1 ge 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KGe))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (85) ComparisonExpr ; XQuery 3.1 EBNF (101) NodeComp")
internal inner class ComparisonExpr_NodeComp {
@Test
@DisplayName("is")
fun eq() {
val expr = parse<XPathComparisonExpr>("a is b")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KIs))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("<<")
fun before() {
val expr = parse<XPathComparisonExpr>("a << b")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.NodePrecedes))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName(">>")
fun after() {
val expr = parse<XPathComparisonExpr>("a >> b")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.NodeFollows))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.11) Logical Expressions ; XQuery 3.1 (3.8) Logical Expressions")
internal inner class LogicalExpressions {
@Test
@DisplayName("XQuery 1.0 EBNF (83) OrExpr")
fun orExpr() {
val expr = parse<XPathOrExpr>("1 or 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KOr))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("XQuery 1.0 EBNF (83) AndExpr")
fun andExpr() {
val expr = parse<XPathAndExpr>("1 and 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KAnd))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.12) Node Constructors ; XQuery 3.1 (3.9) Node Constructors")
internal inner class NodeConstructors {
@Nested
@DisplayName("XQuery 4.0 ED (4.12.1) Direct Element Constructors ; XQuery 3.1 (3.9.1) Direct Element Constructors")
internal inner class DirectElementConstructors {
@Nested
@DisplayName("XQuery 3.1 EBNF (142) DirElemConstructor")
internal inner class DirElemConstructor {
@Test
@DisplayName("open and close tags")
fun openAndCloseTags() {
val element = parse<XQueryDirElemConstructor>("<a:b></a:b>")[0]
val open = element.nodeName!!
assertThat(open.prefix!!.data, `is`("a"))
assertThat(open.localName!!.data, `is`("b"))
val close = element.closingTag!!
assertThat(close, `is`(not(sameInstance(open))))
assertThat(close.prefix!!.data, `is`("a"))
assertThat(close.localName!!.data, `is`("b"))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("self-closing")
fun selfClosing() {
val element = parse<XQueryDirElemConstructor>("<h:br/>")[0]
val open = element.nodeName!!
assertThat(open.prefix!!.data, `is`("h"))
assertThat(open.localName!!.data, `is`("br"))
val close = element.closingTag
assertThat(close, `is`(sameInstance(open)))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("error recovery: missing close tag")
fun missingClosingTag() {
val element = parse<XQueryDirElemConstructor>("<a:b>")[0]
val open = element.nodeName!!
assertThat(open.prefix!!.data, `is`("a"))
assertThat(open.localName!!.data, `is`("b"))
val close = element.closingTag
assertThat(close, `is`(sameInstance(open)))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("error recovery: incomplete open tag")
fun incompleteOpenTag() {
val element = parse<XQueryDirElemConstructor>("<a:></a:b>")[0]
val open = element.nodeName!!
assertThat(open.prefix!!.data, `is`("a"))
assertThat(open.localName, `is`(nullValue()))
val close = element.closingTag!!
assertThat(close, `is`(not(sameInstance(open))))
assertThat(close.prefix!!.data, `is`("a"))
assertThat(close.localName!!.data, `is`("b"))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("error recovery: incomplete close tag")
fun incompleteCloseTag() {
val element = parse<XQueryDirElemConstructor>("<a:b></a:>")[0]
val open = element.nodeName!!
assertThat(open.prefix!!.data, `is`("a"))
assertThat(open.localName!!.data, `is`("b"))
val close = element.closingTag!!
assertThat(close, `is`(not(sameInstance(open))))
assertThat(close.prefix!!.data, `is`("a"))
assertThat(close.localName, `is`(nullValue()))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("error recovery: partial close tag only")
fun partialCloseTagOnly() {
val element = parse<XQueryDirElemConstructor>("</<test>")[0]
val open = element.nodeName
assertThat(open, `is`(nullValue()))
val close = element.closingTag
assertThat(close, `is`(nullValue()))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("error recovery: close tag only")
fun soloCloseTag() {
val element = parse<XQueryDirElemConstructor>("</a:b>")[0]
val open = element.nodeName!!
assertThat(open.prefix!!.data, `is`("a"))
assertThat(open.localName!!.data, `is`("b"))
val close = element.closingTag!!
assertThat(close, `is`(sameInstance(open)))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
<test/>
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultElement))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Element))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("NCName namespace resolution with xmlns")
fun ncnameWithXmlns() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element/2";
<test xmlns="http://www.example.co.uk/element"/>
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultElement))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Element))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (143) DirAttributeList")
internal inner class DirAttributeList {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>("<elem test=\"\"/>")[1] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Attribute))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("QName")
fun qname() {
val qname = parse<XPathQName>("<elem fn:test=\"\"/>")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Attribute))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.w3.org/2005/xpath-functions"))
assertThat(expanded[0].prefix!!.data, `is`("fn"))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("namespace declaration attributes")
fun namespaceDeclarationAttributes() {
val qname = parse<XPathQName>("<elem xmlns:abc=\"http://www.example.com\"/>")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Namespace))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("xmlns"))
assertThat(qname.localName!!.data, `is`("abc"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(0))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (143) DirAttributeList ; XQuery IntelliJ Plugin EBNF (154) DirNamespaceAttribute")
internal inner class DirNamespaceAttribute {
@Test
@DisplayName("namespace prefix")
fun namespacePrefix() {
val expr = parse<PluginDirNamespaceAttribute>(
"<a xmlns:b='http://www.example.com'/>"
)[0] as XpmNamespaceDeclaration
assertThat(expr.namespacePrefix!!.data, `is`("b"))
assertThat(expr.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(expr.namespaceUri!!.context, `is`(XdmUriContext.NamespaceDeclaration))
assertThat(expr.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(expr.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.None), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(expr.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("default element/type namespace")
fun defaultElementTypeNamespace() {
val expr = parse<PluginDirNamespaceAttribute>(
"<a xmlns='http://www.example.com'/>"
)[0] as XpmNamespaceDeclaration
assertThat(expr.namespacePrefix?.data, `is`(""))
assertThat(expr.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(expr.namespaceUri!!.context, `is`(XdmUriContext.NamespaceDeclaration))
assertThat(expr.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(expr.accepts(XdmNamespaceType.DefaultElement), `is`(true))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.DefaultType), `is`(true))
assertThat(expr.accepts(XdmNamespaceType.None), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.Prefixed), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(expr.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Nested
@DisplayName("resolve uri")
internal inner class ResolveUri {
@Test
@DisplayName("empty")
fun empty() {
val file = parseResource("tests/resolve-xquery/files/DirAttributeList_Empty.xq")
val psi = file.walkTree().filterIsInstance<PluginDirNamespaceAttribute>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("same directory")
fun sameDirectory() {
val file = parseResource("tests/resolve-xquery/files/DirAttributeList_SameDirectory.xq")
val psi = file.walkTree().filterIsInstance<PluginDirNamespaceAttribute>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("http:// file matching")
fun httpProtocol() {
val file = parseResource("tests/resolve-xquery/files/DirAttributeList_HttpProtocol.xq")
val psi = file.walkTree().filterIsInstance<PluginDirNamespaceAttribute>().toList()[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
assertThat(
prologs[0].resourcePath(),
endsWith("/org/w3/www/2005/xpath-functions/array.xqy")
)
}
@Test
@DisplayName("http:// file missing")
fun httpProtocolMissing() {
val file = parseResource("tests/resolve-xquery/files/DirAttributeList_HttpProtocol_FileNotFound.xq")
val psi = file.walkTree().filterIsInstance<PluginDirNamespaceAttribute>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.12.2) Other Direct Constructors ; XQuery 3.1 (3.9.2) Other Direct Constructors")
internal inner class OtherDirectConstructors {
@Test
@DisplayName("XQuery 3.1 EBNF (149) DirCommentConstructor")
fun dirCommentConstructor() {
val expr = parse<XQueryDirCommentConstructor>("<!-- test -->")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_COMMENT_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("XQuery 3.1 EBNF (151) DirPIConstructor")
fun dirPIConstructor() {
val expr = parse<XQueryDirPIConstructor>("<?test?>")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.DIR_PI_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.12.3) Computed Constructors ; XQuery 3.1 (3.9.3) Computed Constructors")
internal inner class ComputedElementConstructors {
@Test
@DisplayName("XQuery 3.1 EBNF (156) CompDocConstructor")
fun compDocConstructor() {
val expr = parse<XQueryCompDocConstructor>("document { <test/> }")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.COMP_DOC_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (157) CompElemConstructor")
internal inner class CompElemConstructor {
@Test
@DisplayName("nodeName as an EQName")
fun nodeNameEQName() {
val element = parse<XQueryCompElemConstructor>("element a:b {}")[0]
val name = element.nodeName!!
assertThat(name.prefix!!.data, `is`("a"))
assertThat(name.localName!!.data, `is`("b"))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.COMP_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("nodeName is an expression")
fun nodeNameExpr() {
val element = parse<XQueryCompElemConstructor>("element { \"a:\" || \"b\" } {}")[0]
assertThat(element.nodeName, `is`(nullValue()))
val expr = element as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.COMP_ELEM_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
element test {}
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultElement))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Element))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (159) CompAttrConstructor")
internal inner class CompAttrConstructor {
@Test
@DisplayName("expression")
fun expression() {
val expr = parse<XQueryCompAttrConstructor>("attribute a:b {}")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>("attribute test {}")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Attribute))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (160) CompNamespaceConstructor")
internal inner class CompNamespaceConstructor {
@Test
@DisplayName("nodeName as an EQName")
fun nodeNameEQName() {
val ns = parse<XQueryCompNamespaceConstructor>(
"namespace test { \"http://www.example.co.uk\" }"
)[0]
val expr = ns as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("nodeName as an expression")
fun nodeNameExpr() {
val ns = parse<XQueryCompNamespaceConstructor>(
"namespace { \"test\" } { \"http://www.example.co.uk\" }"
)[0]
val expr = ns as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
@Test
@DisplayName("XQuery 3.1 EBNF (164) CompTextConstructor")
fun compTextConstructor() {
val expr = parse<XQueryCompTextConstructor>("text { 1 }")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.COMP_TEXT_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("XQuery 3.1 EBNF (165) CompCommentConstructor")
fun compCommentConstructor() {
val expr = parse<XQueryCompCommentConstructor>("comment { 1 }")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.COMP_COMMENT_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (166) CompPIConstructor")
internal inner class CompPIConstructor {
@Test
@DisplayName("nodeName as an EQName")
fun nodeNameEQName() {
val ns = parse<XQueryCompPIConstructor>(
"processing-instruction test {}"
)[0]
val expr = ns as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.COMP_PI_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("nodeName as an expression")
fun nodeNameExpr() {
val ns = parse<XQueryCompPIConstructor>(
"processing-instruction { \"test\" } {}"
)[0]
val expr = ns as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.COMP_PI_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.13) String Constructors ; XQuery 3.1 (3.10) String Constructors")
internal inner class StringConstructors {
@Test
@DisplayName("XQuery 1.0 EBNF (177) StringConstructor")
fun stringConstructor() {
val expr = parse<XQueryStringConstructor>("``[`{1}` + `{2}`]``")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.STRING_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
@Nested
@DisplayName("XXQuery 4.0 ED (4.14) Maps and Arrays ; Query 3.1 (3.11) Maps and Arrays")
internal inner class MapsAndArrays {
@Nested
@DisplayName("XQuery 3.1 (3.11.1) Maps")
internal inner class Maps {
@Nested
@DisplayName("XQuery 3.1 EBNF (170) MapConstructor")
internal inner class MapConstructor {
@Test
@DisplayName("empty")
fun empty() {
val expr = parse<XPathMapConstructor>("map {}")[0] as XpmMapExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.MAP_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.itemTypeClass, sameInstance(XdmMap::class.java))
assertThat(expr.itemExpression, sameInstance(expr))
val entries = expr.entries.toList()
assertThat(entries.size, `is`(0))
}
@Test
@DisplayName("with entries")
fun withEntries() {
val expr = parse<XPathMapConstructor>("map { \"1\" : \"one\", \"2\" : \"two\" }")[0] as XpmMapExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.MAP_CONSTRUCTOR_ENTRY))
assertThat(expr.expressionElement?.textOffset, `is`(6))
assertThat(expr.itemTypeClass, sameInstance(XdmMap::class.java))
assertThat(expr.itemExpression, sameInstance(expr))
val entries = expr.entries.toList()
assertThat(entries.size, `is`(2))
assertThat((entries[0].keyExpression as XPathStringLiteral).data, `is`("1"))
assertThat((entries[0].valueExpression as XPathStringLiteral).data, `is`("one"))
assertThat((entries[1].keyExpression as XPathStringLiteral).data, `is`("2"))
assertThat((entries[1].valueExpression as XPathStringLiteral).data, `is`("two"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (171) MapConstructorEntry")
internal inner class MapConstructorEntry {
@Test
@DisplayName("string key, value")
fun stringKey() {
val entry = parse<XPathMapConstructorEntry>("map { \"1\" : \"one\" }")[0]
assertThat(entry.separator.elementType, `is`(XPathTokenProvider.Colon))
assertThat((entry.keyExpression as XPathStringLiteral).data, `is`("1"))
assertThat((entry.valueExpression as XPathStringLiteral).data, `is`("one"))
assertThat(entry.keyName, `is`(nullValue()))
}
@Test
@DisplayName("integer key, value")
fun integerKey() {
val entry = parse<XPathMapConstructorEntry>("map { 1 : \"one\" }")[0]
assertThat(entry.separator.elementType, `is`(XPathTokenProvider.Colon))
assertThat((entry.keyExpression as XPathIntegerLiteral).data, `is`(BigInteger.ONE))
assertThat((entry.valueExpression as XPathStringLiteral).data, `is`("one"))
assertThat(entry.keyName, `is`(nullValue()))
}
@Test
@DisplayName("variable key, no value")
fun missingValue() {
val entry = parse<XPathMapConstructorEntry>("map { \$ a }")[0]
assertThat(entry.separator.elementType, `is`(XPathElementType.VAR_REF))
assertThat((entry.keyExpression as XpmVariableReference).variableName?.localName?.data, `is`("a"))
assertThat(entry.valueExpression, `is`(nullValue()))
assertThat(entry.keyName, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.11.2) Arrays")
internal inner class Arrays {
@Nested
@DisplayName("XQuery 3.1 EBNF (175) SquareArrayConstructor")
internal inner class SquareArrayConstructor {
@Test
@DisplayName("empty")
fun empty() {
val expr = parse<XPathSquareArrayConstructor>("[]")[0] as XpmArrayExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.SQUARE_ARRAY_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.itemTypeClass, sameInstance(XdmArray::class.java))
assertThat(expr.itemExpression, sameInstance(expr))
val entries = expr.memberExpressions.toList()
assertThat(entries.size, `is`(0))
}
@Test
@DisplayName("single member")
fun singleMember() {
val expr = parse<XPathSquareArrayConstructor>("[ 1 ]")[0] as XpmArrayExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.SQUARE_ARRAY_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.itemTypeClass, sameInstance(XdmArray::class.java))
assertThat(expr.itemExpression, sameInstance(expr))
val entries = expr.memberExpressions.toList()
assertThat(entries.size, `is`(1))
assertThat(entries[0].text, `is`("1"))
}
@Test
@DisplayName("multiple members")
fun multipleMembers() {
val expr = parse<XPathSquareArrayConstructor>("[ 1, 2 + 3, 4 ]")[0] as XpmArrayExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.SQUARE_ARRAY_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.itemTypeClass, sameInstance(XdmArray::class.java))
assertThat(expr.itemExpression, sameInstance(expr))
val entries = expr.memberExpressions.toList()
assertThat(entries.size, `is`(3))
assertThat(entries[0].text, `is`("1"))
assertThat(entries[1].text, `is`("2 + 3"))
assertThat(entries[2].text, `is`("4"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (176) CurlyArrayConstructor")
internal inner class CurlyArrayConstructor {
@Test
@DisplayName("empty")
fun empty() {
val expr = parse<XPathCurlyArrayConstructor>("array {}")[0] as XpmArrayExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.CURLY_ARRAY_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.itemTypeClass, sameInstance(XdmArray::class.java))
assertThat(expr.itemExpression, sameInstance(expr))
val entries = expr.memberExpressions.toList()
assertThat(entries.size, `is`(0))
}
@Test
@DisplayName("single member")
fun singleMember() {
val expr = parse<XPathCurlyArrayConstructor>("array { 1 }")[0] as XpmArrayExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.CURLY_ARRAY_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.itemTypeClass, sameInstance(XdmArray::class.java))
assertThat(expr.itemExpression, sameInstance(expr))
val entries = expr.memberExpressions.toList()
assertThat(entries.size, `is`(1))
assertThat(entries[0].text, `is`("1"))
}
@Test
@DisplayName("multiple members")
fun multipleMembers() {
val expr = parse<XPathCurlyArrayConstructor>("array { 1, 2 + 3, 4 }")[0] as XpmArrayExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.CURLY_ARRAY_CONSTRUCTOR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.itemTypeClass, sameInstance(XdmArray::class.java))
assertThat(expr.itemExpression, sameInstance(expr))
val entries = expr.memberExpressions.toList()
assertThat(entries.size, `is`(3))
assertThat(entries[0].text, `is`("1"))
assertThat(entries[1].text, `is`("2 + 3"))
assertThat(entries[2].text, `is`("4"))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.11.3.1) Unary Lookup")
internal inner class UnaryLookup {
@Test
@DisplayName("XQuery 3.1 EBNF (181) UnaryLookup")
fun unaryLookup() {
val expr = parse<XPathUnaryLookup>("map{} ! ?name")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.QuestionMark))
assertThat(expr.expressionElement?.textOffset, `is`(8))
}
@Test
@DisplayName("XQuery 3.1 EBNF (126) KeySpecifier ; XQuery 3.1 EBNF (219) IntegerLiteral")
fun keySpecifier_expression() {
val expr = parse<XPathUnaryLookup>("map{} ! ?2")[0] as XpmLookupExpression
assertThat(expr.contextExpression, sameInstance(XpmContextItem))
val key = expr.keyExpression as XsIntegerValue
assertThat(key.data, `is`(BigInteger.valueOf(2)))
}
@Test
@DisplayName("XQuery 3.1 EBNF (126) KeySpecifier ; XQuery 3.1 EBNF (235) NCName")
fun keySpecifier_ncname() {
val expr = parse<XPathUnaryLookup>("map{} ! ?name")[0] as XpmLookupExpression
assertThat(expr.contextExpression, sameInstance(XpmContextItem))
val key = expr.keyExpression as XsNCNameValue
assertThat(key.data, `is`("name"))
}
@Test
@DisplayName("XQuery 3.1 EBNF (126) KeySpecifier ; wildcard")
fun keySpecifier_wildcard() {
val expr = parse<XPathUnaryLookup>("map{} ! ?*")[0] as XpmLookupExpression
assertThat(expr.contextExpression, sameInstance(XpmContextItem))
val key = expr.keyExpression as XdmWildcardValue
assertThat(key.data, `is`("*"))
}
}
@Nested
@DisplayName("XQuery 3.1 (3.11.3.2) Postfix Lookup")
internal inner class PostfixLookup {
@Test
@DisplayName("XQuery IntelliJ Plugin EBNF (130) PostfixLookup")
fun postfixLookup() {
val step = parse<XPathPostfixExpr>("\$x?name")[0] as XpmPathStep
assertThat(step.axisType, `is`(XpmAxisType.Self))
assertThat(step.nodeName, `is`(nullValue()))
assertThat(step.nodeType, sameInstance(XdmNodeItem))
assertThat(step.predicateExpression, `is`(nullValue()))
val expr = step as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.QuestionMark))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("XQuery 3.1 EBNF (126) KeySpecifier ; XQuery 3.1 EBNF (219) IntegerLiteral")
fun keySpecifier_expression() {
val expr = parse<XPathPostfixExpr>("\$x?2")[0] as XpmLookupExpression
assertThat(expr.contextExpression.text, `is`("\$x"))
val key = expr.keyExpression as XsIntegerValue
assertThat(key.data, `is`(BigInteger.valueOf(2)))
}
@Test
@DisplayName("XQuery 3.1 EBNF (126) KeySpecifier ; XQuery 3.1 EBNF (235) NCName")
fun keySpecifier_ncname() {
val expr = parse<XPathPostfixExpr>("\$x?name")[0] as XpmLookupExpression
assertThat(expr.contextExpression.text, `is`("\$x"))
val key = expr.keyExpression as XsNCNameValue
assertThat(key.data, `is`("name"))
}
@Test
@DisplayName("XQuery 3.1 EBNF (126) KeySpecifier ; wildcard")
fun keySpecifier_wildcard() {
val expr = parse<XPathPostfixExpr>("\$x?*")[0] as XpmLookupExpression
assertThat(expr.contextExpression.text, `is`("\$x"))
val key = expr.keyExpression as XdmWildcardValue
assertThat(key.data, `is`("*"))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.15) FLWOR Expressions ; XQuery 3.1 (3.12) FLWOR Expressions")
internal inner class FLWORExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (41) FLWORExpr")
internal inner class FLWORExpr {
@Test
@DisplayName("for")
fun `for`() {
val expr = parse<XQueryFLWORExpr>("for \$x in (1, 2, 3) return \$x = 1")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.FLWOR_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("let")
fun let() {
val expr = parse<XQueryFLWORExpr>("let \$x := 1 return \$x = 1")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.FLWOR_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (47) PositionalVar")
internal inner class PositionalVar {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryPositionalVar>("for \$x at \$y in \$z return \$w")[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryPositionalVar>(
"for \$a:x at \$a:y in \$a:z return \$a:w"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryPositionalVar>(
"for \$Q{http://www.example.com}x at \$Q{http://www.example.com}y in \$Q{http://www.example.com}z " +
"return \$Q{http://www.example.com}w"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XQueryPositionalVar>("for \$x at \$ \$z return \$w")[0] as XpmVariableBinding
assertThat(expr.variableName, `is`(nullValue()))
}
}
@Nested
@DisplayName("XQuery 3.1 (3.12.2) For Clause ; XQuery 4.0 ED (4.15.2) For Clause")
internal inner class ForClause {
@Nested
@DisplayName("XQuery 3.1 EBNF (45) ForBinding")
internal inner class ForBinding {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryForBinding>("for \$x at \$y in \$z return \$w")[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$z"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryForBinding>(
"for \$a:x at \$a:y in \$a:z return \$a:w"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$a:z"))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryForBinding>(
"for \$Q{http://www.example.com}x at \$Q{http://www.example.com}y in \$Q{http://www.example.com}z " +
"return \$Q{http://www.example.com}w"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$Q{http://www.example.com}z"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XQueryForBinding>("for \$ \$y return \$w")[0] as XpmCollectionBinding
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
}
@Test
@DisplayName("with type")
fun withType() {
val expr = parse<XQueryForBinding>(
"for \$x as node ( (: :) ) ? at \$y in \$z return \$w"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`("node()?"))
assertThat(expr.bindingExpression?.text, `is`("\$z"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (53) ForMemberBinding")
internal inner class ForMemberBinding {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryForMemberBinding>(
"for member \$x at \$y in \$z return \$w"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$z"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryForMemberBinding>(
"for member \$a:x at \$a:y in \$a:z return \$a:w"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$a:z"))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryForMemberBinding>(
"for member \$Q{http://www.example.com}x at \$Q{http://www.example.com}y " +
"in \$Q{http://www.example.com}z " +
"return \$Q{http://www.example.com}w"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$Q{http://www.example.com}z"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XQueryForMemberBinding>(
"for member \$ \$y return \$w"
)[0] as XpmCollectionBinding
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
}
@Test
@DisplayName("with type")
fun withType() {
val expr = parse<XQueryForMemberBinding>(
"for member \$x as node ( (: :) ) ? at \$y in \$z return \$w"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`("node()?"))
assertThat(expr.bindingExpression?.text, `is`("\$z"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.12.3) Let Clause")
internal inner class LetClause {
@Nested
@DisplayName("XQuery 3.1 EBNF (49) LetBinding")
internal inner class LetBinding {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryLetBinding>("let \$x := 2 return \$w")[0]
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("2"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryLetBinding>("let \$a:x := 2 return \$a:w")[0]
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("2"))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryLetBinding>(
"let \$Q{http://www.example.com}x := 2 return \$Q{http://www.example.com}w"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("2"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XQueryLetBinding>("let \$ := 2 return \$w")[0] as XpmAssignableVariable
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("2"))
}
@Test
@DisplayName("with type")
fun withType() {
val expr = parse<XQueryLetBinding>(
"let \$x as node ( (::) )? := 2 return \$w"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`("node()?"))
assertThat(expr.variableExpression?.text, `is`("2"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.12.4) Window Clause")
internal inner class WindowClause {
@Nested
@DisplayName("XQuery 3.1 EBNF (51) TumblingWindowClause")
internal inner class TumblingWindowClause {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryTumblingWindowClause>(
"for tumbling window \$x in \$y return \$z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryTumblingWindowClause>(
"for tumbling window \$a:x in \$a:y return \$a:z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$a:y"))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryTumblingWindowClause>(
"for tumbling window \$Q{http://www.example.com}x in \$Q{http://www.example.com}y " +
"return \$Q{http://www.example.com}z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$Q{http://www.example.com}y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XQueryTumblingWindowClause>(
"for tumbling window \$ \$y return \$w"
)[0] as XpmCollectionBinding
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
}
@Test
@DisplayName("with type")
fun withType() {
val expr = parse<XQueryTumblingWindowClause>(
"for tumbling window \$x as node ( (: :) ? in \$y return \$z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`("node()?"))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (52) SlidingWindowClause")
internal inner class SlidingWindowClause {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQuerySlidingWindowClause>(
"for sliding window \$x in \$y return \$z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQuerySlidingWindowClause>(
"for sliding window \$a:x in \$a:y return \$a:z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$a:y"))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQuerySlidingWindowClause>(
"for sliding window \$Q{http://www.example.com}x in \$Q{http://www.example.com}y " +
"return \$Q{http://www.example.com}z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$Q{http://www.example.com}y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XQuerySlidingWindowClause>(
"for sliding window \$ \$y return \$w"
)[0] as XpmCollectionBinding
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
}
@Test
@DisplayName("with type")
fun withType() {
val expr = parse<XQuerySlidingWindowClause>(
"for sliding window \$x as node ( (: :) ) ? in \$y return \$z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`("node()?"))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (56) CurrentItem")
internal inner class CurrentItem {
@Test
@DisplayName("NCName namespace resolution")
fun ncnameResolution() {
val qname = parse<XPathNCName>(
"for sliding window \$x in () start \$test when () end when () return ()"
)[1] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Variable))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryCurrentItem>(
"for sliding window \$x in \$y start \$w when true() return \$z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryCurrentItem>(
"for sliding window \$a:x in \$a:y start \$a:w when true() return \$a:z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryCurrentItem>(
"for sliding window \$Q{http://www.example.com}x in \$Q{http://www.example.com}y " +
"start \$Q{http://www.example.com}w when true() " +
"return \$Q{http://www.example.com}z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (57) PreviousItem")
internal inner class PreviousItem {
@Test
@DisplayName("NCName namespace resolution")
fun ncnameResolution() {
val qname = parse<XPathNCName>(
"for sliding window \$x in () start previous \$test when () end when () return ()"
)[1] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Variable))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryPreviousItem>(
"for sliding window \$x in \$y start \$v previous \$w when true() return \$z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryPreviousItem>(
"for sliding window \$a:x in \$a:y start \$a:v previous \$a:w when true() return \$a:z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryPreviousItem>(
"for sliding window \$Q{http://www.example.com}x in \$Q{http://www.example.com}y " +
"start \$Q{http://www.example.com}v previous \$Q{http://www.example.com}w when true() " +
"return \$Q{http://www.example.com}z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (58) NextItem")
internal inner class NextItem {
@Test
@DisplayName("NCName namespace resolution")
fun ncnameResolution() {
val qname = parse<XPathNCName>(
"for sliding window \$x in () start next \$test when () end when () return ()"
)[1] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Variable))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryNextItem>(
"for sliding window \$x in \$y start \$v next \$w when true() return \$z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryNextItem>(
"for sliding window \$a:x in \$a:y start \$a:v next \$a:w when true() return \$a:z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryNextItem>(
"for sliding window \$Q{http://www.example.com}x in \$Q{http://www.example.com}y " +
"start \$Q{http://www.example.com}v next \$Q{http://www.example.com}w when true() " +
"return \$Q{http://www.example.com}z"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("w"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.12.6) Count Clause")
internal inner class CountClause {
@Nested
@DisplayName("XQuery 3.1 EBNF (59) CountClause")
internal inner class CountClauseTest {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryCountClause>("for \$x in \$y count \$z return \$w")[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("z"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryCountClause>(
"for \$a:x in \$a:y count \$a:z return \$a:w"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("z"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryCountClause>(
"for \$Q{http://www.example.com}x in \$Q{http://www.example.com}y count \$Q{http://www.example.com}z " +
"return \$Q{http://www.example.com}w"
)[0] as XpmVariableBinding
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("z"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.12.7) Group By Clause")
internal inner class GroupByClause {
@Nested
@DisplayName("XQuery 3.1 EBNF (63) GroupingSpec")
internal inner class GroupingSpec {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryGroupingSpec>(
"for \$x in \$y group by \$z return \$w"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression, `is`(nullValue()))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("z"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryGroupingSpec>(
"for \$a:x in \$a:y group by \$a:z return \$a:w"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression, `is`(nullValue()))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("z"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryGroupingSpec>(
"for \$Q{http://www.example.com}x in \$Q{http://www.example.com}y " +
"group by \$Q{http://www.example.com}z " +
"return \$Q{http://www.example.com}w"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression, `is`(nullValue()))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("z"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryFLWORExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XQueryGroupingSpec>("for \$x in \$y group by \$")[0] as XpmAssignableVariable
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression, `is`(nullValue()))
}
@Test
@DisplayName("with expression")
fun withExpression() {
val expr = parse<XQueryGroupingSpec>(
"for \$x in \$y group by \$z := 2 return \$w"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("2"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("z"))
}
@Test
@DisplayName("with type and expression")
fun withTypeAndExpression() {
val expr = parse<XQueryGroupingSpec>(
"for \$x in \$y group by \$z as node ( (: :) ) ? := 2 return \$w"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`("node()?"))
assertThat(expr.variableExpression?.text, `is`("2"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("z"))
}
@Test
@DisplayName("non-empty collation uri")
fun nonEmptyUri() {
val expr = parse<XQueryGroupingSpec>(
"for \$x in \$y group by \$x collation 'http://www.example.com'"
)[0]
assertThat(expr.collation!!.data, `is`("http://www.example.com"))
assertThat(expr.collation!!.context, `is`(XdmUriContext.Collation))
assertThat(expr.collation!!.moduleTypes, `is`(sameInstance(XdmModuleType.NONE)))
}
@Test
@DisplayName("missing collation uri")
fun noNamespaceUri() {
val expr = parse<XQueryGroupingSpec>("for \$x in \$y group by \$x")[0]
assertThat(expr.collation, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 3.1 (3.12.8) Order By Clause")
internal inner class OrderByClause {
@Nested
@DisplayName("XQuery 3.1 EBNF (68) OrderModifier")
internal inner class OrderModifier {
@Test
@DisplayName("non-empty collation uri")
fun nonEmptyUri() {
val expr = parse<XQueryOrderModifier>(
"for \$x in \$y order by \$x collation 'http://www.example.com'"
)[0]
assertThat(expr.collation!!.data, `is`("http://www.example.com"))
assertThat(expr.collation!!.context, `is`(XdmUriContext.Collation))
assertThat(expr.collation!!.moduleTypes, `is`(sameInstance(XdmModuleType.NONE)))
}
@Test
@DisplayName("missing collation uri")
fun noNamespaceUri() {
val expr = parse<XQueryOrderModifier>("for \$x in \$y order by \$x ascending")[0]
assertThat(expr.collation, `is`(nullValue()))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.16) Ordered and Unordered Expressions ; XQuery 3.1 (3.13) Ordered and Unordered Expressions")
internal inner class OrderedAndUnorderedExpressions {
@Test
@DisplayName("XQuery 3.1 EBNF (135) OrderedExpr")
fun orderedExpr() {
val expr = parse<XQueryOrderedExpr>("ordered { 1, 2, 3 }")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (136) UnorderedExpr")
fun unorderedExpr() {
val expr = parse<XQueryUnorderedExpr>("unordered { 1, 2, 3 }")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.17) Conditional Expressions ; XQuery 3.1 (3.14) Conditional Expressions")
internal inner class ConditionalExpressions {
@Test
@DisplayName("XQuery 4.0 ED EBNF (45) TernaryConditionalExpr")
fun ternaryConditionalExpr() {
val expr = parse<XPathTernaryConditionalExpr>("true() ?? 1 !! 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.TernaryIfThen))
assertThat(expr.expressionElement?.textOffset, `is`(7))
}
@Test
@DisplayName("XQuery 3.1 EBNF (77) IfExpr")
fun ifExpr() {
val expr = parse<XPathIfExpr>("if (true()) then 1 else 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.IF_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.18) Otherwise Expressions")
internal inner class OtherwiseExpressions {
@Test
@DisplayName("XQuery 4.0 ED EBNF (96) OtherwiseExpr")
fun otherwiseExpr() {
val expr = parse<XPathOtherwiseExpr>("1 otherwise 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KOtherwise))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.19) Switch Expressions ; XQuery 3.1 (3.15) Switch Expression")
internal inner class SwitchExpression {
@Test
@DisplayName("XQuery 3.1 EBNF (71) SwitchExpr")
fun switchExpr() {
val expr = parse<XQuerySwitchExpr>("switch (1) case 1 return 1 default return 2")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.SWITCH_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.20) Quantified Expressions ; XQuery 3.1 (3.16) Quantified Expressions")
internal inner class QuantifiedExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (70) QuantifiedExpr")
internal inner class QuantifiedExpr {
@Test
@DisplayName("some")
fun some() {
val expr = parse<XPathQuantifiedExpr>("some \$x in (1, 2, 3) satisfies \$x = 1")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.QUANTIFIED_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Test
@DisplayName("every")
fun every() {
val expr = parse<XPathQuantifiedExpr>("every \$x in (1, 2, 3) satisfies \$x = 1")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.QUANTIFIED_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (70) QuantifiedExpr ; XQuery 4.0 ED EBNF (78) QuantifierBinding")
internal inner class QuantifierBinding {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XPathQuantifierBinding>("some \$x in \$y satisfies \$z")[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XPathQuantifiedExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XPathQuantifierBinding>("some \$a:x in \$a:y satisfies \$a:z")[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$a:y"))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XPathQuantifiedExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XPathQuantifierBinding>(
"some \$Q{http://www.example.com}x in \$Q{http://www.example.com}y satisfies \$Q{http://www.example.com}z"
)[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`("\$Q{http://www.example.com}y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("x"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XPathQuantifiedExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XPathQuantifierBinding>("some \$")[0] as XpmCollectionBinding
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.bindingExpression?.text, `is`(nullValue()))
}
@Test
@DisplayName("with type")
fun withType() {
val expr = parse<XPathQuantifierBinding>("some \$x as node ( (: :) ) ? in \$y satisfies \$z")[0] as XpmCollectionBinding
assertThat(expr.variableType?.typeName, `is`("node()?"))
assertThat(expr.bindingExpression?.text, `is`("\$y"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.21) Try/Catch Expressions ; XQuery 3.1 (3.17) Try/Catch Expressions")
internal inner class TryCatchExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (78) TryCatchExpr")
internal inner class TryCatchExpr {
@Test
@DisplayName("with expression ; single catch clause")
fun expression() {
val expr = parse<XQueryTryCatchExpr>("try { 1 } catch * { 2 }")[0] as XpmTryCatchExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.TRY_CATCH_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.tryExpression.text, `is`("1"))
val catchClauses = expr.catchClauses.toList()
assertThat(catchClauses.size, `is`(1))
assertThat((catchClauses[0] as PsiElement).text, `is`("catch * { 2 }"))
}
@Test
@DisplayName("empty expression ; single catch clause")
fun emptyExpression() {
val expr = parse<XQueryTryCatchExpr>("try { } catch * { 2 }")[0] as XpmTryCatchExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.TRY_CATCH_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.tryExpression, sameInstance(XpmEmptyExpression))
val catchClauses = expr.catchClauses.toList()
assertThat(catchClauses.size, `is`(1))
assertThat((catchClauses[0] as PsiElement).text, `is`("catch * { 2 }"))
}
@Test
@DisplayName("with expression ; multiple catch clauses")
fun multipleCatchClauses() {
val expr = parse<XQueryTryCatchExpr>(
"try { 1 } catch err:XPTY0004 { 2 } catch err:XPTY0005 { 3 }"
)[0] as XpmTryCatchExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.TRY_CATCH_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
assertThat(expr.tryExpression.text, `is`("1"))
val catchClauses = expr.catchClauses.toList()
assertThat(catchClauses.size, `is`(2))
assertThat((catchClauses[0] as PsiElement).text, `is`("catch err:XPTY0004 { 2 }"))
assertThat((catchClauses[1] as PsiElement).text, `is`("catch err:XPTY0005 { 3 }"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (81) CatchClause")
internal inner class CatchClause {
@Test
@DisplayName("with expression ; wildcard error name")
fun wildcard() {
val expr = parse<XQueryCatchClause>("try { 1 } catch * { 2 }")[0] as XpmCatchClause
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.catchExpression.text, `is`("2"))
val errorList = expr.errorList.toList()
assertThat(errorList.size, `is`(1))
assertThat(qname_presentation(errorList[0]), `is`("*:*"))
}
@Test
@DisplayName("with expression ; single error name")
fun expression() {
val expr = parse<XQueryCatchClause>("try { 1 } catch err:XPTY0004 { 2 }")[0] as XpmCatchClause
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.catchExpression.text, `is`("2"))
val errorList = expr.errorList.toList()
assertThat(errorList.size, `is`(1))
assertThat(qname_presentation(errorList[0]), `is`("err:XPTY0004"))
}
@Test
@DisplayName("empty expression ; single error name")
fun emptyExpression() {
val expr = parse<XQueryCatchClause>("try { 1 } catch err:XPTY0004 { }")[0] as XpmCatchClause
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.catchExpression, sameInstance(XpmEmptyExpression))
val errorList = expr.errorList.toList()
assertThat(errorList.size, `is`(1))
assertThat(qname_presentation(errorList[0]), `is`("err:XPTY0004"))
}
@Test
@DisplayName("with expression ; multiple error names")
fun multipleErrorNames() {
val expr = parse<XQueryCatchClause>(
"try { 1 } catch err:XPTY0004 | err:XPTY0005 { 2 }"
)[0] as XpmCatchClause
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.catchExpression.text, `is`("2"))
val errorList = expr.errorList.toList()
assertThat(errorList.size, `is`(2))
assertThat(qname_presentation(errorList[0]), `is`("err:XPTY0004"))
assertThat(qname_presentation(errorList[1]), `is`("err:XPTY0005"))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.22) Expressions on Sequence Types ; XQuery 3.1 (3.18) Expressions on SequenceTypes")
internal inner class ExpressionsOnSequenceTypes {
@Test
@DisplayName("XQuery 3.1 EBNF (92) InstanceofExpr")
fun instanceOfExpr() {
val expr = parse<XPathInstanceofExpr>("1 instance of xs:string")[0] as XpmSequenceTypeExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KInstance))
assertThat(expr.expressionElement?.textOffset, `is`(2))
assertThat(expr.operation, `is`(XpmSequenceTypeOperation.InstanceOf))
assertThat((expr.expression as XsIntegerValue).data, `is`(BigInteger.ONE))
assertThat(expr.type.typeName, `is`("xs:string"))
}
@Test
@DisplayName("XQuery 3.1 EBNF (93) TreatExpr")
fun treatExpr() {
val expr = parse<XPathTreatExpr>("1 treat as xs:string")[0] as XpmSequenceTypeExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KTreat))
assertThat(expr.expressionElement?.textOffset, `is`(2))
assertThat(expr.operation, `is`(XpmSequenceTypeOperation.TreatAs))
assertThat((expr.expression as XsIntegerValue).data, `is`(BigInteger.ONE))
assertThat(expr.type.typeName, `is`("xs:string"))
}
@Test
@DisplayName("XQuery 3.1 EBNF (94) CastableExpr")
fun castableExpr() {
val expr = parse<XPathCastableExpr>("1 castable as xs:string")[0] as XpmSequenceTypeExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KCastable))
assertThat(expr.expressionElement?.textOffset, `is`(2))
assertThat(expr.operation, `is`(XpmSequenceTypeOperation.CastableAs))
assertThat((expr.expression as XsIntegerValue).data, `is`(BigInteger.ONE))
assertThat(expr.type.typeName, `is`("xs:string"))
}
@Nested
@DisplayName("XQuery 3.1 (3.18.2) Typeswitch")
internal inner class Typeswitch {
@Test
@DisplayName("XQuery 3.1 EBNF (74) TypeswitchExpr")
fun typeswitchExpr() {
val expr = parse<XQueryTypeswitchExpr>(
"typeswitch (1) case xs:string return 2 default return 3"
)[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.TYPESWITCH_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (75) CaseClause")
internal inner class CaseClause {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XQueryCaseClause>(
"typeswitch (\$x) case \$y as xs:string return \$z"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`("xs:string"))
assertThat(expr.variableExpression?.text, `is`("\$x"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryCaseClause::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XQueryCaseClause>(
"typeswitch (\$a:x) case \$a:y as xs:string return \$a:z"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`("xs:string"))
assertThat(expr.variableExpression?.text, `is`("\$a:x"))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryCaseClause::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XQueryCaseClause>(
"typeswitch (\$Q{http://www.example.com}x) " +
"case \$Q{http://www.example.com}y as xs:string " +
"return \$Q{http://www.example.com}z"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`("xs:string"))
assertThat(expr.variableExpression?.text, `is`("\$Q{http://www.example.com}x"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XQueryCaseClause::class.java)))
}
@Test
@DisplayName("without VarName")
fun withoutVarName() {
val expr = parse<XQueryCaseClause>(
"typeswitch (2 + 3) case xs:string return \$z"
)[0] as XpmAssignableVariable
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`("xs:string"))
assertThat(expr.variableExpression?.text, `is`("2 + 3"))
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (6) DefaultCaseClause")
internal inner class DefaultCaseClause {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<PluginDefaultCaseClause>(
"typeswitch (\$x) default \$y return \$z"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("\$x"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(PluginDefaultCaseClause::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<PluginDefaultCaseClause>(
"typeswitch (\$a:x) default \$a:y return \$a:z"
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("\$a:x"))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(PluginDefaultCaseClause::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<PluginDefaultCaseClause>(
"""
typeswitch (${'$'}Q{http://www.example.com}x)
default ${'$'}Q{http://www.example.com}y
return ${'$'}Q{http://www.example.com}z
"""
)[0] as XpmAssignableVariable
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("\$Q{http://www.example.com}x"))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("y"))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(PluginDefaultCaseClause::class.java)))
}
@Test
@DisplayName("without VarName")
fun withoutVarName() {
val expr = parse<PluginDefaultCaseClause>(
"typeswitch (\$x) default return \$z"
)[0] as XpmAssignableVariable
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.variableExpression?.text, `is`("\$x"))
}
}
@Test
@DisplayName("XQuery 3.1 EBNF (76) SequenceTypeUnion")
fun sequenceTypeUnion() {
val test = parse<XQuerySequenceTypeUnion>(
"typeswitch (\$x) case \$y as node ( (::) ) | xs:string | array ( * ) return \$y"
)[0]
assertThat(test.isParenthesized, `is`(false))
val type = test as XdmSequenceTypeUnion
assertThat(type.typeName, `is`("node() | xs:string | array(*)"))
val types = type.types.toList()
assertThat(types.size, `is`(3))
assertThat(types[0].typeName, `is`("node()"))
assertThat(types[1].typeName, `is`("xs:string"))
assertThat(types[2].typeName, `is`("array(*)"))
assertThat(type.itemType?.typeName, `is`("item()"))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
}
@Nested
@DisplayName("XQuery 3.1 (3.18.3) Cast")
internal inner class Cast {
@Test
@DisplayName("XQuery 3.1 EBNF (95) CastExpr")
fun castExpr() {
val expr = parse<XPathCastExpr>("1 cast as xs:string")[0] as XpmSequenceTypeExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.KCast))
assertThat(expr.expressionElement?.textOffset, `is`(2))
assertThat(expr.operation, `is`(XpmSequenceTypeOperation.CastAs))
assertThat((expr.expression as XsIntegerValue).data, `is`(BigInteger.ONE))
assertThat(expr.type.typeName, `is`("xs:string"))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (205) SimpleTypeName")
internal inner class SimpleTypeName {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
() cast as test
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultType))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Type))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/element"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("item type")
fun itemType() {
val test = parse<XPathSimpleTypeName>("() cast as xs:string")[0]
assertThat(qname_presentation(test.type), `is`("xs:string"))
val type = test as XdmItemType
assertThat(type.typeName, `is`("xs:string"))
assertThat(type.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(type.itemType, `is`(sameInstance(type)))
assertThat(type.lowerBound, `is`(1))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
}
@Test
@DisplayName("XQuery 3.1 EBNF (182) SingleType")
fun singleType() {
val type = parse<XPathSingleType>("() cast as xs:string ?")[0] as XdmItemType
assertThat(type.typeName, `is`("xs:string?"))
assertThat(type.typeClass, `is`(sameInstance(XsAnyType::class.java)))
assertThat(type.itemType, `is`(sameInstance((type as PsiElement).firstChild)))
assertThat(type.lowerBound, `is`(0))
assertThat(type.upperBound, `is`(Int.MAX_VALUE))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.23) Simple Map Operator ; XQuery 3.1 (3.19) Simple Map Operator")
internal inner class SimpleMapOperator {
@Test
@DisplayName("XQuery 3.1 EBNF (107) SimpleMapExpr")
fun simpleMapExpr() {
val expr = parse<XPathSimpleMapExpr>("/lorem ! fn:abs(.)")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathTokenProvider.MapOperator))
assertThat(expr.expressionElement?.textOffset, `is`(7))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.24) Arrow Expressions ; XQuery 3.1 (3.20) Arrow Operator")
internal inner class ArrowExpressions {
@Nested
@DisplayName("XQuery 3.1 EBNF (96) ArrowExpr")
internal inner class ArrowExpr {
@Test
@DisplayName("XQuery 3.1 EBNF (218) EQName")
fun eqname() {
val expr = parse<XPathArrowExpr>("1 => fn:abs()")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (131) VarRef")
fun varRef() {
val expr = parse<XPathArrowExpr>("let \$x := fn:abs#1 return 1 => \$x()")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("XQuery 3.1 EBNF (133) ParenthesizedExpr")
fun parenthesizedExpr() {
val expr = parse<XPathArrowExpr>("1 => (fn:abs#1)()")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (127) ArrowFunctionSpecifier; XQuery 3.1 EBNF (218) EQName")
internal inner class ArrowFunctionSpecifier_EQName {
@Test
@DisplayName("positional arguments")
fun positionalArguments() {
val f = parse<PluginArrowFunctionCall>("\$x => format-date(1, 2, 3, 4)")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(5))
assertThat(ref.keywordArity, `is`(0))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("format-date"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(4))
assertThat(f.keywordArguments.size, `is`(0))
assertThat(f.positionalArguments[0].text, `is`("1"))
assertThat(f.positionalArguments[1].text, `is`("2"))
assertThat(f.positionalArguments[2].text, `is`("3"))
assertThat(f.positionalArguments[3].text, `is`("4"))
}
@Test
@DisplayName("positional and keyword arguments")
fun positionalAndKeywordArguments() {
val f = parse<PluginArrowFunctionCall>(
"\$x => format-date(1, 2, calendar: 3, place: 4)"
)[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(3))
assertThat(ref.keywordArity, `is`(2))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("format-date"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(2))
assertThat(f.keywordArguments.size, `is`(2))
assertThat(f.positionalArguments[0].text, `is`("1"))
assertThat(f.positionalArguments[1].text, `is`("2"))
assertThat(f.keywordArguments[0].keyName, `is`("calendar"))
assertThat(f.keywordArguments[1].keyName, `is`("place"))
assertThat(f.keywordArguments[0].valueExpression?.text, `is`("3"))
assertThat(f.keywordArguments[1].valueExpression?.text, `is`("4"))
}
@Test
@DisplayName("keyword arguments")
fun keywordArguments() {
val f = parse<PluginArrowFunctionCall>(
"\$x => format-date(picture: 1, language: 2, calendar: 3, place: 4)"
)[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(1))
assertThat(ref.keywordArity, `is`(4))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("format-date"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(0))
assertThat(f.keywordArguments.size, `is`(4))
assertThat(f.keywordArguments[0].keyName, `is`("picture"))
assertThat(f.keywordArguments[1].keyName, `is`("language"))
assertThat(f.keywordArguments[2].keyName, `is`("calendar"))
assertThat(f.keywordArguments[3].keyName, `is`("place"))
assertThat(f.keywordArguments[0].valueExpression?.text, `is`("1"))
assertThat(f.keywordArguments[1].valueExpression?.text, `is`("2"))
assertThat(f.keywordArguments[2].valueExpression?.text, `is`("3"))
assertThat(f.keywordArguments[3].valueExpression?.text, `is`("4"))
}
@Test
@DisplayName("empty arguments")
fun emptyArguments() {
val f = parse<PluginArrowFunctionCall>("\$x => upper-case()")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(1))
assertThat(ref.keywordArity, `is`(0))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("upper-case"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(0))
assertThat(f.keywordArguments.size, `is`(0))
}
@Test
@DisplayName("invalid EQName")
fun invalidEQName() {
val f = parse<PluginArrowFunctionCall>("\$x => :upper-case()")[0] as XpmFunctionCall
assertThat(f.functionCallExpression, sameInstance(f))
val ref = f.functionReference!!
assertThat(ref, sameInstance(f))
assertThat(ref.positionalArity, `is`(1))
assertThat(ref.keywordArity, `is`(0))
assertThat(ref.functionName, `is`(nullValue()))
assertThat(f.positionalArguments.size, `is`(0))
assertThat(f.keywordArguments.size, `is`(0))
}
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathEQName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
() => test()
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultFunctionRef))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.FunctionRef))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/function"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("reference rename")
fun referenceRename() {
val expr = parse<PluginArrowFunctionCall>("1 => test()")[0] as XpmFunctionReference
val ref = (expr.functionName as PsiElement).reference!!
assertThat(ref, `is`(instanceOf(XPathFunctionNameReference::class.java)))
DebugUtil.performPsiModification<Throwable>("rename") {
val renamed = ref.handleElementRename("lorem-ipsum")
assertThat(renamed, `is`(instanceOf(XPathNCName::class.java)))
assertThat(renamed.text, `is`("lorem-ipsum"))
assertThat((renamed as PsiNameIdentifierOwner).name, `is`("lorem-ipsum"))
}
assertThat((expr.functionName as PsiElement).text, `is`("lorem-ipsum"))
}
}
@Test
@DisplayName("XQuery 3.1 EBNF (127) ArrowFunctionSpecifier; XQuery 3.1 EBNF (131) VarRef")
fun arrowFunctionSpecifier_VarRef() {
val f = parse<PluginArrowDynamicFunctionCall>(
"let \$f := format-date#5 return \$x => \$f(1, 2, 3, 4)"
)[0] as XpmArrowFunctionCall
assertThat(f.functionReference, `is`(nullValue())) // TODO: fn:format-date#5
assertThat(f.positionalArguments.size, `is`(4))
assertThat(f.positionalArguments[0].text, `is`("1"))
assertThat(f.positionalArguments[1].text, `is`("2"))
assertThat(f.positionalArguments[2].text, `is`("3"))
assertThat(f.positionalArguments[3].text, `is`("4"))
}
@Test
@DisplayName("XQuery 3.1 EBNF (127) ArrowFunctionSpecifier; XQuery 3.1 EBNF (133) ParenthesizedExpr")
fun arrowFunctionSpecifier_ParenthesizedExpr() {
val f = parse<PluginArrowDynamicFunctionCall>(
"\$x => (format-date#5)(1, 2, 3, 4)"
)[0] as XpmArrowFunctionCall
val ref = f.functionReference!!
assertThat(ref.positionalArity, `is`(5))
assertThat(ref.keywordArity, `is`(0))
val qname = ref.functionName!!
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("format-date"))
assertThat(qname.element, sameInstance(qname as PsiElement))
assertThat(f.positionalArguments.size, `is`(4))
assertThat(f.positionalArguments[0].text, `is`("1"))
assertThat(f.positionalArguments[1].text, `is`("2"))
assertThat(f.positionalArguments[2].text, `is`("3"))
assertThat(f.positionalArguments[3].text, `is`("4"))
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (108) FatArrowTarget ; XQuery 4.0 ED EBNF (142) ArrowStaticFunction")
internal inner class FatArrowTarget_ArrowStaticFunction {
@Test
@DisplayName("single function call")
fun singleFunctionCall() {
val expr = parse<PluginArrowFunctionCall>("1 => fn:abs()")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARROW_FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(5))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Chaining))
assertThat(f.sourceExpression.text, `is`("1"))
}
@Test
@DisplayName("multiple function call; inner")
fun multipleFunctionCallInner() {
val expr = parse<PluginArrowFunctionCall>("1 => fn:abs() => math:pow(2)")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARROW_FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(5))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Chaining))
assertThat(f.sourceExpression.text, `is`("1"))
}
@Test
@DisplayName("multiple function call; outer")
fun multipleFunctionCallOuter() {
val expr = parse<PluginArrowFunctionCall>("1 => fn:abs() => math:pow(2)")[1] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARROW_FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(17))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Chaining))
assertThat(f.sourceExpression.text, `is`("fn:abs()"))
}
@Test
@DisplayName("invalid EQName")
fun invalidEQName() {
val expr = parse<PluginArrowFunctionCall>("1 => :abs()")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARROW_FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(5))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Chaining))
assertThat(f.sourceExpression.text, `is`("1"))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (108) FatArrowTarget ; XQuery 4.0 ED EBNF (143) ArrowDynamicFunction")
internal inner class FatArrowTarget_ArrowDynamicFunction {
@Test
@DisplayName("single function call")
fun singleFunctionCall() {
val expr = parse<PluginArrowDynamicFunctionCall>(
"let \$x := fn:abs#1 return 1 => \$x()"
)[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARGUMENT_LIST))
assertThat(expr.expressionElement?.textOffset, `is`(33))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Chaining))
assertThat(f.sourceExpression.text, `is`("1"))
}
@Test
@DisplayName("multiple function call; inner")
fun multipleFunctionCallInner() {
val expr = parse<PluginArrowDynamicFunctionCall>(
"let \$x := fn:abs#1 let \$y := math:pow#2 return 1 => \$x() => \$y(2)"
)[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARGUMENT_LIST))
assertThat(expr.expressionElement?.textOffset, `is`(54))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Chaining))
assertThat(f.sourceExpression.text, `is`("1"))
}
@Test
@DisplayName("multiple function call; outer")
fun multipleFunctionCallOuter() {
val expr = parse<PluginArrowDynamicFunctionCall>(
"let \$x := fn:abs#1 let \$y := math:pow#2 return 1 => \$x() => \$y(2)"
)[1] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARGUMENT_LIST))
assertThat(expr.expressionElement?.textOffset, `is`(62))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Chaining))
assertThat(f.sourceExpression.text, `is`("\$x()"))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (108) ThinArrowTarget ; XQuery 4.0 ED EBNF (142) ArrowStaticFunction")
internal inner class ThinArrowTarget_ArrowStaticFunction {
@Test
@DisplayName("single function call")
fun singleFunctionCall() {
val expr = parse<PluginArrowFunctionCall>("1 -> fn:abs()")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARROW_FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(5))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Mapping))
assertThat(f.sourceExpression.text, `is`("1"))
}
@Test
@DisplayName("multiple function call; inner")
fun multipleFunctionCallInner() {
val expr = parse<PluginArrowFunctionCall>("1 -> fn:abs() -> math:pow(2)")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARROW_FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(5))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Mapping))
assertThat(f.sourceExpression.text, `is`("1"))
}
@Test
@DisplayName("multiple function call; outer")
fun multipleFunctionCallOuter() {
val expr = parse<PluginArrowFunctionCall>("1 -> fn:abs() -> math:pow(2)")[1] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARROW_FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(17))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Mapping))
assertThat(f.sourceExpression.text, `is`("fn:abs()"))
}
@Test
@DisplayName("invalid EQName")
fun invalidEQName() {
val expr = parse<PluginArrowFunctionCall>("1 -> :abs()")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARROW_FUNCTION_CALL))
assertThat(expr.expressionElement?.textOffset, `is`(5))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Mapping))
assertThat(f.sourceExpression.text, `is`("1"))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (108) ThinArrowTarget ; XQuery 4.0 ED EBNF (143) ArrowDynamicFunction")
internal inner class ThinArrowTarget_ArrowDynamicFunction {
@Test
@DisplayName("single function call")
fun singleFunctionCall() {
val expr = parse<PluginArrowDynamicFunctionCall>(
"let \$x := fn:abs#1 return 1 -> \$x()"
)[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARGUMENT_LIST))
assertThat(expr.expressionElement?.textOffset, `is`(33))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Mapping))
assertThat(f.sourceExpression.text, `is`("1"))
}
@Test
@DisplayName("multiple function call; inner")
fun multipleFunctionCallInner() {
val expr = parse<PluginArrowDynamicFunctionCall>(
"let \$x := fn:abs#1 let \$y := math:pow#2 return 1 -> \$x() -> \$y(2)"
)[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARGUMENT_LIST))
assertThat(expr.expressionElement?.textOffset, `is`(54))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Mapping))
assertThat(f.sourceExpression.text, `is`("1"))
}
@Test
@DisplayName("multiple function call; outer")
fun multipleFunctionCallOuter() {
val expr = parse<PluginArrowDynamicFunctionCall>(
"let \$x := fn:abs#1 let \$y := math:pow#2 return 1 -> \$x() -> \$y(2)"
)[1] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XPathElementType.ARGUMENT_LIST))
assertThat(expr.expressionElement?.textOffset, `is`(62))
val f = expr as XpmArrowFunctionCall
assertThat(f.operation, `is`(XpmArrowOperation.Mapping))
assertThat(f.sourceExpression.text, `is`("\$x()"))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.25) Validate Expressions ; XQuery 3.1 (3.21) Validate Expressions")
internal inner class ValidateExpressions {
@Test
@DisplayName("XQuery 3.1 EBNF (102) ValidateExpr")
fun validateExpr() {
val expr = parse<XQueryValidateExpr>("validate lax { () }")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.VALIDATE_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (4.26) Extension Expressions ; XQuery 3.1 (3.22) Extension Expressions")
internal inner class ExtensionExpressions {
@Test
@DisplayName("XQuery 3.1 EBNF (104) ExtensionExpr")
fun extensionExpr() {
val expr = parse<XQueryExtensionExpr>("(# test #) { () }")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.EXTENSION_EXPR))
assertThat(expr.expressionElement?.textOffset, `is`(0))
}
@Nested
@DisplayName("XQuery 3.1 EBNF (105) Pragma")
internal inner class Pragma {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>("(# test #) {}")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Pragma))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5) Modules and Prologs ; XQuery 3.1 (4) Modules and Prologs")
internal inner class ModulesAndPrologs {
@Nested
@DisplayName("XQuery 3.1 EBNF (1) Module")
internal inner class Module {
@Test
@DisplayName("empty file")
fun emptyFile() {
settings.XQueryVersion = XQuerySpec.REC_3_0_20140408.versionId
val file = parse<XQueryModule>("")[0]
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(nullValue()))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_0_20140408))
settings.XQueryVersion = XQuerySpec.REC_3_1_20170321.versionId
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(nullValue()))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_1_20170321))
}
@Test
@DisplayName("VersionDecl missing")
fun noVersionDecl() {
settings.XQueryVersion = XQuerySpec.REC_3_0_20140408.versionId
val file = parse<XQueryModule>("1234")[0]
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(nullValue()))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_0_20140408))
settings.XQueryVersion = XQuerySpec.REC_3_1_20170321.versionId
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(nullValue()))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_1_20170321))
}
@Test
@DisplayName("VersionDecl with version")
fun versionDeclWithVersion() {
settings.XQueryVersion = XQuerySpec.REC_3_0_20140408.versionId
val file = parse<XQueryModule>("xquery version \"1.0\"; 1234")[0]
val decl = file.descendants().filterIsInstance<XQueryVersionDecl>().first()
assertThat(file.XQueryVersion.version, `is`(XQuerySpec.REC_1_0_20070123))
assertThat(file.XQueryVersion.declaration, `is`(decl.version))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_1_0_20070123))
settings.XQueryVersion = XQuerySpec.REC_3_1_20170321.versionId
assertThat(file.XQueryVersion.version, `is`(XQuerySpec.REC_1_0_20070123))
assertThat(file.XQueryVersion.declaration, `is`(decl.version))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_1_0_20070123))
}
@Test
@DisplayName("VersionDecl with unsupported version")
fun versionDeclWithUnsupportedVersion() {
settings.XQueryVersion = XQuerySpec.REC_3_0_20140408.versionId
val file = parse<XQueryModule>("xquery version \"9.4\"; 1234")[0]
val decl = file.descendants().filterIsInstance<XQueryVersionDecl>().first()
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(decl.version))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_0_20140408))
settings.XQueryVersion = XQuerySpec.REC_3_1_20170321.versionId
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(decl.version))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_1_20170321))
}
@Test
@DisplayName("VersionDecl with empty version")
fun versionDeclWithEmptyVersion() {
settings.XQueryVersion = XQuerySpec.REC_3_0_20140408.versionId
val file = parse<XQueryModule>("xquery version \"\"; 1234")[0]
val decl = file.descendants().filterIsInstance<XQueryVersionDecl>().first()
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(decl.version))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_0_20140408))
settings.XQueryVersion = XQuerySpec.REC_3_1_20170321.versionId
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(decl.version))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_1_20170321))
}
@Test
@DisplayName("VersionDecl with missing version")
fun versionDeclWithMissingVersion() {
settings.XQueryVersion = XQuerySpec.REC_3_0_20140408.versionId
val file = parse<XQueryModule>("xquery; 1234")[0]
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(nullValue()))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_0_20140408))
settings.XQueryVersion = XQuerySpec.REC_3_1_20170321.versionId
assertThat(file.XQueryVersion.version, `is`(nullValue()))
assertThat(file.XQueryVersion.declaration, `is`(nullValue()))
assertThat(file.XQueryVersion.getVersionOrDefault(file.project), `is`(XQuerySpec.REC_3_1_20170321))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (3) MainModule")
internal inner class MainModule {
@Test
@DisplayName("no prolog")
fun noProlog() {
val module = parse<XQueryMainModule>("()")[0]
assertThat((module as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("prolog")
fun prolog() {
val module = parse<XQueryMainModule>("declare function local:func() {}; ()")[0]
val prologs = (module as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
val name = prologs[0].walkTree().filterIsInstance<XPathEQName>().first()
assertThat(name.text, `is`("local:func"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (4) LibraryModule")
internal inner class LibraryModule {
@Test
@DisplayName("no prolog")
fun noProlog() {
val module = parse<XQueryLibraryModule>("module namespace test = \"http://www.example.com\";")[0]
assertThat((module as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("prolog")
fun prolog() {
val module = parse<XQueryLibraryModule>(
"""
module namespace test = "http://www.example.com";
declare function test:func() {};
"""
)[0]
val prologs = (module as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
val name = prologs[0].walkTree().filterIsInstance<XPathEQName>().first()
assertThat(name.text, `is`("test:func"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (38) QueryBody")
internal inner class QueryBody {
@Test
@DisplayName("item presentation")
fun itemPresentation() {
val decl = parse<XQueryQueryBody>("1 div 2")[0]
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XQueryIcons.Nodes.QueryBody)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XQueryIcons.Nodes.QueryBody)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), startsWith("query body ["))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("query body"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("query body"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("query body"))
assertThat(presentation.presentableText, startsWith("query body ["))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("single")
fun single() {
val expr = parse<XQueryQueryBody>("1")[0] as XpmConcatenatingExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.QUERY_BODY))
assertThat(expr.expressionElement?.textOffset, `is`(0))
val exprs = expr.expressions.toList()
assertThat(exprs.size, `is`(1))
assertThat(exprs[0].text, `is`("1"))
}
@Test
@DisplayName("multiple")
fun multiple() {
val expr = parse<XQueryQueryBody>("1, 2 + 3, 4")[0] as XpmConcatenatingExpression
assertThat(expr.expressionElement, `is`(nullValue()))
val exprs = expr.expressions.toList()
assertThat(exprs.size, `is`(3))
assertThat(exprs[0].text, `is`("1"))
assertThat(exprs[1].text, `is`("2 + 3"))
assertThat(exprs[2].text, `is`("4"))
}
@Test
@DisplayName("literal-only expression")
fun literalOnly() {
val expr = parse<XQueryQueryBody>(" 1, 2, 3.5, 4e2, \"test\"")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.QUERY_BODY))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("literal-only parenthesized expression")
fun literalOnlyParenthesized() {
val expr = parse<XQueryQueryBody>(" (1, 2, 3.5, 4e2, \"test\")")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.QUERY_BODY))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("literal-only nested expression")
fun literalOnlyNested() {
val expr = parse<XQueryQueryBody>(" (1, 2, 3.5, (4e2, \"test\"))")[0] as XpmExpression
assertThat(expr.expressionElement.elementType, `is`(XQueryElementType.QUERY_BODY))
assertThat(expr.expressionElement?.textOffset, `is`(2))
}
@Test
@DisplayName("with non-literal sub-expression")
fun nonLiteralSubExpression() {
val expr = parse<XQueryQueryBody>(" (1, 2, (3, 4 + 5))")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
@Test
@DisplayName("with non-literal expression")
fun nonLiteralExpression() {
val expr = parse<XQueryQueryBody>(" 1, 2, 3 + 4")[0] as XpmExpression
assertThat(expr.expressionElement, `is`(nullValue()))
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.1) Version Declaration ; XQuery 3.1 (4.1) Version Declaration")
internal inner class VersionDecl {
@Nested
@DisplayName("XQuery 3.1 EBNF (2) VersionDecl")
internal inner class VersionDecl {
@Test
@DisplayName("no version, no encoding")
fun noVersionOrEncoding() {
val decl = parse<XQueryVersionDecl>("xquery;")[0]
assertThat(decl.version, `is`(nullValue()))
assertThat(decl.encoding, `is`(nullValue()))
}
@Test
@DisplayName("version, no encoding")
fun versionOnly() {
val decl = parse<XQueryVersionDecl>("xquery version \"1.0\";")[0]
assertThat(decl.version!!.data, `is`("1.0"))
assertThat(decl.encoding, `is`(nullValue()))
}
@Test
@DisplayName("no version, encoding")
fun encodingOnly() {
val decl = parse<XQueryVersionDecl>("xquery encoding \"latin1\";")[0]
assertThat(decl.version, `is`(nullValue()))
assertThat(decl.encoding!!.data, `is`("latin1"))
}
@Test
@DisplayName("empty version, no encoding")
fun emptyVersion() {
val decl = parse<XQueryVersionDecl>("xquery version \"\";")[0]
assertThat(decl.version!!.data, `is`(""))
assertThat(decl.encoding, `is`(nullValue()))
}
@Test
@DisplayName("no version, empty encoding")
fun emptyEncoding() {
val decl = parse<XQueryVersionDecl>("xquery encoding \"\";")[0]
assertThat(decl.version, `is`(nullValue()))
assertThat(decl.encoding!!.data, `is`(""))
}
@Test
@DisplayName("version, encoding")
fun versionAndEncoding() {
val decl = parse<XQueryVersionDecl>("xquery version \"1.0\" encoding \"latin1\";")[0]
assertThat(decl.version!!.data, `is`("1.0"))
assertThat(decl.encoding!!.data, `is`("latin1"))
}
@Test
@DisplayName("version, empty encoding")
fun emptyEncodingWithVersion() {
val decl = parse<XQueryVersionDecl>("xquery version \"1.0\" encoding \"\";")[0]
assertThat(decl.version!!.data, `is`("1.0"))
assertThat(decl.encoding!!.data, `is`(""))
}
@Test
@DisplayName("comment before declaration")
fun commentBefore() {
val decl = parse<XQueryVersionDecl>("(: test :)\nxquery version \"1.0\";")[0]
assertThat(decl.version!!.data, `is`("1.0"))
assertThat(decl.encoding, `is`(nullValue()))
}
@Test
@DisplayName("comment as whitespace")
fun commentAsWhitespace() {
val decl = parse<XQueryVersionDecl>("xquery(: A :)version(: B :)\"1.0\"(: C :)encoding(: D :)\"latin1\";")[0]
assertThat(decl.version!!.data, `is`("1.0"))
assertThat(decl.encoding!!.data, `is`("latin1"))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.2) Module Declaration ; XQuery 3.1 (4.2) Module Declaration")
internal inner class ModuleDeclaration {
@Nested
@DisplayName("XQuery 3.1 EBNF (5) ModuleDecl")
internal inner class ModuleDecl {
@Test
@DisplayName("without prolog")
fun withoutProlog() {
val decl = parse<XQueryModuleDecl>("module namespace test = \"http://www.example.com\";")[0] as XpmNamespaceDeclaration
assertThat(decl.namespacePrefix!!.data, `is`("test"))
assertThat(decl.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(decl.namespaceUri!!.context, `is`(XdmUriContext.Namespace))
assertThat(decl.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
assertThat((decl as XQueryPrologResolver).prolog.count(), `is`(0))
val prefix = decl.namespacePrefix?.element?.parent!!
assertThat(prefix.getUsageType(), `is`(XpmUsageType.Namespace))
}
@Test
@DisplayName("with prolog")
fun withProlog() {
val decl = parse<XQueryModuleDecl>("""
module namespace test = "http://www.example.com";
declare function test:func() {};
""")[0] as XpmNamespaceDeclaration
assertThat(decl.namespacePrefix!!.data, `is`("test"))
assertThat(decl.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(decl.namespaceUri!!.context, `is`(XdmUriContext.Namespace))
assertThat(decl.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
val prologs = (decl as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
val name = prologs[0].walkTree().filterIsInstance<XPathEQName>().first()
assertThat(name.text, `is`("test:func"))
}
@Test
@DisplayName("missing namespace prefix")
fun noNamespacePrefix() {
val decl = parse<XQueryModuleDecl>("module namespace = \"http://www.example.com\";")[0] as XpmNamespaceDeclaration
assertThat(decl.namespacePrefix, `is`(nullValue()))
assertThat(decl.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(decl.namespaceUri!!.context, `is`(XdmUriContext.Namespace))
assertThat(decl.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
}
@Test
@DisplayName("missing namespace uri")
fun noNamespaceUri() {
val decl = parse<XQueryModuleDecl>("module namespace test = ;")[0] as XpmNamespaceDeclaration
assertThat(decl.namespacePrefix!!.data, `is`("test"))
assertThat(decl.namespaceUri, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.4) Default Collation Declaration ; XQuery 3.1 (4.4) Default Collation Declaration")
internal inner class DefaultCollationDecl {
@Nested
@DisplayName("XQuery 3.1 EBNF (10) DefaultCollationDecl")
internal inner class DefaultCollationDecl {
@Test
@DisplayName("non-empty collation uri")
fun nonEmptyUri() {
val expr = parse<XQueryDefaultCollationDecl>("declare default collation 'http://www.example.com';")[0]
assertThat(expr.collation!!.data, `is`("http://www.example.com"))
assertThat(expr.collation!!.context, `is`(XdmUriContext.Collation))
assertThat(expr.collation!!.moduleTypes, `is`(sameInstance(XdmModuleType.NONE)))
}
@Test
@DisplayName("missing collation uri")
fun noNamespaceUri() {
val expr = parse<XQueryDefaultCollationDecl>("declare default collation;")[0]
assertThat(expr.collation, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.5) Base URI Declaration ; XQuery 3.1 (4.5) Base URI Declaration")
internal inner class BaseURIDecl {
@Nested
@DisplayName("XQuery 3.1 EBNF (11) BaseURIDecl")
internal inner class BaseURIDecl {
@Test
@DisplayName("non-empty uri")
fun nonEmptyUri() {
val expr = parse<XQueryBaseURIDecl>("declare base-uri 'http://www.example.com';")[0]
assertThat(expr.baseUri!!.data, `is`("http://www.example.com"))
assertThat(expr.baseUri!!.context, `is`(XdmUriContext.BaseUri))
assertThat(expr.baseUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.NONE)))
}
@Test
@DisplayName("missing namespace uri")
fun noNamespaceUri() {
val expr = parse<XQueryBaseURIDecl>("declare base-uri;")[0]
assertThat(expr.baseUri, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.10) Decimal Format Declaration ; XQuery 3.1 (4.10) Decimal Format Declaration")
internal inner class DecimalFormatDeclaration {
@Nested
@DisplayName("XQuery 3.1 EBNF (18) DecimalFormatDecl")
internal inner class DecimalFormatDecl {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>("declare decimal-format test;")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.DecimalFormat))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.11) Schema Import ; XQuery 3.1 (4.11) Schema Import")
internal inner class SchemaImport {
@Nested
@DisplayName("XQuery 3.1 EBNF (21) SchemaImport")
internal inner class SchemaImport {
@Test
@DisplayName("specified namespace prefix and uri")
fun namespacePrefixAndUri() {
val import = parse<XQuerySchemaImport>("import schema namespace test = 'http://www.example.com';")[0] as XpmNamespaceDeclaration
assertThat(import.namespacePrefix!!.data, `is`("test"))
assertThat(import.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(import.namespaceUri!!.context, `is`(XdmUriContext.TargetNamespace))
assertThat(import.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.SCHEMA)))
val uris = (import as XQueryImport).locationUris.toList()
assertThat(uris.size, `is`(0))
assertThat(import.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(import.accepts(XdmNamespaceType.None), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(import.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(import.accepts(XdmNamespaceType.XQuery), `is`(false))
val prefix = import.namespacePrefix?.element?.parent!!
assertThat(prefix.getUsageType(), `is`(XpmUsageType.Namespace))
}
@Test
@DisplayName("missing namespace prefix")
fun noNamespacePrefix() {
val import = parse<XQuerySchemaImport>("import schema namespace = 'http://www.example.com';")[0] as XpmNamespaceDeclaration
assertThat(import.namespacePrefix?.data, `is`(""))
assertThat(import.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(import.namespaceUri!!.context, `is`(XdmUriContext.TargetNamespace))
assertThat(import.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.SCHEMA)))
val uris = (import as XQueryImport).locationUris.toList()
assertThat(uris.size, `is`(0))
assertThat(import.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(import.accepts(XdmNamespaceType.None), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(import.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(import.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("missing namespace uri")
fun noNamespaceUri() {
val import = parse<XQuerySchemaImport>("import schema namespace test = ;")[0] as XpmNamespaceDeclaration
assertThat(import.namespacePrefix!!.data, `is`("test"))
assertThat(import.namespaceUri, `is`(nullValue()))
val uris = (import as XQueryImport).locationUris.toList()
assertThat(uris.size, `is`(0))
assertThat(import.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(import.accepts(XdmNamespaceType.None), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(import.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(import.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("default element namespace")
fun defaultElementNamespace() {
val import = parse<XQuerySchemaImport>("import schema default element namespace 'http://www.example.com';")[0] as XpmNamespaceDeclaration
assertThat(import.namespacePrefix?.data, `is`(""))
assertThat(import.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(import.namespaceUri!!.context, `is`(XdmUriContext.TargetNamespace))
assertThat(import.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.SCHEMA)))
val uris = (import as XQueryImport).locationUris.toList()
assertThat(uris.size, `is`(0))
assertThat(import.accepts(XdmNamespaceType.DefaultElement), `is`(true))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultType), `is`(true))
assertThat(import.accepts(XdmNamespaceType.None), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Prefixed), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(import.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("location uris; single uri")
fun singleLocationUri() {
val import = parse<XQuerySchemaImport>(
"import schema namespace test = 'http://www.example.com' at 'test1.xsd';"
)[0]
val uris = import.locationUris.toList()
assertThat(uris.size, `is`(1))
assertThat(uris[0].data, `is`("test1.xsd"))
assertThat(uris[0].context, `is`(XdmUriContext.Location))
assertThat(uris[0].moduleTypes, `is`(sameInstance(XdmModuleType.SCHEMA)))
}
@Test
@DisplayName("location uris; multiple uris")
fun multipleLocationUris() {
val import = parse<XQuerySchemaImport>(
"import schema namespace test = 'http://www.example.com' at 'test1.xsd' , 'test2.xsd';"
)[0]
val uris = import.locationUris.toList()
assertThat(uris.size, `is`(2))
assertThat(uris[0].data, `is`("test1.xsd"))
assertThat(uris[0].context, `is`(XdmUriContext.Location))
assertThat(uris[0].moduleTypes, `is`(sameInstance(XdmModuleType.SCHEMA)))
assertThat(uris[1].data, `is`("test2.xsd"))
assertThat(uris[1].context, `is`(XdmUriContext.Location))
assertThat(uris[1].moduleTypes, `is`(sameInstance(XdmModuleType.SCHEMA)))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.12) Module Import ; XQuery 3.1 (4.12) Module Import")
internal inner class ModuleImport {
@Nested
@DisplayName("XQuery 3.1 EBNF (23) ModuleImport")
internal inner class ModuleImport {
@Test
@DisplayName("specified namespace prefix and uri")
fun namespacePrefixAndUri() {
val import = parse<XQueryModuleImport>(
"import module namespace test = 'http://www.example.com';"
)[0] as XpmNamespaceDeclaration
assertThat(import.namespacePrefix!!.data, `is`("test"))
assertThat(import.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(import.namespaceUri!!.context, `is`(XdmUriContext.TargetNamespace))
assertThat(import.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
val uris = (import as XQueryImport).locationUris.toList()
assertThat(uris.size, `is`(0))
val prefix = import.namespacePrefix?.element?.parent!!
assertThat(prefix.getUsageType(), `is`(XpmUsageType.Namespace))
assertThat(import.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(import.accepts(XdmNamespaceType.None), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(import.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(import.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("missing namespace prefix NCName")
fun noNamespacePrefixNCName() {
val import = parse<XQueryModuleImport>(
"import module namespace = 'http://www.example.com';"
)[0] as XpmNamespaceDeclaration
assertThat(import.namespacePrefix, `is`(nullValue()))
assertThat(import.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(import.namespaceUri!!.context, `is`(XdmUriContext.TargetNamespace))
assertThat(import.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
val uris = (import as XQueryImport).locationUris.toList()
assertThat(uris.size, `is`(0))
assertThat(import.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(import.accepts(XdmNamespaceType.None), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(import.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(import.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("missing namespace prefix")
fun noNamespacePrefix() {
val import = parse<XQueryModuleImport>(
"import module 'http://www.example.com';"
)[0] as XpmNamespaceDeclaration
assertThat(import.namespacePrefix, `is`(nullValue()))
assertThat(import.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(import.namespaceUri!!.context, `is`(XdmUriContext.TargetNamespace))
assertThat(import.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
val uris = (import as XQueryImport).locationUris.toList()
assertThat(uris.size, `is`(0))
assertThat(import.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(import.accepts(XdmNamespaceType.None), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(import.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(import.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("missing namespace uri")
fun noNamespaceUri() {
val import = parse<XQueryModuleImport>("import module namespace test = ;")[0] as XpmNamespaceDeclaration
assertThat(import.namespacePrefix!!.data, `is`("test"))
assertThat(import.namespaceUri, `is`(nullValue()))
val uris = (import as XQueryImport).locationUris.toList()
assertThat(uris.size, `is`(0))
assertThat(import.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(import.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(import.accepts(XdmNamespaceType.None), `is`(false))
assertThat(import.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(import.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(import.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("location uris; single uri")
fun singleLocationUri() {
val import = parse<XQueryModuleImport>(
"import module namespace test = 'http://www.example.com' at 'test1.xqy';"
)[0]
val uris = import.locationUris.toList()
assertThat(uris.size, `is`(1))
assertThat(uris[0].data, `is`("test1.xqy"))
assertThat(uris[0].context, `is`(XdmUriContext.Location))
assertThat(uris[0].moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
}
@Test
@DisplayName("location uris; multiple uris")
fun multipleLocationUris() {
val import = parse<XQueryModuleImport>(
"import module namespace test = 'http://www.example.com' at 'test1.xqy' , 'test2.xqy';"
)[0]
val uris = import.locationUris.toList()
assertThat(uris.size, `is`(2))
assertThat(uris[0].data, `is`("test1.xqy"))
assertThat(uris[0].context, `is`(XdmUriContext.Location))
assertThat(uris[0].moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
assertThat(uris[1].data, `is`("test2.xqy"))
assertThat(uris[1].context, `is`(XdmUriContext.Location))
assertThat(uris[1].moduleTypes, `is`(sameInstance(XdmModuleType.MODULE)))
}
@Nested
@DisplayName("resolve uri")
internal inner class ResolveUri {
@Test
@DisplayName("empty")
fun empty() {
val file = parseResource("tests/resolve-xquery/files/ModuleImport_URILiteral_Empty.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("same directory")
fun sameDirectory() {
val file = parseResource("tests/resolve-xquery/files/ModuleImport_URILiteral_SameDirectory.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
assertThat(prologs[0].resourcePath(), endsWith("/tests/resolve-xquery/files/test.xq"))
}
@Test
@DisplayName("parent directory")
fun parentDirectory() {
val file = parseResource("tests/resolve-xquery/files/ModuleImport_URILiteral_ParentDirectory.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
assertThat(prologs[0].resourcePath(), endsWith("/tests/module-xquery/namespaces/ModuleDecl.xq"))
}
@Test
@DisplayName("module in relative directory")
fun moduleInRelativeDirectory() {
val file = parseResource("tests/resolve-xquery/ModuleImport_URILiteral_InDirectory.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
assertThat(prologs[0].resourcePath(), endsWith("/tests/module-xquery/namespaces/ModuleDecl.xq"))
}
@Test
@DisplayName("http:// file matching")
fun httpProtocol() {
val file = parseResource("tests/resolve-xquery/files/ModuleImport_URILiteral_HttpProtocol.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
assertThat(prologs[0].resourcePath(), endsWith("/org/w3/www/2005/xpath-functions/array.xqy"))
}
@Test
@DisplayName("http:// file missing")
fun httpProtocolMissing() {
val file = parseResource("tests/resolve-xquery/files/ModuleImport_URILiteral_HttpProtocol_FileNotFound.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("http:// (import namespace) file matching")
fun httpProtocolOnNamespace() {
val file = parseResource("tests/resolve-xquery/files/ModuleImport_NamespaceOnly.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
assertThat(prologs[0].resourcePath(), endsWith("/org/w3/www/2005/xpath-functions/array.xqy"))
}
@Test
@DisplayName("http:// (import namespace) file missing")
fun httpProtocolOnNamespaceMissing() {
val file = parseResource("tests/resolve-xquery/files/ModuleImport_NamespaceOnly_FileNotFound.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("multiple location URIs")
fun multipleLocationUris() {
val file = parseResource("tests/resolve-xquery/files/ModuleImport_URILiteral_MultipleLocationUris.xq")
val psi = file.walkTree().filterIsInstance<XQueryModuleImport>().toList()[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(2))
assertThat(prologs[0].resourcePath(), endsWith("/tests/resolve-xquery/files/test.xq"))
assertThat(prologs[1].resourcePath(), endsWith("/tests/resolve-xquery/files/test2.xq"))
}
@Test
@DisplayName("module root")
fun moduleRoot() {
val psi = parse<XQueryModuleImport>(
"""
import module "http://example.com/test" at "/files/test.xq";
()
"""
)[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
assertThat(prologs[0].resourcePath(), endsWith("/tests/module-xquery/files/test.xq"))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.13) Namespace Declaration ; XQuery 3.1 (4.13) Namespace Declaration")
internal inner class NamespaceDeclaration {
@Nested
@DisplayName("XQuery 3.1 EBNF (24) NamespaceDecl")
internal inner class NamespaceDecl {
@Test
@DisplayName("specified namespace prefix and uri")
fun namespacePrefixAndUri() {
val decl = parse<XQueryNamespaceDecl>("declare namespace test = 'http://www.example.com';")[0] as XpmNamespaceDeclaration
assertThat(decl.namespacePrefix!!.data, `is`("test"))
assertThat(decl.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(decl.namespaceUri!!.context, `is`(XdmUriContext.NamespaceDeclaration))
assertThat(decl.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
val prefix = decl.namespacePrefix?.element?.parent!!
assertThat(prefix.getUsageType(), `is`(XpmUsageType.Namespace))
assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.None), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("missing namespace prefix")
fun noNamespacePrefix() {
val decl = parse<XQueryNamespaceDecl>("declare namespace = 'http://www.example.com';")[0] as XpmNamespaceDeclaration
assertThat(decl.namespacePrefix, `is`(nullValue()))
assertThat(decl.namespaceUri!!.data, `is`("http://www.example.com"))
assertThat(decl.namespaceUri!!.context, `is`(XdmUriContext.NamespaceDeclaration))
assertThat(decl.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.None), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("missing namespace uri")
fun noNamespaceUri() {
val decl = parse<XQueryNamespaceDecl>("declare namespace test = ;")[0] as XpmNamespaceDeclaration
assertThat(decl.namespacePrefix!!.data, `is`("test"))
assertThat(decl.namespaceUri, `is`(nullValue()))
assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.None), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Nested
@DisplayName("resolve uri")
internal inner class ResolveUri {
@Test
@DisplayName("empty")
fun empty() {
val file = parseResource("tests/resolve-xquery/files/NamespaceDecl_Empty.xq")
val psi = file.walkTree().filterIsInstance<XQueryNamespaceDecl>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("same directory")
fun sameDirectory() {
val file = parseResource("tests/resolve-xquery/files/NamespaceDecl_SameDirectory.xq")
val psi = file.walkTree().filterIsInstance<XQueryNamespaceDecl>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
@Test
@DisplayName("http:// file matching")
fun httpProtocol() {
val file = parseResource("tests/resolve-xquery/files/NamespaceDecl_HttpProtocol.xq")
val psi = file.walkTree().filterIsInstance<XQueryNamespaceDecl>().toList()[0]
val prologs = (psi as XQueryPrologResolver).prolog.toList()
assertThat(prologs.size, `is`(1))
assertThat(prologs[0].resourcePath(), endsWith("/org/w3/www/2005/xpath-functions/array.xqy"))
}
@Test
@DisplayName("http:// file missing")
fun httpProtocolMissing() {
val file = parseResource("tests/resolve-xquery/files/NamespaceDecl_HttpProtocol_FileNotFound.xq")
val psi = file.walkTree().filterIsInstance<XQueryNamespaceDecl>().toList()[0]
assertThat((psi as XQueryPrologResolver).prolog.count(), `is`(0))
}
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.14) Default Namespace Declaration ; XQuery 3.1 (4.14) Default Namespace Declaration")
internal inner class DefaultNamespaceDeclaration {
@Nested
@DisplayName("XQuery 3.1 EBNF (25) DefaultNamespaceDecl")
internal inner class DefaultNamespaceDecl {
@Test
@DisplayName("default element/type namespace declaration")
fun element() {
val decl = parse<XpmNamespaceDeclaration>(
"declare default element namespace 'http://www.w3.org/1999/xhtml';"
)[0]
assertThat(decl.namespacePrefix?.data, `is`(""))
assertThat(decl.namespaceUri?.data, `is`("http://www.w3.org/1999/xhtml"))
assertThat(decl.namespaceUri?.context, `is`(XdmUriContext.Namespace))
assertThat(decl.namespaceUri?.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.None), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("default function namespace declaration")
fun function() {
val decl = parse<XpmNamespaceDeclaration>(
"declare default function namespace 'http://www.w3.org/2005/xpath-functions/math';"
)[0]
assertThat(decl.namespacePrefix?.data, `is`(""))
assertThat(decl.namespaceUri?.data, `is`("http://www.w3.org/2005/xpath-functions/math"))
assertThat(decl.namespaceUri?.context, `is`(XdmUriContext.Namespace))
assertThat(decl.namespaceUri?.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.None), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("empty namespace")
fun emptyNamespace() {
val decl = parse<XpmNamespaceDeclaration>("declare default element namespace '';")[0]
assertThat(decl.namespacePrefix?.data, `is`(""))
assertThat(decl.namespaceUri!!.data, `is`(""))
assertThat(decl.namespaceUri!!.context, `is`(XdmUriContext.Namespace))
assertThat(decl.namespaceUri!!.moduleTypes, `is`(sameInstance(XdmModuleType.MODULE_OR_SCHEMA)))
assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.None), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false))
}
@Test
@DisplayName("missing namespace")
fun missingNamespace() {
val decl = parse<XpmNamespaceDeclaration>("declare default element namespace;")[0]
assertThat(decl.namespacePrefix?.data, `is`(""))
assertThat(decl.namespaceUri, `is`(nullValue()))
assertThat(decl.accepts(XdmNamespaceType.DefaultElement), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionDecl), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultFunctionRef), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.DefaultType), `is`(true))
assertThat(decl.accepts(XdmNamespaceType.None), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Prefixed), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.Undefined), `is`(false))
assertThat(decl.accepts(XdmNamespaceType.XQuery), `is`(false))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.15) Annotations ; XQuery 3.1 (4.15) Annotations")
internal inner class Annotations {
@Nested
@DisplayName("XQuery 3.1 EBNF (27) Annotation")
internal inner class Annotation {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>("declare function %test f() {};")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.XQuery))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Annotation))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.w3.org/2012/xquery"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
@Test
@DisplayName("name only")
fun nameOnly() {
val annotation = parse<XQueryAnnotation>("declare % private function f() {};")[0] as XdmAnnotation
assertThat(qname_presentation(annotation.name!!), `is`("private"))
val values = annotation.values.toList()
assertThat(values.size, `is`(0))
val presentation = annotation as ItemPresentation
assertThat(presentation.getIcon(false), `is`(XQueryIcons.Nodes.Annotation))
assertThat(presentation.locationString, `is`(nullValue()))
assertThat(presentation.presentableText, `is`("%private"))
}
@Test
@DisplayName("missing name")
fun missingName() {
val annotation = parse<XQueryAnnotation>("declare % () {};")[0] as XdmAnnotation
assertThat(annotation.name, `is`(nullValue()))
val values = annotation.values.toList()
assertThat(values.size, `is`(0))
val presentation = annotation as ItemPresentation
assertThat(presentation.getIcon(false), `is`(XQueryIcons.Nodes.Annotation))
assertThat(presentation.locationString, `is`(nullValue()))
assertThat(presentation.presentableText, `is`(nullValue()))
}
@Test
@DisplayName("values")
fun values() {
val annotation = parse<XQueryAnnotation>("declare % test ( 1 , 2.3 , 4e3 , 'lorem ipsum' ) function f() {};")[0] as XdmAnnotation
assertThat(qname_presentation(annotation.name!!), `is`("test"))
val values = annotation.values.toList()
assertThat(values.size, `is`(4))
assertThat((values[0] as XsIntegerValue).data, `is`(BigInteger.ONE))
assertThat((values[1] as XsDecimalValue).data, `is`(BigDecimal.valueOf(2.3)))
assertThat((values[2] as XsDoubleValue).data, `is`(4e3))
assertThat((values[3] as XsStringValue).data, `is`("lorem ipsum"))
val presentation = annotation as ItemPresentation
assertThat(presentation.getIcon(false), `is`(XQueryIcons.Nodes.Annotation))
assertThat(presentation.locationString, `is`(nullValue()))
assertThat(presentation.presentableText, `is`("%test(1, 2.3, 4e3, 'lorem ipsum')"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (28) VarDecl")
internal inner class VarDecl {
fun useScope(element: XpmAnnotated): String = when (val scope = (element as PsiElement).useScope) {
is LocalSearchScope -> "LocalSearchScope(${scope.scope.joinToString { it.javaClass.simpleName }})"
is GlobalSearchScope -> "GlobalSearchScope"
else -> scope.javaClass.simpleName
}
@Test
@DisplayName("no annotations")
fun none() {
val decl = parse<XpmAnnotated>("declare variable \$v := 2;")[0]
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(0))
}
@Test
@DisplayName("single annotation")
fun single() {
val decl = parse<XpmAnnotated>("declare %private variable \$v := 2;")[0]
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(1))
assertThat(qname_presentation(annotations[0].name!!), `is`("private"))
}
@Test
@DisplayName("multiple annotations")
fun multiple() {
val decl = parse<XpmAnnotated>("declare %public %private variable \$v := 2;")[0]
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(2))
assertThat(qname_presentation(annotations[0].name!!), `is`("public"))
assertThat(qname_presentation(annotations[1].name!!), `is`("private"))
}
@Test
@DisplayName("visibility (%public/%private)")
fun visibility() {
val decls = parse<XpmAnnotated>(
"""
declare variable ${'$'}a := 1;
declare %public variable ${'$'}b := 2;
declare %private variable ${'$'}c := 3;
""".trimIndent()
)
assertThat(decls[0].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(decls[1].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(decls[2].accessLevel, `is`(XpmAccessLevel.Private))
assertThat(useScope(decls[0]), `is`("GlobalSearchScope"))
assertThat(useScope(decls[1]), `is`("GlobalSearchScope"))
assertThat(useScope(decls[2]), `is`("LocalSearchScope(XQueryModuleImpl)"))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (32) FunctionDecl")
internal inner class FunctionDecl {
@Test
@DisplayName("no annotation")
fun none() {
val decl = parse<XpmAnnotated>("declare function f() {};")[0]
assertThat(decl.accessLevel, `is`(XpmAccessLevel.Public))
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(0))
}
@Test
@DisplayName("single annotation")
fun single() {
val decl = parse<XpmAnnotated>("declare %private function f() {};")[0]
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(1))
assertThat(qname_presentation(annotations[0].name!!), `is`("private"))
}
@Test
@DisplayName("multiple annotations")
fun multiple() {
val decl = parse<XpmAnnotated>("declare %public %private function f() {};")[0]
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(2))
assertThat(qname_presentation(annotations[0].name!!), `is`("public"))
assertThat(qname_presentation(annotations[1].name!!), `is`("private"))
}
@Test
@DisplayName("visibility (%public/%private)")
fun visibility() {
val decls = parse<XpmAnnotated>(
"""
declare function a() {};
declare %public function b() {};
declare %private function c() {};
""".trimIndent()
)
assertThat(decls[0].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(decls[1].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(decls[2].accessLevel, `is`(XpmAccessLevel.Private))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (169) InlineFunctionExpr")
internal inner class InlineFunctionExpr {
@Test
@DisplayName("no annotation")
fun none() {
val expr = parse<XpmAnnotated>("function() {};")[0]
assertThat(expr.accessLevel, `is`(XpmAccessLevel.Public))
val annotations = expr.annotations.toList()
assertThat(annotations.size, `is`(0))
}
@Test
@DisplayName("single annotation")
fun single() {
val expr = parse<XpmAnnotated>("%private function() {};")[0]
val annotations = expr.annotations.toList()
assertThat(annotations.size, `is`(1))
assertThat(qname_presentation(annotations[0].name!!), `is`("private"))
}
@Test
@DisplayName("multiple annotations")
fun multiple() {
val expr = parse<XpmAnnotated>("%public %private function() {};")[0]
val annotations = expr.annotations.toList()
assertThat(annotations.size, `is`(2))
assertThat(qname_presentation(annotations[0].name!!), `is`("public"))
assertThat(qname_presentation(annotations[1].name!!), `is`("private"))
}
@Test
@DisplayName("visibility (%public/%private)")
fun visibility() {
val exprs = parse<XpmAnnotated>(
"""
function() {},
%public function() {},
%private function() {}
""".trimIndent()
)
assertThat(exprs[0].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(exprs[1].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(exprs[2].accessLevel, `is`(XpmAccessLevel.Private))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (207) FunctionTest ; XQuery 3.1 EBNF (208) AnyFunctionTest")
internal inner class AnyFunctionTest {
@Test
@DisplayName("no annotations")
fun none() {
val test = parse<XpmAnnotated>("1 instance of function(*)")[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(0))
}
@Test
@DisplayName("single annotation")
fun single() {
val test = parse<XpmAnnotated>("1 instance of %private function(*)")[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(1))
assertThat(qname_presentation(annotations[0].name!!), `is`("private"))
}
@Test
@DisplayName("multiple annotations")
fun multiple() {
val test = parse<XpmAnnotated>("1 instance of %public %private function(*)")[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(2))
assertThat(qname_presentation(annotations[0].name!!), `is`("public"))
assertThat(qname_presentation(annotations[1].name!!), `is`("private"))
}
@Test
@DisplayName("visibility (%public/%private)")
fun visibility() {
val tests = parse<XpmAnnotated>(
"""
1 instance of function(*),
1 instance of %public function(*),
1 instance of %private function(*)
""".trimIndent()
)
assertThat(tests[0].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(tests[1].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(tests[2].accessLevel, `is`(XpmAccessLevel.Private))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (207) FunctionTest ; XQuery 3.1 EBNF (209) TypedFunctionTest")
internal inner class TypedFunctionTest {
@Test
@DisplayName("no annotations")
fun none() {
val test = parse<XpmAnnotated>("1 instance of function(item()) as item()")[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(0))
}
@Test
@DisplayName("single annotation")
fun single() {
val test = parse<XpmAnnotated>("1 instance of %private function(item()) as item()")[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(1))
assertThat(qname_presentation(annotations[0].name!!), `is`("private"))
}
@Test
@DisplayName("multiple annotations")
fun multiple() {
val test = parse<XpmAnnotated>("1 instance of %public %private function(item()) as item()")[0]
val annotations = test.annotations.toList()
assertThat(annotations.size, `is`(2))
assertThat(qname_presentation(annotations[0].name!!), `is`("public"))
assertThat(qname_presentation(annotations[1].name!!), `is`("private"))
}
@Test
@DisplayName("visibility (%public/%private)")
fun visibility() {
val tests = parse<XpmAnnotated>(
"""
1 instance of function(item()) as item(),
1 instance of %public function(item()) as item(),
1 instance of %private function(item()) as item()
""".trimIndent()
)
assertThat(tests[0].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(tests[1].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(tests[2].accessLevel, `is`(XpmAccessLevel.Private))
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (38) ItemTypeDecl")
internal inner class ItemTypeDecl {
@Test
@DisplayName("no annotation")
fun none() {
val decl = parse<XpmAnnotated>("declare item-type test as item();")[0]
assertThat(decl.accessLevel, `is`(XpmAccessLevel.Public))
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(0))
}
@Test
@DisplayName("single annotation")
fun single() {
val decl = parse<XpmAnnotated>("declare %private item-type test as item();")[0]
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(1))
assertThat(qname_presentation(annotations[0].name!!), `is`("private"))
}
@Test
@DisplayName("multiple annotations")
fun multiple() {
val decl = parse<XpmAnnotated>("declare %public %private item-type test as item();")[0]
val annotations = decl.annotations.toList()
assertThat(annotations.size, `is`(2))
assertThat(qname_presentation(annotations[0].name!!), `is`("public"))
assertThat(qname_presentation(annotations[1].name!!), `is`("private"))
}
@Test
@DisplayName("visibility (%public/%private)")
fun visibility() {
val decls = parse<XpmAnnotated>(
"""
declare item-type a as item();
declare %public item-type b as item();
declare %private item-type c as item();
""".trimIndent()
)
assertThat(decls[0].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(decls[1].accessLevel, `is`(XpmAccessLevel.Public))
assertThat(decls[2].accessLevel, `is`(XpmAccessLevel.Private))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.16) Variable Declaration ; XQuery 3.1 (4.16) Variable Declaration")
internal inner class VariableDeclaration {
@Nested
@DisplayName("XQuery 3.1 EBNF (28) VarDecl")
internal inner class VarDecl {
@Test
@DisplayName("NCName")
fun ncname() {
val decl = parse<XpmVariableDeclaration>("declare variable \$x := \$y;")[0]
assertThat(decl.isExternal, `is`(false))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
assertThat(decl.variableExpression?.text, `is`("\$y"))
val qname = decl.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`("x"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("QName")
fun qname() {
val decl = parse<XpmVariableDeclaration>("declare variable \$a:x := \$a:y;")[0]
assertThat(decl.isExternal, `is`(false))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
assertThat(decl.variableExpression?.text, `is`("\$a:y"))
val qname = decl.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`("a:x"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val decl = parse<XpmVariableDeclaration>(
"declare variable \$Q{http://www.example.com}x := \$Q{http://www.example.com}y;"
)[0]
assertThat(decl.isExternal, `is`(false))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
assertThat(decl.variableExpression?.text, `is`("\$Q{http://www.example.com}y"))
val qname = decl.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`("Q{http://www.example.com}x"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("with CompatibilityAnnotation")
fun withCompatibilityAnnotation() {
val decl = parse<XpmVariableDeclaration>("declare private variable \$a:x := \$a:y;")[0]
assertThat(decl.isExternal, `is`(false))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
assertThat(decl.variableExpression?.text, `is`("\$a:y"))
val qname = decl.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`("a:x"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val decl = parse<XpmVariableDeclaration>("declare variable \$ := \$y;")[0]
assertThat(decl.isExternal, `is`(false))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
assertThat(decl.variableExpression?.text, `is`("\$y"))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`(nullValue()))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("invalid VarName")
fun invalidVarName() {
val decl = parse<XpmVariableDeclaration>("declare variable \$: := \$y;")[0]
assertThat(decl.isExternal, `is`(false))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
assertThat(decl.variableExpression?.text, `is`("\$y"))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`(nullValue()))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("with type")
fun withType() {
val decl = parse<XpmVariableDeclaration>("declare variable \$a:x as node ( (::) )? := \$a:y;")[0]
assertThat(decl.isExternal, `is`(false))
assertThat(decl.variableType?.typeName, `is`("node()?"))
assertThat(decl.variableExpression?.text, `is`("\$a:y"))
val qname = decl.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`("a:x as node()?"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("external without default")
fun externalWithoutDefault() {
val decl = parse<XpmVariableDeclaration>("declare variable \$x external;")[0]
assertThat(decl.isExternal, `is`(true))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
assertThat(decl.variableExpression, `is`(nullValue()))
val qname = decl.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`("x"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("external with default")
fun externalWithDefault() {
val decl = parse<XpmVariableDeclaration>("declare variable \$x external := \$y;")[0]
assertThat(decl.isExternal, `is`(true))
assertThat(decl.variableType?.typeName, `is`(nullValue()))
assertThat(decl.variableExpression?.text, `is`("\$y"))
val qname = decl.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (decl as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.VarDecl)))
assertThat(presentation.presentableText, `is`("x"))
assertThat(presentation.locationString, `is`(nullValue()))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.18) Function Declaration ; XQuery 3.1 (4.18) Function Declaration")
internal inner class FunctionDeclaration {
@Nested
@DisplayName("XQuery 3.1 EBNF (32) FunctionDecl")
internal inner class FunctionDecl {
@Test
@DisplayName("empty ParamList")
fun emptyParamList() {
val decl = parse<XpmFunctionDeclaration>("declare function fn:true() external;")[0]
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody, `is`(nullValue()))
val qname = decl.functionName!!
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("fn:true()"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("fn:true()"))
assertThat(presentation.presentableText, `is`("fn:true"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("non-empty ParamList")
fun nonEmptyParamList() {
val decl = parse<XpmFunctionDeclaration>("declare function test(\$one, \$two) external;")[0]
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.functionBody, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(2))
assertThat(qname_presentation(decl.parameters[0].variableName!!), `is`("one"))
assertThat(qname_presentation(decl.parameters[1].variableName!!), `is`("two"))
val qname = decl.functionName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`("test"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("test(\$one, \$two)"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("test"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("test(\$one, \$two)"))
assertThat(presentation.presentableText, `is`("test"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("non-empty ParamList with types")
fun nonEmptyParamListWithTypes() {
val decl = parse<XpmFunctionDeclaration>("declare function test(\$one as array ( * ), \$two as node((::))) external;")[0]
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.functionBody, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(2))
assertThat(qname_presentation(decl.parameters[0].variableName!!), `is`("one"))
assertThat(qname_presentation(decl.parameters[1].variableName!!), `is`("two"))
val qname = decl.functionName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`("test"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("test(\$one as array(*), \$two as node())"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("test"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("test(\$one as array(*), \$two as node())"))
assertThat(presentation.presentableText, `is`("test"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("return type")
fun returnType() {
val decl = parse<XpmFunctionDeclaration>("declare function fn:true() as xs:boolean external;")[0]
assertThat(decl.returnType?.typeName, `is`("xs:boolean"))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody, `is`(nullValue()))
val qname = decl.functionName!!
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("fn:true() as xs:boolean"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("fn:true() as xs:boolean"))
assertThat(presentation.presentableText, `is`("fn:true"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("invalid EQName")
fun invalidEQName() {
val decl = parse<XpmFunctionDeclaration>("declare function :true() external;")[0]
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.functionName, `is`(nullValue()))
assertThat(decl.functionBody, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(0))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`(nullValue()))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`(nullValue()))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`(nullValue()))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`(nullValue()))
assertThat(presentation.presentableText, `is`(nullValue()))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("invalid local name")
fun invalidLocalName() {
// e.g. MarkLogic's roxy framework has template files declaring 'c:#function-name'.
val decl = parse<XpmFunctionDeclaration>("declare function fn:() external;")[0]
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody, `is`(nullValue()))
val qname = decl.functionName!!
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName, `is`(nullValue()))
assertThat(qname.element, sameInstance(qname as PsiElement))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`(nullValue()))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`(nullValue()))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`(nullValue()))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`(nullValue()))
assertThat(presentation.presentableText, `is`(nullValue()))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("with CompatibilityAnnotation")
fun withCompatibilityAnnotation() {
val decl = parse<XpmFunctionDeclaration>("declare private function fn:true() external;")[0]
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody, `is`(nullValue()))
val qname = decl.functionName!!
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("fn:true()"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("fn:true()"))
assertThat(presentation.presentableText, `is`("fn:true"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("empty function body")
fun emptyFunctionBody() {
val decl = parse<XpmFunctionDeclaration>("declare function fn:true() {};")[0]
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody, sameInstance(XpmEmptyExpression))
val qname = decl.functionName!!
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("fn:true()"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("fn:true()"))
assertThat(presentation.presentableText, `is`("fn:true"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("function body expression")
fun functionBodyExpression() {
val decl = parse<XpmFunctionDeclaration>("declare function fn:true() { \"1\" cast as xs:boolean };")[0]
assertThat(decl.returnType, `is`(nullValue()))
assertThat(decl.parameters.size, `is`(0))
assertThat(decl.functionBody?.text, `is`("\"1\" cast as xs:boolean "))
val qname = decl.functionName!!
assertThat(qname.prefix!!.data, `is`("fn"))
assertThat(qname.localName!!.data, `is`("true"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val presentation = (decl as NavigationItem).presentation!! as ItemPresentationEx
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.FunctionDecl)))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.Default), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.StructureView), `is`("fn:true()"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBar), `is`("fn:true"))
assertThat(presentation.getPresentableText(ItemPresentationEx.Type.NavBarPopup), `is`("fn:true()"))
assertThat(presentation.presentableText, `is`("fn:true"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>(
"""
declare default function namespace "http://www.example.co.uk/function";
declare default element namespace "http://www.example.co.uk/element";
declare function test() {};
"""
)[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.DefaultFunctionDecl))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.FunctionDecl))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.example.co.uk/function"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
@Nested
@DisplayName("XQuery 3.1 EBNF (34) Param")
internal inner class Param {
@Test
@DisplayName("NCName")
fun ncname() {
val expr = parse<XPathParam>("function (\$x) {}")[0] as XpmParameter
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.defaultExpression, `is`(nullValue()))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (expr as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.presentableText, `is`("\$x"))
assertThat(presentation.locationString, `is`(nullValue()))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XPathInlineFunctionExpr::class.java)))
}
@Test
@DisplayName("QName")
fun qname() {
val expr = parse<XPathParam>("function (\$a:x) {}")[0] as XpmParameter
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.defaultExpression, `is`(nullValue()))
val qname = expr.variableName!!
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix!!.data, `is`("a"))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (expr as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.presentableText, `is`("\$a:x"))
assertThat(presentation.locationString, `is`(nullValue()))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XPathInlineFunctionExpr::class.java)))
}
@Test
@DisplayName("URIQualifiedName")
fun uriQualifiedName() {
val expr = parse<XPathParam>("function (\$Q{http://www.example.com}x) {}")[0] as XpmParameter
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.defaultExpression, `is`(nullValue()))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace!!.data, `is`("http://www.example.com"))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (expr as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.presentableText, `is`("\$Q{http://www.example.com}x"))
assertThat(presentation.locationString, `is`(nullValue()))
val localScope = expr.variableName?.element?.useScope as LocalSearchScope
assertThat(localScope.scope.size, `is`(1))
assertThat(localScope.scope[0], `is`(instanceOf(XPathInlineFunctionExpr::class.java)))
}
@Test
@DisplayName("missing VarName")
fun missingVarName() {
val expr = parse<XPathParam>("function (\$) {}")[0] as XpmParameter
assertThat(expr.variableName, `is`(nullValue()))
assertThat(expr.variableType?.typeName, `is`(nullValue()))
assertThat(expr.defaultExpression, `is`(nullValue()))
val presentation = (expr as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.presentableText, `is`(nullValue()))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("with type")
fun withType() {
val expr = parse<XPathParam>("function ( \$x as element() ) {}")[0] as XpmParameter
assertThat(expr.variableType?.typeName, `is`("element()"))
assertThat(expr.defaultExpression, `is`(nullValue()))
val qname = expr.variableName!!
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("x"))
val presentation = (expr as NavigationItem).presentation!!
assertThat(presentation.getIcon(false), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.getIcon(true), `is`(sameInstance(XPathIcons.Nodes.Param)))
assertThat(presentation.presentableText, `is`("\$x as element()"))
assertThat(presentation.locationString, `is`(nullValue()))
}
@Test
@DisplayName("NCName namespace resolution")
fun ncnameNamespaceResolution() {
val qname = parse<XPathEQName>("function (\$test) {}")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.None))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Parameter))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`(""))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED (5.20) Option Declaration ; XQuery 3.1 (4.19) Option Declaration")
internal inner class OptionDeclaration {
@Nested
@DisplayName("XQuery 3.1 EBNF (37) OptionDecl")
internal inner class OptionDecl {
@Test
@DisplayName("NCName namespace resolution")
fun ncname() {
val qname = parse<XPathNCName>("declare option test \"lorem ipsum\";")[0] as XsQNameValue
assertThat(qname.getNamespaceType(), `is`(XdmNamespaceType.XQuery))
assertThat(qname.element!!.getUsageType(), `is`(XpmUsageType.Option))
assertThat(qname.isLexicalQName, `is`(true))
assertThat(qname.namespace, `is`(nullValue()))
assertThat(qname.prefix, `is`(nullValue()))
assertThat(qname.localName!!.data, `is`("test"))
assertThat(qname.element, sameInstance(qname as PsiElement))
val expanded = qname.expand().toList()
assertThat(expanded.size, `is`(1))
assertThat(expanded[0].isLexicalQName, `is`(false))
assertThat(expanded[0].namespace!!.data, `is`("http://www.w3.org/2012/xquery"))
assertThat(expanded[0].prefix, `is`(nullValue()))
assertThat(expanded[0].localName!!.data, `is`("test"))
assertThat(expanded[0].element, sameInstance(qname as PsiElement))
}
}
}
}
}
| apache-2.0 |
michaldrabik/KotlinMVP | app/src/main/java/com/michaldrabik/kotlintest/data/model/Response.kt | 1 | 113 | package com.michaldrabik.kotlintest.data.model
data class Response<out T>(val type: String, val value: List<T>)
| apache-2.0 |
rhdunn/xquery-intellij-plugin | src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/text/Units.kt | 1 | 1305 | /*
* Copyright (C) 2019 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.core.text
import java.text.NumberFormat
object Units {
private fun numberFormat(min: Int, max: Int): NumberFormat {
val nf = NumberFormat.getInstance()
nf.minimumFractionDigits = min
nf.maximumFractionDigits = max
return nf
}
@Suppress("unused")
object Precision {
val milli: NumberFormat = numberFormat(0, 3)
val micro: NumberFormat = numberFormat(3, 6)
val nano: NumberFormat = numberFormat(6, 9)
val milliWithZeros: NumberFormat = numberFormat(3, 3)
val microWithZeros: NumberFormat = numberFormat(6, 6)
val nanoWithZeros: NumberFormat = numberFormat(9, 9)
}
}
| apache-2.0 |
mitallast/netty-queue | src/main/java/org/mitallast/queue/raft/protocol/LogEntry.kt | 1 | 581 | package org.mitallast.queue.raft.protocol
import org.mitallast.queue.common.codec.Codec
import org.mitallast.queue.common.codec.Message
data class LogEntry(val term: Long, val index: Long, val session: Long, val command: Message) : Message {
companion object {
val codec = Codec.of(
::LogEntry,
LogEntry::term,
LogEntry::index,
LogEntry::session,
LogEntry::command,
Codec.longCodec(),
Codec.longCodec(),
Codec.longCodec(),
Codec.anyCodec()
)
}
}
| mit |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CataloguePresenter.kt | 1 | 3789 | package eu.kanade.tachiyomi.ui.catalogue
import android.os.Bundle
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Presenter of [CatalogueController]
* Function calls should be done from here. UI calls should be done from the controller.
*
* @param sourceManager manages the different sources.
* @param preferences application preferences.
*/
class CataloguePresenter(
val sourceManager: SourceManager = Injekt.get(),
private val preferences: PreferencesHelper = Injekt.get(),
private val controllerMode: CatalogueController.Mode
) : BasePresenter<CatalogueController>() {
/**
* Enabled sources.
*/
var sources = getEnabledSources()
/**
* Subscription for retrieving enabled sources.
*/
private var sourceSubscription: Subscription? = null
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
// Load enabled and last used sources
loadSources()
loadLastUsedSource()
}
/**
* Unsubscribe and create a new subscription to fetch enabled sources.
*/
fun loadSources() {
sourceSubscription?.unsubscribe()
val map = TreeMap<String, MutableList<CatalogueSource>> { d1, d2 ->
// Catalogues without a lang defined will be placed at the end
when {
d1 == "" && d2 != "" -> 1
d2 == "" && d1 != "" -> -1
else -> d1.compareTo(d2)
}
}
val byLang = sources.groupByTo(map, { it.lang })
val sourceItems = byLang.flatMap {
val langItem = LangItem(it.key)
it.value.map { source -> SourceItem(source, langItem, controllerMode == CatalogueController.Mode.CATALOGUE) }
}
sourceSubscription = Observable.just(sourceItems)
.subscribeLatestCache(CatalogueController::setSources)
}
private fun loadLastUsedSource() {
val sharedObs = preferences.lastUsedCatalogueSource().asObservable().share()
// Emit the first item immediately but delay subsequent emissions by 500ms.
Observable.merge(
sharedObs.take(1),
sharedObs.skip(1).delay(500, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()))
.distinctUntilChanged()
.map { (sourceManager.get(it) as? CatalogueSource)?.let { SourceItem(it, showButtons = controllerMode == CatalogueController.Mode.CATALOGUE) } }
.subscribeLatestCache(CatalogueController::setLastUsedSource)
}
fun updateSources() {
sources = getEnabledSources()
loadSources()
}
/**
* Returns a list of enabled sources ordered by language and name.
*
* @return list containing enabled sources.
*/
private fun getEnabledSources(): List<CatalogueSource> {
val languages = preferences.enabledLanguages().getOrDefault()
val hiddenCatalogues = preferences.hiddenCatalogues().getOrDefault()
return sourceManager.getVisibleCatalogueSources()
.filter { it.lang in languages }
.filterNot { it.id.toString() in hiddenCatalogues }
.sortedBy { "(${it.lang}) ${it.name}" } +
sourceManager.get(LocalSource.ID) as LocalSource
}
}
| apache-2.0 |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/source/EnhancedHttpSource.kt | 1 | 7620 | package exh.source
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.HttpSource
import okhttp3.Response
import uy.kohesive.injekt.injectLazy
class EnhancedHttpSource(val originalSource: HttpSource,
val enchancedSource: HttpSource): HttpSource() {
private val prefs: PreferencesHelper by injectLazy()
/**
* Returns the request for the popular manga given the page.
*
* @param page the page number to retrieve.
*/
override fun popularMangaRequest(page: Int)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun popularMangaParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Returns the request for the search manga given the page.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
override fun searchMangaRequest(page: Int, query: String, filters: FilterList)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun searchMangaParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Returns the request for latest manga given the page.
*
* @param page the page number to retrieve.
*/
override fun latestUpdatesRequest(page: Int)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun latestUpdatesParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns the details of a manga.
*
* @param response the response from the site.
*/
override fun mangaDetailsParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a list of chapters.
*
* @param response the response from the site.
*/
override fun chapterListParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a list of pages.
*
* @param response the response from the site.
*/
override fun pageListParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
override fun imageUrlParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Base url of the website without the trailing slash, like: http://mysite.com
*/
override val baseUrl get() = source().baseUrl
/**
* Whether the source has support for latest updates.
*/
override val supportsLatest get() = source().supportsLatest
/**
* Name of the source.
*/
override val name get() = source().name
/**
* An ISO 639-1 compliant language code (two letters in lower case).
*/
override val lang get() = source().lang
// ===> OPTIONAL FIELDS
/**
* Id of the source. By default it uses a generated id using the first 16 characters (64 bits)
* of the MD5 of the string: sourcename/language/versionId
* Note the generated id sets the sign bit to 0.
*/
override val id get() = source().id
/**
* Default network client for doing requests.
*/
override val client get() = source().client
/**
* Visible name of the source.
*/
override fun toString() = source().toString()
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
*/
override fun fetchPopularManga(page: Int) = source().fetchPopularManga(page)
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
override fun fetchSearchManga(page: Int, query: String, filters: FilterList)
= source().fetchSearchManga(page, query, filters)
/**
* Returns an observable containing a page with a list of latest manga updates.
*
* @param page the page number to retrieve.
*/
override fun fetchLatestUpdates(page: Int) = source().fetchLatestUpdates(page)
/**
* Returns an observable with the updated details for a manga. Normally it's not needed to
* override this method.
*
* @param manga the manga to be updated.
*/
override fun fetchMangaDetails(manga: SManga) = source().fetchMangaDetails(manga)
/**
* Returns the request for the details of a manga. Override only if it's needed to change the
* url, send different headers or request method like POST.
*
* @param manga the manga to be updated.
*/
override fun mangaDetailsRequest(manga: SManga) = source().mangaDetailsRequest(manga)
/**
* Returns an observable with the updated chapter list for a manga. Normally it's not needed to
* override this method. If a manga is licensed an empty chapter list observable is returned
*
* @param manga the manga to look for chapters.
*/
override fun fetchChapterList(manga: SManga) = source().fetchChapterList(manga)
/**
* Returns an observable with the page list for a chapter.
*
* @param chapter the chapter whose page list has to be fetched.
*/
override fun fetchPageList(chapter: SChapter) = source().fetchPageList(chapter)
/**
* Returns an observable with the page containing the source url of the image. If there's any
* error, it will return null instead of throwing an exception.
*
* @param page the page whose source image has to be fetched.
*/
override fun fetchImageUrl(page: Page) = source().fetchImageUrl(page)
/**
* Called before inserting a new chapter into database. Use it if you need to override chapter
* fields, like the title or the chapter number. Do not change anything to [manga].
*
* @param chapter the chapter to be added.
* @param manga the manga of the chapter.
*/
override fun prepareNewChapter(chapter: SChapter, manga: SManga)
= source().prepareNewChapter(chapter, manga)
/**
* Returns the list of filters for the source.
*/
override fun getFilterList() = source().getFilterList()
private fun source(): HttpSource {
return if(prefs.eh_delegateSources().getOrDefault()) {
enchancedSource
} else {
originalSource
}
}
} | apache-2.0 |
AnnSofiAhn/15 | contest/app/src/main/kotlin/isotop/se/isotop15/contests/SlotCarsFragment.kt | 1 | 4616 | package isotop.se.isotop15.contests
import android.app.AlertDialog
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import isotop.se.isotop15.App
import isotop.se.isotop15.ContestantsRecyclerViewAdapter
import isotop.se.isotop15.R
import isotop.se.isotop15.models.Game
import isotop.se.isotop15.utils.MarginItemDecoration
/**
* @author Ann-Sofi Åhn
*
* Created on 17/02/13.
*/
class SlotCarsFragment(app: App): ContestFragment(app) {
@BindView(R.id.contestants_grid) lateinit var recyclerView: RecyclerView
@BindView(R.id.contest_button) lateinit var sendToBackendButton: Button
@BindView(R.id.instructions_view) lateinit var instructionsView: TextView
lateinit var adapter: ContestantsRecyclerViewAdapter
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_contest_simple, container, false)
ButterKnife.bind(this, rootView)
adapter = ContestantsRecyclerViewAdapter(context!!)
recyclerView.layoutManager = GridLayoutManager(context, 1)
recyclerView.adapter = adapter
recyclerView.setHasFixedSize(true)
recyclerView.addItemDecoration(MarginItemDecoration(resources))
sendToBackendButton.text = "Hoppa in i tävlingen"
instructionsView.text = ""
return rootView
}
override fun onResume() {
super.onResume()
val contestant = contestants.firstOrNull()
if (contestant != null){
Log.d(TAG, "onResume: $contestant")
adapter.clearContestants()
adapter.addContestant(contestant)
}
}
override fun contestantsUpdated() {
Log.d(TAG, "contestantsUpdated")
}
override fun getActivityId(): Int {
return Game.SLOT_CARS.id
}
@OnClick(R.id.contest_button)
fun sendContestantToBackend() {
val contestant = contestants.firstOrNull()
if (contestant != null) {
// Send to the backend, listen
app.slotCarsBackend.startPlaying(contestant.slug!!)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({
Log.d(TAG, "Got something back! $it")
val color = getControllerColor(it.controller)
var message = it.error ?: "${it.name} har $color kontroll"
if (message == "nouser") {
message = "Hittade inte användaren, vänligen försök igen om några minuter"
app.slotCarsBackend.requestDatabaseRefresh()
.subscribeOn(Schedulers.io())
.subscribe({
Log.d(TAG, "Asked the slot cars backend to refresh users")
}, {
Log.w(TAG, "Got an error when asking the slot cars backend to refresh users", it)
})
} else {
postParticipationForContestant(contestant)
}
AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton(android.R.string.ok, {ignore, id ->
callback.onContestFinished()
})
.create()
.show()
}, {
Log.w(TAG, "Got an error when entering a player into the game", it)
})
}
}
private fun getControllerColor(id: Int): String {
return when (id) {
0 -> "grön"
1 -> "röd"
2 -> "orange"
3 -> "vit"
4 -> "gul"
5 -> "blå"
else -> "okänd"
}
}
companion object {
val TAG = "SlotCarsFragment"
}
}
| mit |
mtransitapps/parser | src/main/java/org/mtransit/parser/mt/data/MFrequency.kt | 1 | 2268 | package org.mtransit.parser.mt.data
import org.mtransit.parser.Constants
import org.mtransit.parser.db.SQLUtils
import org.mtransit.parser.gtfs.GAgencyTools
import org.mtransit.parser.gtfs.data.GIDs
data class MFrequency(
val serviceIdInt: Int,
private val tripId: Long, // exported
val startTime: Int,
val endTime: Int,
private val headwayInSec: Int
) : Comparable<MFrequency?> {
@Deprecated(message = "Not memory efficient")
@Suppress("unused")
val serviceId = _serviceId
private val _serviceId: String
get() {
return GIDs.getString(serviceIdInt)
}
private fun getCleanServiceId(agencyTools: GAgencyTools): String {
return agencyTools.cleanServiceId(_serviceId)
}
val uID by lazy { getNewUID(serviceIdInt, tripId, startTime, endTime) }
fun toFile(agencyTools: GAgencyTools): String {
return SQLUtils.quotes(SQLUtils.escape(getCleanServiceId(agencyTools))) + // service ID
Constants.COLUMN_SEPARATOR + //
tripId + // trip ID
Constants.COLUMN_SEPARATOR + //
startTime + // start time
Constants.COLUMN_SEPARATOR + //
endTime + // end time
Constants.COLUMN_SEPARATOR + //
headwayInSec // headway in seconds
}
override fun compareTo(other: MFrequency?): Int {
return when {
other !is MFrequency -> {
+1
}
serviceIdInt != other.serviceIdInt -> {
_serviceId.compareTo(other._serviceId)
}
tripId != other.tripId -> {
tripId.compareTo(other.tripId)
}
startTime != other.startTime -> {
startTime - other.startTime
}
endTime != other.endTime -> {
endTime - other.endTime
}
else -> {
headwayInSec - other.headwayInSec
}
}
}
companion object {
@JvmStatic
fun getNewUID(
serviceIdInt: Int,
tripId: Long,
startTime: Int,
endTime: Int
) = "${serviceIdInt}-${tripId}-${startTime}-${endTime}"
}
} | apache-2.0 |
apollostack/apollo-android | apollo-runtime/src/main/java/com/apollographql/apollo3/fetcher/ApolloResponseFetchers.kt | 1 | 2345 | package com.apollographql.apollo3.fetcher
import com.apollographql.apollo3.internal.fetcher.CacheAndNetworkFetcher
import com.apollographql.apollo3.internal.fetcher.CacheFirstFetcher
import com.apollographql.apollo3.internal.fetcher.CacheOnlyFetcher
import com.apollographql.apollo3.internal.fetcher.NetworkFirstFetcher
import com.apollographql.apollo3.internal.fetcher.NetworkOnlyFetcher
object ApolloResponseFetchers {
/**
* Signals the apollo client to **only** fetch the data from the normalized cache. If it's not present in
* the normalized cache or if an exception occurs while trying to fetch it from the normalized cache, an empty [ ] is sent back with the [com.apollographql.apollo3.api.Operation] info
* wrapped inside.
*/
val CACHE_ONLY: ResponseFetcher = CacheOnlyFetcher()
/**
* Signals the apollo client to **only** fetch the GraphQL data from the network. If network request fails, an
* exception is thrown.
*/
@JvmField
val NETWORK_ONLY: ResponseFetcher = NetworkOnlyFetcher()
/**
* Signals the apollo client to first fetch the data from the normalized cache. If it's not present in the
* normalized cache or if an exception occurs while trying to fetch it from the normalized cache, then the data is
* instead fetched from the network.
*/
@JvmField
val CACHE_FIRST: ResponseFetcher = CacheFirstFetcher()
/**
* Signals the apollo client to first fetch the data from the network. If network request fails, then the
* data is fetched from the normalized cache. If the data is not present in the normalized cache, then the
* exception which led to the network request failure is rethrown.
*/
val NETWORK_FIRST: ResponseFetcher = NetworkFirstFetcher()
/**
* Signal the apollo client to fetch the data from both the network and the cache. If cached data is not
* present, only network data will be returned. If cached data is available, but network experiences an error,
* cached data is first returned, followed by the network error. If cache data is not available, and network
* data is not available, the error of the network request will be propagated. If both network and cache
* are available, both will be returned. Cache data is guaranteed to be returned first.
*/
val CACHE_AND_NETWORK: ResponseFetcher = CacheAndNetworkFetcher()
} | mit |
onoderis/failchat | src/main/kotlin/failchat/chat/handlers/SpaceSeparatedEmoticonHandler.kt | 1 | 782 | package failchat.chat.handlers
import failchat.Origin
import failchat.chat.ChatMessage
import failchat.chat.MessageHandler
import failchat.emoticon.EmoticonFinder
import failchat.emoticon.ReplaceDecision
import failchat.emoticon.WordReplacer
class SpaceSeparatedEmoticonHandler(
private val origin: Origin,
private val emoticonFinder: EmoticonFinder
) : MessageHandler<ChatMessage> {
override fun handleMessage(message: ChatMessage) {
message.text = WordReplacer.replace(message.text) { code ->
val emoticon = emoticonFinder.findByCode(origin, code)
?: return@replace ReplaceDecision.Skip
val label = message.addElement(emoticon)
return@replace ReplaceDecision.Replace(label)
}
}
}
| gpl-3.0 |
Maccimo/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/decompiler/stubBuilder/AbstractClsStubBuilderTest.kt | 2 | 4874 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.decompiler.stubBuilder
import com.google.common.io.Files
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.StubElement
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.util.indexing.FileContentImpl
import org.jetbrains.kotlin.analysis.decompiler.stub.file.KotlinClsStubBuilder
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.stubs.AbstractStubBuilderTest
import org.jetbrains.kotlin.idea.test.KotlinJdkAndLibraryProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.stubs.elements.KtFileStubBuilder
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.jetbrains.kotlin.idea.test.KotlinCompilerStandalone
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.utils.addIfNotNull
import org.junit.Assert
import java.io.File
abstract class AbstractClsStubBuilderTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinJdkAndLibraryProjectDescriptor(
listOf(KotlinArtifacts.kotlinAnnotationsJvm),
emptyList()
)
fun doTest(sourcePath: String) {
val ktFile = File("$sourcePath/${lastSegment(sourcePath)}.kt")
val jvmFileName = if (ktFile.exists()) {
val ktFileText = ktFile.readText()
InTextDirectivesUtils.findStringWithPrefixes(ktFileText, "JVM_FILE_NAME:")
} else {
null
}
val txtFilePath = File("$sourcePath/${lastSegment(sourcePath)}.txt")
testWithEnabledStringTable(sourcePath, jvmFileName, txtFilePath)
testWithDisabledStringTable(sourcePath, jvmFileName, txtFilePath)
}
private fun testWithEnabledStringTable(sourcePath: String, classFileName: String?, txtFile: File?) {
doTest(sourcePath, true, classFileName, txtFile)
}
private fun testWithDisabledStringTable(sourcePath: String, classFileName: String?, txtFile: File?) {
doTest(sourcePath, false, classFileName, txtFile)
}
protected fun doTest(sourcePath: String, useStringTable: Boolean, classFileName: String?, txtFile: File?) {
val classFile = getClassFileToDecompile(sourcePath, useStringTable, classFileName)
testClsStubsForFile(classFile, txtFile)
}
protected fun testClsStubsForFile(classFile: VirtualFile, txtFile: File?) {
val stubTreeFromCls = KotlinClsStubBuilder().buildFileStub(FileContentImpl.createByFile(classFile))!!
myFixture.configureFromExistingVirtualFile(classFile)
val psiFile = myFixture.file
val stubTreeFromDecompiledText = KtFileStubBuilder().buildStubTree(psiFile)
val expectedText = stubTreeFromDecompiledText.serializeToString()
Assert.assertEquals(expectedText, stubTreeFromCls.serializeToString())
if (txtFile != null) {
KotlinTestUtils.assertEqualsToFile(txtFile, expectedText)
}
}
private fun getClassFileToDecompile(sourcePath: String, isUseStringTable: Boolean, classFileName: String?): VirtualFile {
val outDir = KotlinTestUtils.tmpDir("libForStubTest-$sourcePath")
val extraOptions = ArrayList<String>()
extraOptions.add("-Xallow-kotlin-package")
if (isUseStringTable) {
extraOptions.add("-Xuse-type-table")
}
KotlinCompilerStandalone(
sources = listOf(File(sourcePath)),
target = outDir,
options = extraOptions,
classpath = listOf(KotlinArtifacts.kotlinAnnotationsJvm)
).compile()
val root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(outDir)!!
return root.findClassFileByName(classFileName ?: lastSegment(sourcePath))
}
private fun lastSegment(sourcePath: String): String {
return Files.getNameWithoutExtension(sourcePath.split('/').last { !it.isEmpty() })!!
}
}
fun StubElement<out PsiElement>.serializeToString(): String {
return AbstractStubBuilderTest.serializeStubToString(this)
}
fun VirtualFile.findClassFileByName(className: String): VirtualFile {
val files = LinkedHashSet<VirtualFile>()
VfsUtilCore.iterateChildrenRecursively(
this,
{ virtualFile ->
virtualFile.isDirectory || virtualFile.name == "$className.class"
},
{ virtualFile ->
if (!virtualFile.isDirectory) files.addIfNotNull(virtualFile); true
})
return files.single()
}
| apache-2.0 |
Maccimo/intellij-community | tools/intellij.ide.starter/src/com/intellij/ide/starter/utils/utils.kt | 1 | 9295 | package com.intellij.ide.starter.utils
import com.intellij.ide.starter.di.di
import com.intellij.ide.starter.exec.ExecOutputRedirect
import com.intellij.ide.starter.exec.exec
import com.intellij.ide.starter.path.GlobalPaths
import com.intellij.ide.starter.system.SystemInfo
import org.kodein.di.direct
import org.kodein.di.instance
import java.io.*
import java.lang.Long.numberOfLeadingZeros
import java.nio.charset.Charset
import java.nio.file.FileStore
import java.nio.file.Files
import java.nio.file.Path
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import kotlin.io.path.*
import kotlin.time.Duration
fun formatArtifactName(artifactType: String, testName: String): String {
val testNameFormatted = testName.replace("/", "-").replace(" ", "")
val time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
return "$artifactType-$testNameFormatted-$time"
}
fun getThrowableText(t: Throwable): String {
val writer = StringWriter()
t.printStackTrace(PrintWriter(writer))
return writer.buffer.toString()
}
inline fun catchAll(action: () -> Unit) {
try {
action()
}
catch (t: Throwable) {
logError("CatchAll swallowed error: ${t.message}")
logError(getThrowableText(t))
}
}
fun FileStore.getDiskInfo(): String = buildString {
appendLine("Disk info of ${name()}")
appendLine(" Total space: " + totalSpace.formatSize())
appendLine(" Unallocated space: " + unallocatedSpace.formatSize())
appendLine(" Usable space: " + usableSpace.formatSize())
}
fun Runtime.getRuntimeInfo(): String = buildString {
appendLine("Memory info")
appendLine(" Total memory: " + totalMemory().formatSize())
appendLine(" Free memory: " + freeMemory().formatSize())
appendLine(" Max memory: " + maxMemory().formatSize())
}
/**
* Invoke cmd: java [arg1 arg2 ... argN]
*/
fun execJavaCmd(javaHome: Path, args: Iterable<String> = listOf()): List<String> {
val ext = if (SystemInfo.isWindows) ".exe" else ""
val realJavaHomePath = if (javaHome.isSymbolicLink()) javaHome.readSymbolicLink() else javaHome
val java = realJavaHomePath.toAbsolutePath().resolve("bin/java$ext")
require(java.isRegularFile()) { "Java is not found under $java" }
val prefix = "exec-java-cmd"
val stdout = ExecOutputRedirect.ToString()
val stderr = ExecOutputRedirect.ToString()
val processArguments = listOf(java.toString()).plus(args)
exec(
presentablePurpose = prefix,
workDir = javaHome,
timeout = Duration.minutes(1),
args = processArguments,
stdoutRedirect = stdout,
stderrRedirect = stderr
)
val mergedOutput = listOf(stdout, stderr)
.flatMap { it.read().split(System.lineSeparator()) }
.map { it.trim() }
.filter { it.isNotBlank() }
logOutput(
"""
Result of calling $processArguments:
${mergedOutput.joinToString(System.lineSeparator())}
""")
return mergedOutput
}
/**
* Invoke java -version
*
* @return
* openjdk version "17.0.1" 2021-10-19 LTS
* OpenJDK Runtime Environment Corretto-17.0.1.12.1 (build 17.0.1+12-LTS)
* OpenJDK 64-Bit Server VM Corretto-17.0.1.12.1 (build 17.0.1+12-LTS, mixed mode, sharing)
*/
fun callJavaVersion(javaHome: Path): String = execJavaCmd(javaHome, listOf("-version")).joinToString(System.lineSeparator())
fun isX64Jdk(javaHome: Path): Boolean {
val archProperty = execJavaCmd(javaHome, listOf("-XshowSettings:all", "-version")).firstOrNull { it.startsWith("sun.arch.data.model") }
if (archProperty.isNullOrBlank())
throw IllegalAccessException("Couldn't get architecture property sun.arch.data.model value from JDK")
return archProperty.trim().endsWith("64")
}
fun resolveInstalledJdk11(): Path {
val jdkEnv = listOf("JDK_11_X64", "JAVA_HOME").firstNotNullOfOrNull { System.getenv(it) } ?: System.getProperty("java.home")
val javaHome = jdkEnv?.let {
val path = Path(it)
if (path.isSymbolicLink()) path.readSymbolicLink()
else path
}
if (javaHome == null || !javaHome.exists())
throw IllegalArgumentException("Java Home $javaHome is null, empty or doesn't exist. Specify JAVA_HOME to point to JDK 11 x64")
require(javaHome.isDirectory() && Files.walk(javaHome)
.use { it.count() } > 10) {
"Java Home $javaHome is not found or empty!"
}
require(isX64Jdk(javaHome)) { "JDK at path $javaHome should support x64 architecture" }
return javaHome
}
fun String.withIndent(indent: String = " "): String = lineSequence().map { "$indent$it" }.joinToString(System.lineSeparator())
private fun quoteArg(arg: String): String {
val specials = " #'\"\n\r\t\u000c"
if (!specials.any { arg.contains(it) }) {
return arg
}
val sb = StringBuilder(arg.length * 2)
for (element in arg) {
when (element) {
' ', '#', '\'' -> sb.append('"').append(element).append('"')
'"' -> sb.append("\"\\\"\"")
'\n' -> sb.append("\"\\n\"")
'\r' -> sb.append("\"\\r\"")
'\t' -> sb.append("\"\\t\"")
else -> sb.append(element)
}
}
return sb.toString()
}
/**
* Writes list of Java arguments to the Java Command-Line Argument File
* See https://docs.oracle.com/javase/9/tools/java.htm, section "java Command-Line Argument Files"
**/
fun writeJvmArgsFile(argFile: File,
args: List<String>,
lineSeparator: String = System.lineSeparator(),
charset: Charset = Charsets.UTF_8) {
BufferedWriter(OutputStreamWriter(FileOutputStream(argFile), charset)).use { writer ->
for (arg in args) {
writer.write(quoteArg(arg))
writer.write(lineSeparator)
}
}
}
fun takeScreenshot(logsDir: Path) {
val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools")
val toolName = "TakeScreenshot"
val screenshotTool = toolsDir / toolName
if (!File(screenshotTool.toString()).exists()) {
val archivePath = toolsDir / "$toolName.zip"
HttpClient.download("https://repo.labs.intellij.net/phpstorm/tools/TakeScreenshot-1.02.zip", archivePath)
FileSystem.unpack(archivePath, screenshotTool)
}
val screenshotFile = logsDir.resolve("screenshot_beforeKill.jpg")
val toolPath = screenshotTool.resolve("$toolName.jar")
val javaPath = ProcessHandle.current().info().command().orElseThrow().toString()
exec(
presentablePurpose = "take-screenshot",
workDir = toolsDir,
timeout = Duration.seconds(15),
args = mutableListOf(javaPath, "-jar", toolPath.absolutePathString(), screenshotFile.toString()),
environmentVariables = mapOf("DISPLAY" to ":88"),
onlyEnrichExistedEnvVariables = true
)
if (screenshotFile.exists()) {
logOutput("Screenshot saved in $screenshotFile")
}
else {
error("Couldn't take screenshot")
}
}
fun startProfileNativeThreads(pid: String) {
if (!SystemInfo.isWindows) {
val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools")
val toolName = "async-profiler-2.7-macos"
val profiler = toolsDir / toolName
downloadAsyncProfilerIfNeeded(profiler, toolsDir)
givePermissionsToExecutables(profiler)
exec(
presentablePurpose = "start-profile",
workDir = profiler,
timeout = Duration.seconds(15),
args = mutableListOf("./profiler.sh", "start", pid)
)
}
}
private fun givePermissionsToExecutables(profiler: Path) {
exec(
presentablePurpose = "give-permissions-to-jattach",
workDir = profiler.resolve("build"),
timeout = Duration.seconds(10),
args = mutableListOf("chmod", "+x", "jattach")
)
exec(
presentablePurpose = "give-permissions-to-profiler",
workDir = profiler,
timeout = Duration.seconds(10),
args = mutableListOf("chmod", "+x", "profiler.sh")
)
}
fun stopProfileNativeThreads(pid: String, fileToStoreInfo: String) {
if (!SystemInfo.isWindows) {
val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools")
val toolName = "async-profiler-2.7-macos"
val profiler = toolsDir / toolName
exec(
presentablePurpose = "stop-profile",
workDir = profiler,
timeout = Duration.seconds(15),
args = mutableListOf("./profiler.sh", "stop", pid, "-f", fileToStoreInfo)
)
}
}
private fun downloadAsyncProfilerIfNeeded(profiler: Path, toolsDir: Path) {
if (!File(profiler.toString()).exists()) {
val profilerFileName = when {
SystemInfo.isMac -> "async-profiler-2.7-macos.zip"
SystemInfo.isLinux -> "async-profiler-2.7-linux-x64.tar.gz"
else -> error("Current OS is not supported")
}
val archivePath = toolsDir / profilerFileName
HttpClient.download("https://github.com/jvm-profiling-tools/async-profiler/releases/download/v2.7/$profilerFileName",
archivePath)
FileSystem.unpack(archivePath, toolsDir)
}
}
fun Long.formatSize(): String {
if (this < 1024) return "$this B"
val z = (63 - numberOfLeadingZeros(this)) / 10
return String.format("%.1f %sB", this.toDouble() / (1L shl z * 10), " KMGTPE"[z])
}
fun pathInsideJarFile(
jarFile: Path,
pathInsideJar: String
): String = jarFile.toAbsolutePath().toString().trimEnd('/') + "!/" + pathInsideJar
data class FindUsagesCallParameters(val pathToFile: String, val offset: String, val element: String) {
override fun toString() = "$pathToFile $element, $offset)"
}
| apache-2.0 |
onoderis/failchat | src/test/kotlin/failchat/emoticon/WordReplacerTest.kt | 2 | 1508 | package failchat.emoticon
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
class WordReplacerTest {
@Test
fun replaceNothingTest() {
val words = listOf("just", "a", "simple", "message")
val initialString = words.joinToString(separator = " ")
val actualWords = ArrayList<String>()
val resultString = WordReplacer.replace(initialString) {
actualWords.add(it)
ReplaceDecision.Skip
}
assertSame(initialString, resultString)
assertEquals(words, actualWords)
}
@Test
fun replaceAllTest() {
val resultString = WordReplacer.replace("just a simple message") {
ReplaceDecision.Replace("42")
}
assertEquals("42 42 42 42", resultString)
}
@Test
fun specialCharactersTest() {
val words = listOf(
"!", "@", "#", "$", "%", "^", "&", "*", "(", ")",
"!!", "@@", "##", "$$", "%%", "^^", "&&", "**", "((", "))"
)
val initialString = words.joinToString(separator = " ")
val resultString = WordReplacer.replace(initialString) {
ReplaceDecision.Replace("1")
}
assertEquals(words.joinToString(separator = " ") { "1" }, resultString)
}
@Test
fun lineBreakTest() {
val resultString = WordReplacer.replace("the\nmessage") {
ReplaceDecision.Replace("1")
}
assertEquals("1\n1", resultString)
}
}
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.