JS Implement IDL2K tool and import DOM3 IDLs

JS Introduce required utility functions for DOM3
This commit is contained in:
Sergey Mashkov
2015-04-24 18:41:49 +03:00
committed by Sergey Mashkov
parent dc7f81a904
commit 53495fa989
16 changed files with 7299 additions and 3 deletions
+133
View File
@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>idl2k</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<kotlin.version>0.1-SNAPSHOT</kotlin.version>
<antlr.version>4.5</antlr.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>${antlr.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.2</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<!--<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>-->
<plugins>
<plugin>
<groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId>
<version>${antlr.version}</version>
<executions>
<execution>
<goals>
<goal>antlr4</goal>
</goals>
<configuration>
<visitor>true</visitor>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>org.jetbrains.idl2k.Idl2kPackage</mainClass>
<classpathScope>compile</classpathScope>
<workingDirectory>${project.basedir}</workingDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>sonatype.oss.snapshots</id>
<name>Sonatype OSS Snapshot Repository</name>
<url>http://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>sonatype.oss.snapshots</id>
<name>Sonatype OSS Snapshot Repository</name>
<url>http://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
@@ -0,0 +1,591 @@
/*
BSD License
Copyright (c) 2013, Rainer Schuster
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Rainer Schuster nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Web IDL grammar derived from:
http://heycam.github.io/webidl/
Web IDL (Second Edition)
W3C Editor's Draft 13 November 2014
*/
grammar WebIDL;
// Note: Replaced keywords: const, default, enum, interface, null.
// Note: Added "wrapper" rule webIDL with EOF token.
webIDL
: definitions EOF
;
definitions
: extendedAttributeList definition definitions
| /* empty */
;
definition
: callbackOrInterface
| partial
| dictionary
| enum_
| typedef
| implementsStatement
;
callbackOrInterface
: 'callback' callbackRestOrInterface
| interface_
;
callbackRestOrInterface
: callbackRest
| interface_
;
interface_
: 'interface' IDENTIFIER_WEBIDL inheritance '{' interfaceMembers '}' ';'
;
partial
: 'partial' partialDefinition
;
partialDefinition
: partialInterface
| partialDictionary
;
partialInterface
: 'interface' IDENTIFIER_WEBIDL '{' interfaceMembers '}' ';'
;
interfaceMembers
: extendedAttributeList interfaceMember interfaceMembers
| /* empty */
;
interfaceMember
: const_
| operation
| serializer
| stringifier
| staticMember
| iterable
| readonlyMember
| readWriteAttribute
| readWriteMaplike
| readWriteSetlike
;
dictionary
: 'dictionary' IDENTIFIER_WEBIDL inheritance '{' dictionaryMembers '}' ';'
;
dictionaryMembers
: extendedAttributeList dictionaryMember dictionaryMembers
| /* empty */
;
dictionaryMember
: required type IDENTIFIER_WEBIDL default_ ';'
;
required
: 'required'
| /* empty */
;
partialDictionary
: 'dictionary' IDENTIFIER_WEBIDL '{' dictionaryMembers '}' ';'
;
default_
: '=' defaultValue
| /* empty */
;
defaultValue
: constValue
| STRING_WEBIDL
| '[' ']'
;
inheritance
: ':' IDENTIFIER_WEBIDL
| /* empty */
;
enum_
: 'enum' IDENTIFIER_WEBIDL '{' enumValueList '}' ';'
;
enumValueList
: STRING_WEBIDL enumValueListComma
;
enumValueListComma
: ',' enumValueListString
| /* empty */
;
enumValueListString
: STRING_WEBIDL enumValueListComma
| /* empty */
;
callbackRest
: IDENTIFIER_WEBIDL '=' returnType '(' argumentList ')' ';'
;
typedef
: 'typedef' type IDENTIFIER_WEBIDL ';'
;
implementsStatement
: IDENTIFIER_WEBIDL 'implements' IDENTIFIER_WEBIDL ';'
;
const_
: 'const' constType IDENTIFIER_WEBIDL '=' constValue ';'
;
constValue
: booleanLiteral
| floatLiteral
| INTEGER_WEBIDL
| 'null'
;
booleanLiteral
: 'true'
| 'false'
;
floatLiteral
: FLOAT_WEBIDL
| '-Infinity'
| 'Infinity'
| 'NaN'
;
serializer
: 'serializer' serializerRest
;
serializerRest
: operationRest
| '=' serializationPattern
| /* empty */
;
serializationPattern
: '{' serializationPatternMap '}'
| '[' serializationPatternList ']'
| IDENTIFIER_WEBIDL
;
serializationPatternMap
: 'getter'
| 'inherit' identifiers
| IDENTIFIER_WEBIDL identifiers
| /* empty */
;
serializationPatternList
: 'getter'
| IDENTIFIER_WEBIDL identifiers
| /* empty */
;
stringifier
: 'stringifier' stringifierRest
;
stringifierRest
: readOnly attributeRest
| returnType operationRest
| ';'
;
staticMember
: 'static' staticMemberRest
;
staticMemberRest
: readOnly attributeRest
| returnType operationRest
;
readonlyMember
: 'readonly' readonlyMemberRest
;
readonlyMemberRest
: attributeRest
| maplikeRest
| setlikeRest
;
readWriteAttribute
: 'inherit' readOnly attributeRest
| attributeRest
;
attributeRest
: 'attribute' type (IDENTIFIER_WEBIDL | 'required') ';'
;
attributeName
: attributeNameKeyword
| IDENTIFIER_WEBIDL
;
attributeNameKeyword
: 'required'
;
inherit
: 'inherit'
| /* empty */
;
readOnly
: 'readonly'
| /* empty */
;
operation
: returnType operationRest
| specialOperation
;
specialOperation
: special specials returnType operationRest
;
specials
: special specials
| /* empty */
;
special
: 'getter'
| 'setter'
| 'creator'
| 'deleter'
| 'legacycaller'
;
operationRest
: optionalIdentifier '(' argumentList ')' ';'
;
optionalIdentifier
: IDENTIFIER_WEBIDL
| /* empty */
;
argumentList
: argument arguments
| /* empty */
;
arguments
: ',' argument arguments
| /* empty */
;
argument
: extendedAttributeList optionalOrRequiredArgument
;
optionalOrRequiredArgument
: 'optional'? type ellipsis argumentName default_
;
argumentName
: argumentNameKeyword
| IDENTIFIER_WEBIDL
;
ellipsis
: '...'
| /* empty */
;
iterable
: 'iterable' '<' type optionalType '>' ';'
| 'legacyiterable' '<' type '>' ';'
;
optionalType
: ',' type
| /* empty */
;
readWriteMaplike
: maplikeRest
;
readWriteSetlike
: setlikeRest
;
maplikeRest
: 'maplike' '<' type ',' type '>' ';'
;
setlikeRest
: 'setlike' '<' type '>' ';'
;
extendedAttributeList
: '[' extendedAttribute extendedAttributes ']'
| /* empty */
;
extendedAttributes
: ',' extendedAttribute extendedAttributes
| /* empty */
;
extendedAttribute
: extendedAttributeNamePart? IDENTIFIER_WEBIDL ('(' argumentList ')')?
| extendedAttributeNamePart? IDENTIFIER_WEBIDL? '(' argumentList ')'
| extendedAttributeNamePart? IDENTIFIER_WEBIDL? '(' identifierList ')'
| /* empty */
;
extendedAttributeNamePart
: IDENTIFIER_WEBIDL '='
;
argumentNameKeyword
: 'attribute'
| 'callback'
| 'const'
| 'creator'
| 'deleter'
| 'dictionary'
| 'enum'
| 'getter'
| 'implements'
| 'inherit'
| 'interface'
| 'iterable'
| 'legacycaller'
| 'legacyiterable'
| 'maplike'
| 'partial'
| 'required'
| 'serializer'
| 'setlike'
| 'setter'
| 'static'
| 'stringifier'
| 'typedef'
| 'unrestricted'
;
type
: singleType
| unionType typeSuffix
;
singleType
: nonAnyType
| 'any' typeSuffixStartingWithArray
;
unionType
: '(' unionMemberType 'or' unionMemberType unionMemberTypes ')'
;
unionMemberType
: nonAnyType
| unionType typeSuffix
| 'any' '[' ']' typeSuffix
;
unionMemberTypes
: 'or' unionMemberType unionMemberTypes
| /* empty */
;
nonAnyType
: primitiveType typeSuffix
| promiseType null_
| 'ByteString' typeSuffix
| 'DOMString' typeSuffix
| 'USVString' typeSuffix
| IDENTIFIER_WEBIDL typeSuffix
| 'sequence' '<' type '>' null_
| 'object' typeSuffix
| 'Date' typeSuffix
| 'RegExp' typeSuffix
| 'DOMException' typeSuffix
| bufferRelatedType typeSuffix
;
bufferRelatedType
: 'ArrayBuffer'
| 'DataView'
| 'Int8Array'
| 'Int16Array'
| 'Int32Array'
| 'Uint8Array'
| 'Uint16Array'
| 'Uint32Array'
| 'Uint8ClampedArray'
| 'Float32Array'
| 'Float64Array'
;
constType
: primitiveType null_
| IDENTIFIER_WEBIDL null_
;
primitiveType
: unsignedIntegerType
| unrestrictedFloatType
| 'boolean'
| 'byte'
| 'octet'
;
unrestrictedFloatType
: 'unrestricted' floatType
| floatType
;
floatType
: 'float'
| 'double'
;
unsignedIntegerType
: 'unsigned' integerType
| integerType
;
integerType
: 'short'
| 'long' optionalLong
;
optionalLong
: 'long'
| /* empty */
;
promiseType
: 'Promise' '<' returnType '>'
;
typeSuffix
: '[' ']' typeSuffix
| '?' typeSuffixStartingWithArray
| /* empty */
;
typeSuffixStartingWithArray
: '[' ']' typeSuffix
| /* empty */
;
null_
: '?'
| /* empty */
;
returnType
: type
| 'void'
;
identifierList
: IDENTIFIER_WEBIDL identifiers
;
identifiers
: ',' IDENTIFIER_WEBIDL identifiers
| /* empty */
;
extendedAttributeNoArgs
: IDENTIFIER_WEBIDL
;
extendedAttributeArgList
: IDENTIFIER_WEBIDL '(' argumentList ')'
;
extendedAttributeIdent
: IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL
;
extendedAttributeIdentList
: IDENTIFIER_WEBIDL '=' '(' identifierList ')'
;
extendedAttributeNamedArgList
: IDENTIFIER_WEBIDL '=' IDENTIFIER_WEBIDL '(' argumentList ')'
;
INTEGER_WEBIDL
: '-'?('0'([Xx][0-9A-Fa-f]+|[0-7]*)|[1-9][0-9]*)
;
FLOAT_WEBIDL
: '-'?(([0-9]+'.'[0-9]*|[0-9]*'.'[0-9]+)([Ee][\+\-]?[0-9]+)?|[0-9]+[Ee][\+\-]?[0-9]+)
;
IDENTIFIER_WEBIDL
: [A-Z_a-z][0-9A-Z_a-z]*
;
STRING_WEBIDL
: '"'~['"']*'"'
;
WHITESPACE_WEBIDL
: [\t\n\r ]+ -> channel(HIDDEN)
;
COMMENT_WEBIDL
: ('//'~[\n\r]*|'/*'(.|'\n')*?'*/')+ -> channel(HIDDEN)
; // Note: '/''/'~[\n\r]* instead of '/''/'.* (non-greedy because of wildcard).
OTHER_WEBIDL
: ~[\t\n\r 0-9A-Z_a-z]
;
@@ -0,0 +1,80 @@
/*
* Copyright 2010-2015 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.idl2k
import java.util.*
private val typeMapper = mapOf(
"unsignedlong" to "Int",
"unsignedlonglong" to "Long",
"longlong" to "Long",
"unsignedshort" to "Short",
"void" to "Unit",
"DOMString" to "String",
"boolean" to "Boolean",
"short" to "Short",
"long" to "Int",
"double" to "Double",
"any" to "Any",
"" to "dynamic",
"DOMTimeStamp" to "Number",
"EventHandler" to "() -> Unit",
"object" to "dynamic",
"WindowProxy" to "Window",
"Uint8ClampedArray" to "dynamic", // TODO think of native arrays,
"Function" to "() -> dynamic",
"USVString" to "String",
"ByteString" to "String",
"DOMError" to "dynamic",
"SVGMatrix" to "dynamic",
"ArrayBuffer" to "dynamic",
"Elements" to "dynamic"
)
private fun fixDynamic(type : String) = if (type == "dynamic?") "dynamic" else type
private fun mapType(repository: Repository, type: String) = fixDynamic(handleSpecialTypes(repository, typeMapper[type] ?: type))
private fun handleSpecialTypes(repository: Repository, type: String): String {
if (type.endsWith("?")) {
return mapType(repository, type.substring(0, type.length() - 1)) + "?"
} else if (type.endsWith("...")) {
return mapType(repository, type.substring(0, type.length() - 3))
} else if (type.endsWith("[]")) {
return "Array<${mapType(repository, type.substring(0, type.length() - 2))}>"
} else if (type.startsWith("unrestricted")) {
return mapType(repository, type.substring(12))
} else if (type.startsWith("sequence")) {
return "Any" // TODO how do we handle sequences?
} else if (type in repository.typeDefs) {
return "dynamic"
} else if (type in repository.enums) {
return "String"
} else if (type.endsWith("Callback")) {
return "() -> Unit"
// } else if (type.startsWith("Union<")) {
// return "dynamic"
} else if (type.startsWith("Promise<")) {
return "dynamic"
} else if ("NoInterfaceObject" in repository.interfaces[type]?.extendedAttributes?.map {it.call} ?: emptyList()) {
return "dynamic"
}
return type
}
private fun findConstructorAttribute(iface: InterfaceDefinition) = iface.extendedAttributes.firstOrNull { it.call == "Constructor" }
@@ -0,0 +1,272 @@
package org.jetbrains.idl2k
import java.math.BigInteger
import java.util.*
import kotlin.support.AbstractIterator
private fun Operation.getterOrSetter() = this.attributes.map { it.call }.toSet().let { attributes ->
when {
"getter" in attributes -> NativeGetterOrSetter.GETTER
"setter" in attributes -> NativeGetterOrSetter.SETTER
else -> NativeGetterOrSetter.NONE
}
}
private fun String.ensureNullable() = if (this.endsWith("?") || this == "dynamic") this else this + "?"
fun generateFunction1(repository: Repository, function: Operation, functionName: String, nativeGetterOrSetter: Boolean): GenerateFunction =
function.attributes.map { it.call }.toSet().let { attributes ->
GenerateFunction(
name = functionName,
returnType = mapType(repository, function.returnType).let { mapped -> if (nativeGetterOrSetter) mapped.ensureNullable() else mapped },
arguments = function.parameters.map {
GenerateAttribute(
name = it.name,
type = mapType(repository, it.type),
initializer = it.defaultValue,
getterSetterNoImpl = false,
override = false,
readOnly = true,
vararg = it.vararg
)
},
native = if (nativeGetterOrSetter) function.getterOrSetter() else NativeGetterOrSetter.NONE
)
}
fun generateFunction(repository: Repository, function: Operation): List<GenerateFunction> {
val realFunction = if (function.name == "") null else generateFunction1(repository, function, function.name, false)
val getterOrSetterFunction = when (function.getterOrSetter()) {
NativeGetterOrSetter.NONE -> null
NativeGetterOrSetter.GETTER -> generateFunction1(repository, function, "get", true)
NativeGetterOrSetter.SETTER -> generateFunction1(repository, function, "set", true)
}
return listOf(realFunction, getterOrSetterFunction).filterNotNull()
}
fun generateAttribute(putNoImpl: Boolean, repository: Repository, attribute: Attribute): GenerateAttribute =
GenerateAttribute(attribute.name,
type = mapType(repository, attribute.type),
initializer = attribute.defaultValue,
getterSetterNoImpl = putNoImpl,
readOnly = attribute.readOnly,
override = false,
vararg = attribute.vararg
)
private fun InterfaceDefinition.findConstructor() = extendedAttributes.firstOrNull { it.call == "Constructor" }
private fun InterfaceDefinition.superTypes(repository: Repository) = superTypes.map { repository.interfaces[it] }.filterNotNull()
private fun resolveDefinitionType(repository: Repository, iface: InterfaceDefinition, constructor: ExtendedAttribute? = findConstructorAttribute(iface)): GenerateDefinitionType =
if (iface.dictionary || constructor != null || iface.superTypes(repository).any { resolveDefinitionType(repository, it) == GenerateDefinitionType.CLASS }) GenerateDefinitionType.CLASS
else GenerateDefinitionType.TRAIT
private fun InterfaceDefinition.mapAttributes(repository: Repository) = attributes.map { generateAttribute(!dictionary, repository, it) }
private fun InterfaceDefinition.mapOperations(repository: Repository) = operations.flatMap { generateFunction(repository, it) }
private fun Constant.mapConstant(repository : Repository) = GenerateAttribute(name, mapType(repository, type), value, false, true, false, false)
fun generateTrait(repository: Repository, iface: InterfaceDefinition): GenerateTraitOrClass {
val constructor = iface.findConstructor()
val parentTypes = iface.superTypes.map { repository.interfaces[it] }.filterNotNull().map { it to resolveDefinitionType(repository, it) }
val constructorFunction = generateFunction1(repository, Operation("", "Unit", constructor?.arguments ?: emptyList(), emptyList()), "", false)
val constructorArgumentNames = constructorFunction.arguments.map { it.name }.toSet()
val constructorSuperCalls = parentTypes.filter { it.second == GenerateDefinitionType.CLASS }.map { it.first }.map {
val superConstructor = it.findConstructor()
GenerateFunctionCall(name = it.name,
arguments = if (superConstructor == null) emptyList() else
superConstructor.arguments.map { arg ->
if (arg.name in constructorArgumentNames) arg.name
else "noImpl"
}
)
}
val entityType = resolveDefinitionType(repository, iface, constructor)
val extensions = repository.externals[iface.name]?.map { repository.interfaces[it] }?.filterNotNull() ?: emptyList()
return GenerateTraitOrClass(iface.name, entityType, iface.superTypes,
memberAttributes = (iface.mapAttributes(repository) + extensions.flatMap { it.mapAttributes(repository) }).distinct().toList(),
memberFunctions = (iface.mapOperations(repository) + extensions.flatMap { it.mapOperations(repository) }).distinct().toList(),
constnats = iface.constants.map {it.mapConstant(repository)},
constructor = constructorFunction,
superConstructorCalls = constructorSuperCalls
)
}
private fun splitUnionType(unionType: String) =
unionType.split("[>]*,(Union<)*".toRegex()).toList().filter { it != "" }.map { it.removePrefix("Union<").replaceAll(">*$", "") }.distinct()
private fun GenerateFunction?.allTypes() = if (this != null) sequenceOf(returnType) + arguments.asSequence().map { it.type } else emptySequence()
class UnionType(types : Collection<String>) {
val types = HashSet(types)
val name = "Union${this.types.sort().joinToString("Or")}"
fun contains(type : String) = type in types
override fun equals(other: Any?): Boolean = other is UnionType && name == other.name
override fun hashCode(): Int = name.hashCode()
override fun toString(): String = name
}
private fun collectUnionTypes(allTypes: Map<String, GenerateTraitOrClass>) =
allTypes.values().asSequence()
.flatMap {
it.constructor.allTypes() +
it.memberAttributes.asSequence().map { it.type } +
it.memberFunctions.asSequence().flatMap { it.allTypes() }
}
.filter { it.startsWith("Union<") }
.map { splitUnionType(it) }
.filter { it.all { unionMember -> unionMember in allTypes } }
.toSet()
.map { UnionType(it) }
fun generateUnionTypeTraits(allUnionTypes : Iterable<UnionType>): List<GenerateTraitOrClass> =
allUnionTypes.map { GenerateTraitOrClass(
name = it.name,
type = GenerateDefinitionType.TRAIT,
superTypes = emptyList(),
memberAttributes = emptyList(),
memberFunctions = emptyList(),
constnats = emptyList(),
constructor = null,
superConstructorCalls = emptyList()
) }
fun mapDefinitions(repository: Repository, definitions: Iterable<InterfaceDefinition>) =
definitions.filter { "NoInterfaceObject" !in it.extendedAttributes.map { it.call } }.map { generateTrait(repository, it) }
private fun <O : Appendable> O.renderAttributeDeclaration(allTypes: Set<String>, arg: GenerateAttribute, override: Boolean) {
append(" ")
if (override) {
append("override ")
}
append(if (arg.readOnly) "val" else "var")
append(" ")
append(arg.name)
append(" : ")
append(arg.type.mapUnknownType(allTypes))
if (arg.initializer != null) {
append(" = ")
append(arg.initializer)
}
appendln()
if (arg.getterNoImpl) {
appendln(" get() = noImpl")
}
if (arg.setterNoImpl) {
appendln(" set(value) = noImpl")
}
}
fun GenerateTraitOrClass.allSuperTypes(all: Map<String, GenerateTraitOrClass>) = HashSet<GenerateTraitOrClass>().let { result -> allSuperTypesImpl(listOf(this), all, result); result.toList() }
tailRecursive
private fun allSuperTypesImpl(roots: List<GenerateTraitOrClass>, all: Map<String, GenerateTraitOrClass>, result: HashSet<GenerateTraitOrClass>) {
if (roots.isNotEmpty()) {
allSuperTypesImpl(roots.flatMap { it.superTypes }.map { all[it] }.filterNotNull().filter { result.add(it) }, all, result)
}
}
private fun String.mapUnknownType(allTypes: Set<String>, standardTypes: Set<String> = typeMapper.values().toSet()): String =
if (this.endsWith("?")) (this.substring(0, length() - 1).mapUnknownType(allTypes, standardTypes) + "?").replace("dynamic?", "dynamic")
else if (this.startsWith("Union<")) UnionType(splitUnionType(this)).name.mapUnknownType(allTypes, standardTypes)
else if (this in allTypes || this in standardTypes) this else "dynamic"
private fun String.parse() = if (this.startsWith("0x")) BigInteger(this.substring(2), 16) else BigInteger(this)
private fun String.replaceInitializer(type: String) = if (this == "noImpl" || type == "Int" && parse() > BigInteger.valueOf(Int.MAX_VALUE.toLong())) "noImpl" else this
private fun <O : Appendable> O.renderArgumentsDeclaration(allTypes: Set<String>, args: List<GenerateAttribute>, omitDefaults: Boolean) =
args.map { "${if (it.vararg) "vararg " else ""}${it.name} : ${it.type.mapUnknownType(allTypes)}${if (omitDefaults || it.initializer == null) "" else " = ${it.initializer.replaceInitializer(it.type)}"}" }.joinTo(this, ", ")
private fun renderCall(call: GenerateFunctionCall) = "${call.name}(${call.arguments.join(", ")})"
private fun <O : Appendable> O.renderFunction(allTypes: Set<String>, f: GenerateFunction, override: Boolean) {
append(" ")
when (f.native) {
NativeGetterOrSetter.GETTER -> append("nativeGetter ")
NativeGetterOrSetter.GETTER -> append("nativeSetter ")
}
if (override) {
append("override ")
}
append("fun ${f.name}(")
renderArgumentsDeclaration(allTypes, f.arguments, override)
appendln(") : ${f.returnType.mapUnknownType(allTypes)} = noImpl")
}
fun <O : Appendable> O.render(allTypes: Map<String, GenerateTraitOrClass>, classesToUnions : Map<String, List<UnionType>>, iface: GenerateTraitOrClass) {
val superTypes = iface.allSuperTypes(allTypes).filter { it.name != "" }
val superTypesNames = superTypes.map { it.name }.toSet()
append("native ")
when (iface.type) {
GenerateDefinitionType.CLASS -> append("open class ")
GenerateDefinitionType.TRAIT -> append("trait ")
}
append(iface.name)
if (iface.constructor != null && iface.constructor.arguments.isNotEmpty()) {
append("(")
renderArgumentsDeclaration(allTypes.keySet(), iface.constructor.arguments, false)
append(")")
}
val superCalls = iface.superConstructorCalls.map { it.name }.toSet()
val superTypesWithCalls =
iface.superConstructorCalls.filter { it.name in superTypesNames }.map { renderCall(it) } +
iface.superTypes.filter { it !in superCalls && it in superTypesNames } +
(classesToUnions[iface.name]?.map {it.name} ?: emptyList())
if (superTypesWithCalls.isNotEmpty()) {
superTypesWithCalls.joinTo(this, ", ", " : ")
}
appendln (" {")
val superAttributes = superTypes.flatMap { it.memberAttributes }.distinct()
val superFunctions = superTypes.flatMap { it.memberFunctions }.distinct()
val superProtos = superAttributes.map { it.proto } merge superFunctions.map { it.proto }
iface.memberAttributes.filter { it !in superAttributes }.forEach { arg ->
renderAttributeDeclaration(allTypes.keySet(), arg, arg.proto in superProtos)
}
iface.memberFunctions.filter { it !in superFunctions }.forEach {
renderFunction(allTypes.keySet(), it, it.proto in superProtos)
}
if (iface.constnats.isNotEmpty()) {
appendln("companion object {")
iface.constnats.forEach {
renderAttributeDeclaration(allTypes.keySet(), it, false)
}
appendln("}")
}
appendln("}")
}
fun <O : Appendable> O.render(ifaces: List<GenerateTraitOrClass>) {
val all = ifaces.groupBy { it.name }.mapValues { it.getValue().single() }
val unionTypes = collectUnionTypes(all)
val unionTypeTraits = generateUnionTypeTraits(unionTypes)
val allUnions = unionTypeTraits.groupBy { it.name }.mapValues { it.getValue().single() }
val classesToUnions = unionTypes.flatMap { unionType -> unionType.types.map { it to unionType } }.groupBy { it.first }.mapValues { it.getValue().map { it.second } }
ifaces.forEach {
render(all + allUnions, classesToUnions, it)
}
unionTypeTraits.forEach {
render(all, emptyMap(), it)
}
}
@@ -0,0 +1,53 @@
package org.jetbrains.idl2k
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.parser.Tag
import java.net.URL
val urls = listOf(
"https://raw.githubusercontent.com/whatwg/html-mirror/master/source",
"https://html.spec.whatwg.org/",
"https://raw.githubusercontent.com/whatwg/dom/master/dom.html",
"http://www.w3.org/TR/uievents/",
"https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html",
"https://raw.githubusercontent.com/whatwg/xhr/master/Overview.src.html",
"https://raw.githubusercontent.com/w3c/FileAPI/gh-pages/index.html",
"https://raw.githubusercontent.com/whatwg/notifications/master/notifications.html",
"https://raw.githubusercontent.com/whatwg/fullscreen/master/Overview.src.html",
"http://www.w3.org/TR/DOM-Parsing/",
"http://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html",
"https://raw.githubusercontent.com/whatwg/fetch/master/Overview.src.html",
"http://www.w3.org/TR/vibration/",
"http://dev.w3.org/csswg/cssom/"
)
private fun extractIDLText(url: String, out: StringBuilder) {
// val soup = Jsoup.connect(url).validateTLSCertificates(false).ignoreHttpErrors(true).get()
val soup = Jsoup.parse(URL(url).readText())
fun append(it : Element) {
if (!it.tag().preserveWhitespace()) {
return append(Element(Tag.valueOf("pre"), it.baseUri()).appendChild(it))
}
val text = it.text()
out.appendln(text)
if (!text.trimEnd().endsWith(";")) {
out.appendln(";")
}
}
soup.select("pre.idl").filter {!it.hasClass("extract")}.forEach(::append)
soup.select("code.idl-code").forEach(::append)
soup.select("spec-idl").forEach(::append)
}
fun getAllIDLs(): String =
StringBuilder {
urls.forEach {
extractIDLText(it, this)
}
// appendln(constantPart)
}.toString()
@@ -0,0 +1,445 @@
/*
* Copyright 2010-2015 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.idl2k
import org.antlr.webidl.WebIDLBaseListener
import org.antlr.webidl.WebIDLLexer
import org.antlr.webidl.WebIDLParser
import org.antlr.webidl.WebIDLParser.*
import org.antlr.v4.runtime.ANTLRInputStream
import org.antlr.v4.runtime.BufferedTokenStream
import org.antlr.v4.runtime.CommonTokenStream
import org.antlr.v4.runtime.ParserRuleContext
import org.antlr.v4.runtime.tree.TerminalNode
import org.antlr.webidl.WebIDLBaseVisitor
import org.jsoup.Jsoup
import java.io.File
import java.io.Reader
import java.io.StringReader
import java.net.URL
import java.util.*
data class ExtendedAttribute(val name : String?, val call : String, val arguments : List<Attribute>)
data class Operation(val name : String, val returnType : String, val parameters : List<Attribute>, val attributes : List<ExtendedAttribute>)
data class Attribute(val name : String, val type : String, val readOnly : Boolean, val defaultValue : String? = null, val vararg : Boolean)
data class Constant(val name : String, val type : String, val value : String?)
enum class DefinitionType {
INTERFACE
TYPEDEF
EXTENSION_INTERFACE
ENUM
DICTIONARY
}
trait Definition
data class TypedefDefinition(val from : String, val to : String) : Definition
data class InterfaceDefinition(val name : String, val extendedAttributes: List<ExtendedAttribute>, val operations : List<Operation>, val attributes : List<Attribute>, val superTypes : List<String>, val constants : List<Constant>, val dictionary : Boolean = false) : Definition
data class ExtensionInterfaceDefinition(val name : String, val implements : String) : Definition
data class EnumDefinition(val name : String) : Definition
class ExtendedAttributeArgumentsParser : WebIDLBaseVisitor<List<Attribute>>() {
private val arguments = ArrayList<Attribute>()
override fun defaultResult(): List<Attribute> = arguments
override fun visitOptionalOrRequiredArgument(ctx: WebIDLParser.OptionalOrRequiredArgumentContext): List<Attribute> {
val attributeVisitor = AttributeVisitor(false)
attributeVisitor.visit(ctx)
val parameter = attributeVisitor.visitChildren(ctx)
arguments.add(parameter)
visitChildren(ctx)
return defaultResult()
}
}
class ExtendedAttributeParser : WebIDLBaseVisitor<ExtendedAttribute>() {
private var name : String? = null
private var call : String = ""
private val arguments = ArrayList<Attribute>()
override fun defaultResult(): ExtendedAttribute = ExtendedAttribute(name, call, arguments)
override fun visitExtendedAttribute(ctx: WebIDLParser.ExtendedAttributeContext): ExtendedAttribute {
call = ctx.children?.filter {it is TerminalNode && it.getSymbol().getType() == WebIDLLexer.IDENTIFIER_WEBIDL}?.firstOrNull()?.getText() ?: ""
visitChildren(ctx)
return defaultResult()
}
override fun visitArgumentList(ctx: WebIDLParser.ArgumentListContext): ExtendedAttribute {
arguments.addAll(ExtendedAttributeArgumentsParser().visitChildren(ctx))
return defaultResult()
}
override fun visitIdentifierList(ctx : IdentifierListContext) : ExtendedAttribute {
object : WebIDLBaseVisitor<Unit>() {
override fun visitTerminal(node : TerminalNode) {
if (node.getSymbol().getType() == WebIDLLexer.IDENTIFIER_WEBIDL) {
arguments.add(Attribute(node.getText(), "any", true, vararg = false))
}
}
}.visitChildren(ctx)
return defaultResult()
}
override fun visitExtendedAttributeNamePart(ctx: WebIDLParser.ExtendedAttributeNamePartContext): ExtendedAttribute {
name = getName(ctx)
return defaultResult()
}
}
class UnionTypeVisitor : WebIDLBaseVisitor<List<String>>() {
val list = ArrayList<String>()
override fun defaultResult() = list
override fun visitUnionMemberType(ctx: WebIDLParser.UnionMemberTypeContext): List<String> {
list.add(TypeVisitor().visitChildren(ctx))
return list
}
}
class TypeVisitor : WebIDLBaseVisitor<String>() {
private var type = ""
override fun defaultResult() = type
override fun visitNonAnyType(ctx: WebIDLParser.NonAnyTypeContext): String {
type = ctx.getText()
return type
}
override fun visitUnionType(ctx: WebIDLParser.UnionTypeContext): String {
type = "Union<" + UnionTypeVisitor().visitChildren(ctx).joinToString(",") + ">"
return type
}
override fun visitTerminal(node: TerminalNode): String {
type = node.getText()
return type
}
}
class OperationVisitor(val attributes : List<ExtendedAttribute>) : WebIDLBaseVisitor<Operation>() {
private var name : String = ""
private var returnType : String = ""
private val parameters = ArrayList<Attribute>()
private val exts = ArrayList<ExtendedAttribute>()
override fun defaultResult() = Operation(name, returnType, parameters, attributes + exts)
override fun visitOptionalIdentifier(ctx: OptionalIdentifierContext): Operation {
name = ctx.getText()
return defaultResult()
}
override fun visitSpecial(ctx: WebIDLParser.SpecialContext): Operation {
if (ctx.children != null) {
exts.add(ExtendedAttribute(call = ctx.getText(), name = null, arguments = emptyList()))
}
return defaultResult()
}
override fun visitReturnType(ctx: ReturnTypeContext): Operation {
returnType = TypeVisitor().visit(ctx)
return defaultResult()
}
override fun visitOptionalOrRequiredArgument(ctx: WebIDLParser.OptionalOrRequiredArgumentContext): Operation {
val attributeVisitor = AttributeVisitor(false)
attributeVisitor.visit(ctx)
val parameter = attributeVisitor.visitChildren(ctx)
parameters.add(parameter)
return defaultResult()
}
}
class AttributeVisitor(val readOnly : Boolean) : WebIDLBaseVisitor<Attribute>() {
var type : String = ""
var name : String = ""
var defaultValue : String? = null
var vararg : Boolean = false
override fun defaultResult() : Attribute = Attribute(name, type, readOnly, defaultValue, vararg)
override fun visitType(ctx: WebIDLParser.TypeContext): Attribute {
type = TypeVisitor().visit(ctx)
return defaultResult()
}
override fun visitOptionalOrRequiredArgument(ctx: WebIDLParser.OptionalOrRequiredArgumentContext): Attribute {
if (ctx.children?.any {it is TerminalNode && it.getText() == "optional"} ?: false) {
defaultValue = "noImpl"
}
return visitChildren(ctx)
}
override fun visitAttributeRest(ctx: WebIDLParser.AttributeRestContext): Attribute {
try {
name = getName(ctx)
} catch (ignore : Throwable) {
name = ctx.children.filter { it is TerminalNode}.filter {it.getText() != ";"}.last().getText()
}
return defaultResult()
}
override fun visitArgumentName(ctx: WebIDLParser.ArgumentNameContext): Attribute {
try {
name = getName(ctx)
} catch (ignore : Throwable) {
name = ctx.getText()
}
return defaultResult()
}
override fun visitDefaultValue(ctx: WebIDLParser.DefaultValueContext): Attribute {
defaultValue = ctx.getText()
return defaultResult()
}
override fun visitEllipsis(ctx: WebIDLParser.EllipsisContext): Attribute {
vararg = vararg || "..." in ctx.getText()
return defaultResult()
}
}
class ConstantVisitor(val attributes : List<ExtendedAttribute>) : WebIDLBaseVisitor<Constant>() {
var type : String = ""
var name : String = ""
var value : String? = null
override fun defaultResult() : Constant = Constant(name, type, value)
override fun visitConst_(ctx: WebIDLParser.Const_Context): Constant {
name = getName(ctx)
return visitChildren(ctx)
}
override fun visitConstType(ctx: WebIDLParser.ConstTypeContext): Constant {
type = ctx.getText()
return defaultResult()
}
override fun visitConstValue(ctx: WebIDLParser.ConstValueContext): Constant {
value = ctx.getText()
return defaultResult()
}
}
class DefinitionVisitor(val extendedAttributes: List<ExtendedAttribute>) : WebIDLBaseVisitor<Definition>() {
private var type : DefinitionType = DefinitionType.INTERFACE
private var name = ""
private val memberAttributes = ArrayList<ExtendedAttribute>()
private val operations = ArrayList<Operation>()
private val attributes = ArrayList<Attribute>()
private var readOnly : Boolean = false
private val inherited = ArrayList<String>()
private var singleType : String? = null
private var implements : String? = null
private val constants = ArrayList<Constant>()
override fun defaultResult(): Definition = when(type) {
DefinitionType.INTERFACE -> InterfaceDefinition(name, extendedAttributes, operations, attributes, inherited, constants)
DefinitionType.DICTIONARY -> InterfaceDefinition(name, extendedAttributes, operations, attributes, inherited, constants, true)
DefinitionType.EXTENSION_INTERFACE -> ExtensionInterfaceDefinition(name, implements ?: "")
DefinitionType.TYPEDEF -> TypedefDefinition(singleType ?: "", name)
DefinitionType.ENUM -> EnumDefinition(name)
}
override fun visitInterface_(ctx: Interface_Context) : Definition {
name = getName(ctx)
visitChildren(ctx)
return defaultResult()
}
override fun visitPartialInterface(ctx: WebIDLParser.PartialInterfaceContext): Definition {
name = getName(ctx)
visitChildren(ctx)
return defaultResult()
}
override fun visitTypedef(ctx: WebIDLParser.TypedefContext): Definition {
type = DefinitionType.TYPEDEF
name = getName(ctx)
visitChildren(ctx)
return defaultResult()
}
override fun visitEnum_(ctx: Enum_Context): Definition {
type = DefinitionType.ENUM
name = getName(ctx)
return defaultResult()
}
override fun visitDictionary(ctx: DictionaryContext): Definition {
type = DefinitionType.DICTIONARY
name = getName(ctx)
return visitChildren(ctx)
}
override fun visitDictionaryMember(ctx: DictionaryMemberContext): Definition {
val name = ctx.children
?.filter {it is TerminalNode && it.getSymbol().getType() == WebIDLLexer.IDENTIFIER_WEBIDL}
?.first { it.getText() != "" }
?.getText()
val type = TypeVisitor().visit(ctx)
val defaultValue = object : WebIDLBaseVisitor<String?>() {
private var value : String? = null
override fun defaultResult() = value
override fun visitDefaultValue(ctx2: DefaultValueContext) : String? {
value = ctx2.getText()
return value
}
}.visit(ctx)
attributes.add(Attribute(name ?: "", type, false, defaultValue, false))
return defaultResult()
}
override fun visitImplementsStatement(ctx: ImplementsStatementContext): Definition {
val identifiers = ctx.children.filter {it is TerminalNode && it.getSymbol().getType() == WebIDLLexer.IDENTIFIER_WEBIDL}.map {it.getText()}
if (identifiers.size() >= 2) {
type = DefinitionType.EXTENSION_INTERFACE
name = identifiers[0]
implements = identifiers[1]
visitChildren(ctx)
}
return defaultResult()
}
override fun visitSingleType(ctx: SingleTypeContext): Definition {
singleType = ctx.getText()
return defaultResult()
}
override fun visitOperation(ctx: OperationContext) : Definition {
with(OperationVisitor(memberAttributes.toList())) {
operations.add(visit(ctx))
}
memberAttributes.clear()
return defaultResult()
}
override fun visitInheritance(ctx: WebIDLParser.InheritanceContext): Definition {
if (ctx.children != null && ctx.isEmpty().not()) {
inherited.add(getName(ctx))
}
return defaultResult()
}
override fun visitReadOnly(ctx: WebIDLParser.ReadOnlyContext): Definition {
readOnly = true
visitChildren(ctx)
readOnly = false
return defaultResult()
}
override fun visitAttributeRest(ctx: WebIDLParser.AttributeRestContext): Definition {
with(AttributeVisitor(readOnly)) {
visit(ctx)
this@DefinitionVisitor.attributes.add(visitChildren(ctx))
}
return defaultResult()
}
override fun visitConst_(ctx: WebIDLParser.Const_Context): Definition {
constants.add(ConstantVisitor(memberAttributes.toList()).visit(ctx))
memberAttributes.clear()
return defaultResult()
}
override fun visitExtendedAttribute(ctx: ExtendedAttributeContext) : Definition {
val att = with(ExtendedAttributeParser()) {
visit(ctx)
}
memberAttributes.add(att)
return defaultResult()
}
}
private fun getName(ctx: ParserRuleContext) = ctx.children.first {it is TerminalNode && it.getSymbol().getType() == WebIDLLexer.IDENTIFIER_WEBIDL}.getText()
fun parseIDL(reader : Reader) : Repository {
val ll = WebIDLLexer(ANTLRInputStream(reader))
val pp = WebIDLParser(CommonTokenStream(ll))
val idl = pp.webIDL()
val declarations = ArrayList<Definition>()
idl.accept(object : WebIDLBaseVisitor<Unit>() {
val extendedAttributes = ArrayList<ExtendedAttribute>()
override fun visitDefinition(ctx: WebIDLParser.DefinitionContext) {
val declaration = DefinitionVisitor(extendedAttributes.toList()).visitChildren(ctx)
extendedAttributes.clear()
declarations.add(declaration)
}
override fun visitExtendedAttribute(ctx: ExtendedAttributeContext?) {
val att = with(ExtendedAttributeParser()) {
visit(ctx)
}
extendedAttributes.add(att)
}
})
return Repository(
declarations.filterIsInstance<InterfaceDefinition>().filter {it.name.isEmpty().not()}.groupBy { it.name }.mapValues { it.getValue().reduce(::merge) },
declarations.filterIsInstance<TypedefDefinition>().groupBy { it.to }.mapValues { it.getValue().first() },
declarations.filterIsInstance<ExtensionInterfaceDefinition>().groupBy { it.name }.mapValues { it.getValue().map {it.implements} },
declarations.filterIsInstance<EnumDefinition>().groupBy { it.name }.mapValues { it.getValue().reduce {a, b -> a} }
)
}
fun merge(i1 : InterfaceDefinition, i2 : InterfaceDefinition) : InterfaceDefinition {
require(i1.name == i2.name)
return InterfaceDefinition(i1.name,
extendedAttributes = i1.extendedAttributes merge i2.extendedAttributes,
operations = i1.operations merge i2.operations,
attributes = i1.attributes merge i2.attributes,
superTypes = i1.superTypes merge i2.superTypes,
constants = i1.constants merge i2.constants,
dictionary = i1.dictionary || i2.dictionary
)
}
fun <T> List<T>.merge(other : List<T>) = (this + other).distinct().toList()
@@ -0,0 +1,32 @@
package org.jetbrains.idl2k
import java.io.File
import java.io.StringReader
fun main(args: Array<String>) {
val idl = getAllIDLs()
val defs = parseIDL(StringReader(idl))
println("IDL dump:")
idl.lineSequence().forEachIndexed { i, line ->
println("${i.toString().padStart(4, ' ')}: ${line}")
}
println()
val definitions = mapDefinitions(defs, defs.interfaces.values())
File("../../../js/js.libraries/src/core/dom3.kt").writer().use { w ->
w.appendln("/*")
w.appendln(" * Generated file")
w.appendln(" * DO NOT EDIT")
w.appendln(" * ")
w.appendln(" * See libraries/tools/idl2k for details")
w.appendln(" */")
w.appendln()
w.appendln("package org.w3c.dom3")
w.appendln()
w.render(definitions)
}
}
@@ -0,0 +1,58 @@
/*
* Copyright 2010-2015 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.idl2k
data class Repository(
val interfaces: Map<String, InterfaceDefinition>,
val typeDefs: Map<String, TypedefDefinition>,
val externals: Map<String, List<String>>,
val enums: Map<String, EnumDefinition>
)
data class GenerateAttribute(val name: String, val type: String, val initializer: String?, val getterSetterNoImpl: Boolean, val readOnly: Boolean, val override: Boolean, var vararg : Boolean) {
val getterNoImpl: Boolean
get() = getterSetterNoImpl
val setterNoImpl: Boolean
get() = getterSetterNoImpl && !readOnly
}
val GenerateAttribute.proto : String
get() = "$name:$type"
enum class NativeGetterOrSetter {
NONE
GETTER
SETTER
}
enum class GenerateDefinitionType {
TRAIT
CLASS
}
data class GenerateFunction(val name: String, val returnType: String, val arguments: List<GenerateAttribute>, val native : NativeGetterOrSetter)
data class GenerateFunctionCall(val name: String, val arguments: List<String>)
class GenerateTraitOrClass(val name: String,
val type : GenerateDefinitionType,
val superTypes: List<String>,
val memberAttributes: List<GenerateAttribute>,
val memberFunctions: List<GenerateFunction>,
val constnats : List<GenerateAttribute>,
val constructor: GenerateFunction?,
val superConstructorCalls: List<GenerateFunctionCall>)
val GenerateFunction.proto : String
get() = arguments.map {it.type}.joinToString(", ", "$name(", ")")
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
mkdir -p ~/tmp/ca
cd ~/tmp/ca
curl http://www.startssl.com/certs/ca.crt -O
curl http://www.startssl.com/certs/sub.class1.server.ca.crt -O
curl http://www.startssl.com/certs/sub.class2.server.ca.crt -O
curl http://www.startssl.com/certs/sub.class3.server.ca.crt -O
curl http://www.startssl.com/certs/sub.class4.server.ca.crt -O
for crt in *.crt; do
keytool -import -trustcacerts -keystore ${JAVA_HOME}/jre/lib/security/cacerts -storepass changeit -noprompt -alias ${crt} -file ${crt};
done
@@ -14,6 +14,7 @@ import org.w3c.dom.events.*
* This tool generates JavaScript stubs for classes available in the JDK which are already available in the browser environment
* such as the W3C DOM
*/
deprecated("You shouldn't use it anymore as there is idl2k tool and DOM3 specification")
fun generateDomAPI(file: File): Unit {
val packageName = "org.w3c.dom"
val imports = ""
@@ -87,6 +88,7 @@ $imports
val interfaces = klass.getInterfaces()
val extends = if (interfaces != null && interfaces.size == 1) ": ${interfaces[0]?.getSimpleName()}" else ""
println("deprecated(\"Use org.w3c.dom3 instead\")")
println("native public interface ${klass.getSimpleName()}$extends {")
val methods = klass.getDeclaredMethods().sortBy { it.getName()!! }
@@ -133,6 +135,7 @@ $imports
if (typeName == null) {
validMethods.add(pk.method)
} else {
println(" deprecated(\"Use org.w3c.dom3 instead\")")
println(" public ${pk.kind} ${pk.name}: ${typeName}")
}
}
@@ -143,6 +146,7 @@ $imports
var counter = 0
val parameters = parameterTypes.map{ "arg${++counter}: ${parameterTypeName(it)}" }.makeString(", ")
val returnType = simpleTypeName(method.getReturnType())
println(" deprecated(\"Use org.w3c.dom3 instead\")")
println(" public fun ${method.getName()}($parameters): $returnType = noImpl")
}
}
@@ -160,6 +164,7 @@ $imports
val value = field.get(null)
if (value != null) {
val fieldType = simpleTypeName(field.getType())
println(" deprecated(\"Use org.w3c.dom3 instead\")")
println(" public val ${field.getName()}: $fieldType = $value")
}
} catch (e: Exception) {