/
TSDefParser.scala
300 lines (229 loc) · 8.82 KB
/
TSDefParser.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/* TypeScript importer for Scala.js
* Copyright 2013-2014 LAMP/EPFL
* @author Sébastien Doeraene
*/
package org.scalajs.tools.tsimporter.parser
import org.scalajs.tools.tsimporter.Trees._
import java.io.File
import scala.collection.mutable.ListBuffer
import scala.util.parsing.combinator._
import scala.util.parsing.combinator.token._
import scala.util.parsing.combinator.syntactical._
import scala.util.parsing.input._
class TSDefParser extends StdTokenParsers with ImplicitConversions {
type Tokens = StdTokens
val lexical: TSDefLexical = new TSDefLexical
lexical.reserved ++= List(
// Value keywords
"true", "false",
// Current JavaScript keywords
"break", "case", "catch", "continue", "debugger", "default", "delete",
"do", "else", "finally", "for", "function", "if", "in", "instanceof",
"new", "return", "switch", "this", "throw", "try", "typeof", "var",
"void", "while", "with",
// Future reserved keywords - some used in TypeScript
"class", "const", "enum", "export", "extends", "import", "super",
"readonly",
// Future reserved keywords in Strict mode - some used in TypeScript
"implements", "interface", "let", "package", "private", "protected",
"public", "static", "yield",
// Additional keywords of TypeScript
"declare", "module", "type", "namespace"
)
lexical.delimiters ++= List(
"{", "}", "(", ")", "[", "]", "<", ">",
".", ";", ",", "?", ":", "=", "|",
// TypeScript-specific
"...", "=>"
)
def parseDefinitions(input: Reader[Char]) =
phrase(ambientDeclarations)(new lexical.Scanner(input))
lazy val ambientDeclarations: Parser[List[DeclTree]] =
rep(ambientDeclaration)
lazy val ambientDeclaration: Parser[DeclTree] =
opt("declare") ~> opt("export") ~> moduleElementDecl1
lazy val ambientModuleDecl: Parser[DeclTree] =
("module" | "namespace") ~> rep1sep(propertyName, ".") ~ moduleBody ^^ {
case nameParts ~ body =>
nameParts.init.foldRight(ModuleDecl(nameParts.last, body)) {
(name, inner) => ModuleDecl(name, inner :: Nil)
}
}
lazy val moduleBody: Parser[List[DeclTree]] =
"{" ~> rep(moduleElementDecl) <~ "}" ^^ (_.flatten)
lazy val moduleElementDecl: Parser[Option[DeclTree]] = (
"export" ~> (
moduleElementDecl1 ^^ (Some(_))
| "=" ~> identifier <~ ";" ^^^ None)
| moduleElementDecl1 ^^ (Some(_))
)
lazy val moduleElementDecl1: Parser[DeclTree] = (
ambientModuleDecl | ambientVarDecl | ambientFunctionDecl
| ambientEnumDecl | ambientClassDecl | ambientInterfaceDecl
| ambientConstDecl | typeAliasDecl
)
lazy val ambientVarDecl: Parser[DeclTree] =
"var" ~> identifier ~ optTypeAnnotation <~ opt(";") ^^ VarDecl
lazy val ambientConstDecl: Parser[DeclTree] =
"const" ~> identifier ~ optTypeAnnotation <~ opt(";") ^^ ConstDecl
lazy val ambientFunctionDecl: Parser[DeclTree] =
"function" ~> identifier ~ functionSignature <~ opt(";") ^^ FunctionDecl
lazy val ambientEnumDecl: Parser[DeclTree] =
"enum" ~> typeName ~ ("{" ~> ambientEnumBody <~ "}") ^^ EnumDecl
lazy val ambientEnumBody: Parser[List[Ident]] =
repsep(identifier <~ opt("=" ~ numericLit), ",") <~ opt(",")
lazy val ambientClassDecl: Parser[DeclTree] =
"class" ~> typeName ~ tparams ~ classParent ~ classImplements ~ memberBlock <~ opt(";") ^^ ClassDecl
lazy val ambientInterfaceDecl: Parser[DeclTree] =
"interface" ~> typeName ~ tparams ~ intfInheritance ~ memberBlock <~ opt(";") ^^ InterfaceDecl
lazy val typeAliasDecl: Parser[DeclTree] =
"type" ~> typeName ~ tparams ~ ("=" ~> typeDesc) <~ opt(";") ^^ TypeAliasDecl
lazy val tparams = (
"<" ~> rep1sep(typeParam, ",") <~ ">"
| success(Nil)
)
lazy val typeParam: Parser[TypeParam] =
typeName ~ opt("extends" ~> typeRef) ^^ TypeParam
lazy val classParent =
opt("extends" ~> typeRef)
lazy val classImplements = (
"implements" ~> repsep(typeRef, ",")
| success(Nil)
)
lazy val intfInheritance = (
"extends" ~> repsep(typeRef, ",")
| success(Nil)
)
lazy val functionSignature =
tparams ~ ("(" ~> repsep(functionParam, ",") <~ ")") ~ optResultType ^^ FunSignature
lazy val functionParam =
repeatedParamMarker ~ identifier ~ optionalMarker ~ optParamType ^^ {
case false ~ i ~ o ~ t =>
FunParam(i, o, t)
case _ ~ i ~ o ~ Some(ArrayType(t)) =>
FunParam(i, o, Some(RepeatedType(t)))
case _ ~ i ~ o ~ t =>
Console.err.println(
s"Warning: Dropping repeated marker of param $i because its type $t is not an array type")
FunParam(i, o, t)
}
lazy val repeatedParamMarker =
opt("...") ^^ (_.isDefined)
lazy val optionalMarker =
opt("?") ^^ (_.isDefined)
lazy val optParamType =
opt(":" ~> paramType)
lazy val paramType: Parser[TypeTree] = (
typeDesc
| stringLiteral ^^ ConstantType
)
lazy val optResultType =
opt(":" ~> resultType)
lazy val resultType: Parser[TypeTree] = (
("void" ^^^ TypeRef(CoreType("void")))
| typeDesc
)
lazy val optTypeAnnotation =
opt(typeAnnotation)
lazy val typeAnnotation =
":" ~> typeDesc
lazy val typeDesc: Parser[TypeTree] =
rep1sep(singleTypeDesc, "|") ^^ {
_.reduceLeft(UnionType)
}
lazy val singleTypeDesc: Parser[TypeTree] =
baseTypeDesc ~ rep("[" ~ "]") ^^ {
case base ~ arrayDims =>
(base /: arrayDims) {
(elem, _) => ArrayType(elem)
}
}
lazy val baseTypeDesc: Parser[TypeTree] = (
typeRef
| objectType
| functionType
| stringType
| typeQuery
| tupleType
| "(" ~> typeDesc <~ ")"
)
lazy val typeRef: Parser[TypeRef] =
baseTypeRef ~ opt(typeArgs) ^^ {
case base ~ optTargs =>
TypeRef(base, optTargs getOrElse Nil)
}
lazy val baseTypeRef: Parser[BaseTypeRef] =
rep1sep("void" | ident, ".") ^^ { parts =>
if (parts.tail.isEmpty) typeNameToTypeRef(parts.head)
else QualifiedTypeName(parts.init map Ident, TypeName(parts.last))
}
lazy val typeArgs: Parser[List[TypeTree]] =
"<" ~> rep1sep(typeDesc, ",") <~ ">"
lazy val functionType: Parser[TypeTree] =
tparams ~ ("(" ~> repsep(functionParam, ",") <~ ")") ~ ("=>" ~> resultType) ^^ {
case tparams ~ params ~ resultType =>
FunctionType(FunSignature(tparams, params, Some(resultType)))
}
lazy val stringType: Parser[TypeTree] =
stringLiteral ^^ ConstantType
lazy val typeQuery: Parser[TypeTree] =
"typeof" ~> rep1sep(ident, ".") ^^ { parts =>
TypeQuery(QualifiedIdent(parts.init.map(Ident), Ident(parts.last)))
}
lazy val tupleType: Parser[TypeTree] =
"[" ~> rep1sep(typeDesc, ",") <~ "]" ^^ { parts =>
TupleType(parts)
}
lazy val objectType: Parser[TypeTree] =
memberBlock ^^ ObjectType
lazy val memberBlock: Parser[List[MemberTree]] =
"{" ~> rep(typeMember <~ opt(";" | ",")) <~ "}"
lazy val typeMember: Parser[MemberTree] =
callMember | constructorMember | indexMember | namedMember
lazy val callMember: Parser[MemberTree] =
functionSignature ^^ CallMember
lazy val constructorMember: Parser[MemberTree] =
"new" ~> functionSignature ^^ ConstructorMember
lazy val indexMember: Parser[MemberTree] =
("[" ~> identifier ~ typeAnnotation <~ "]") ~ typeAnnotation ^^ IndexMember
lazy val namedMember: Parser[MemberTree] =
modifiers ~ propertyName ~ optionalMarker >> {
case mods ~ name ~ optional => (
functionSignature ^^ (FunctionMember(name, optional, _, mods))
| typeAnnotation ^^ (PropertyMember(name, optional, _, mods))
)
}
lazy val modifiers: Parser[Modifiers] =
rep(modifier).map(_.toSet)
lazy val modifier: Parser[Modifier] = (
"static" ^^^ Modifier.Static
| "public" ^^^ Modifier.Public
| "readonly" ^^^ Modifier.ReadOnly
| "protected" ^^^ Modifier.Protected
)
lazy val identifier =
identifierName ^^ Ident
lazy val typeName =
identifierName ^^ TypeName
lazy val identifierName = accept("IdentifierName", {
case lexical.Identifier(chars) => chars
case lexical.Keyword(chars) if chars.forall(Character.isLetter) => chars
})
lazy val propertyName: Parser[PropertyName] =
identifier | stringLiteral
lazy val stringLiteral: Parser[StringLiteral] =
stringLit ^^ StringLiteral
private val isCoreTypeName =
Set("any", "void", "number", "bool", "boolean", "string", "null", "undefined", "never")
def typeNameToTypeRef(name: String): BaseTypeRef =
if (isCoreTypeName(name)) CoreType(name)
else TypeName(name)
object ArrayType {
def apply(elem: TypeTree): TypeRef =
TypeRef(TypeName("Array"), List(elem))
def unapply(typeRef: TypeRef): Option[TypeTree] = typeRef match {
case TypeRef(TypeName("Array"), List(elem)) => Some(elem)
case _ => None
}
}
}