1 /**
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <ir/expressions/literals/bigIntLiteral.h>
17 #include <ir/expressions/literals/numberLiteral.h>
18 #include <ir/expressions/literals/stringLiteral.h>
19 #include <ir/expressions/functionExpression.h>
20 #include <ir/expressions/memberExpression.h>
21 #include <ir/expressions/identifier.h>
22 #include <ir/statements/variableDeclarator.h>
23 #include <ir/base/property.h>
24 #include <ir/base/scriptFunction.h>
25 #include <ir/base/spreadElement.h>
26 #include <ir/ts/tsIndexSignature.h>
27 #include <ir/ts/tsMethodSignature.h>
28 #include <ir/ts/tsTypeLiteral.h>
29 #include <ir/ts/tsPropertySignature.h>
30 #include <ir/ts/tsSignatureDeclaration.h>
31 #include <ir/ts/tsInterfaceDeclaration.h>
32 #include <ir/ts/tsInterfaceHeritage.h>
33 #include <ir/ts/tsInterfaceBody.h>
34 #include <util/helpers.h>
35 #include <binder/variable.h>
36 #include <binder/scope.h>
37
38 #include <typescript/checker.h>
39 #include <typescript/types/indexInfo.h>
40
41 namespace panda::es2panda::checker {
42
CheckIndexConstraints(Type * type)43 void Checker::CheckIndexConstraints(Type *type)
44 {
45 if (!type->IsObjectType()) {
46 return;
47 }
48
49 ObjectType *objType = type->AsObjectType();
50 ResolveStructuredTypeMembers(objType);
51
52 IndexInfo *numberInfo = objType->NumberIndexInfo();
53 IndexInfo *stringInfo = objType->StringIndexInfo();
54 const ArenaVector<binder::LocalVariable *> &properties = objType->Properties();
55
56 if (numberInfo) {
57 for (auto *it : properties) {
58 if (it->HasFlag(binder::VariableFlags::NUMERIC_NAME)) {
59 Type *propType = GetTypeOfVariable(it);
60 IsTypeAssignableTo(propType, numberInfo->GetType(),
61 {"Property '", it->Name(), "' of type '", propType,
62 "' is not assignable to numeric index type '", numberInfo->GetType(), "'."},
63 it->Declaration()->Node()->Start());
64 }
65 }
66 }
67
68 if (stringInfo) {
69 for (auto *it : properties) {
70 Type *propType = GetTypeOfVariable(it);
71 IsTypeAssignableTo(propType, stringInfo->GetType(),
72 {"Property '", it->Name(), "' of type '", propType,
73 "' is not assignable to string index type '", stringInfo->GetType(), "'."},
74 it->Declaration()->Node()->Start());
75 }
76
77 if (numberInfo && !IsTypeAssignableTo(numberInfo->GetType(), stringInfo->GetType())) {
78 ThrowTypeError({"Number index info type ", numberInfo->GetType(),
79 " is not assignable to string index info type ", stringInfo->GetType(), "."},
80 numberInfo->Pos());
81 }
82 }
83 }
84
ResolveStructuredTypeMembers(Type * type)85 void Checker::ResolveStructuredTypeMembers(Type *type)
86 {
87 if (type->IsObjectType()) {
88 ObjectType *objType = type->AsObjectType();
89
90 if (objType->IsObjectLiteralType()) {
91 ResolveObjectTypeMembers(objType);
92 return;
93 }
94
95 if (objType->IsInterfaceType()) {
96 ResolveInterfaceOrClassTypeMembers(objType->AsInterfaceType());
97 return;
98 }
99 }
100
101 if (type->IsUnionType()) {
102 ResolveUnionTypeMembers(type->AsUnionType());
103 return;
104 }
105 }
106
ResolveUnionTypeMembers(UnionType * type)107 void Checker::ResolveUnionTypeMembers(UnionType *type)
108 {
109 if (type->MergedObjectType()) {
110 return;
111 }
112
113 ObjectDescriptor *desc = allocator_->New<ObjectDescriptor>(allocator_);
114 ArenaVector<Type *> stringInfoTypes(allocator_->Adapter());
115 ArenaVector<Type *> numberInfoTypes(allocator_->Adapter());
116 ArenaVector<Signature *> callSignatures(allocator_->Adapter());
117 ArenaVector<Signature *> constructSignatures(allocator_->Adapter());
118
119 for (auto *it : type->AsUnionType()->ConstituentTypes()) {
120 if (!it->IsObjectType()) {
121 continue;
122 }
123
124 ObjectType *objType = it->AsObjectType();
125 ResolveObjectTypeMembers(objType);
126
127 if (!objType->CallSignatures().empty()) {
128 for (auto *signature : objType->CallSignatures()) {
129 callSignatures.push_back(signature);
130 }
131 }
132
133 if (!objType->ConstructSignatures().empty()) {
134 for (auto *signature : objType->ConstructSignatures()) {
135 constructSignatures.push_back(signature);
136 }
137 }
138
139 if (objType->StringIndexInfo()) {
140 stringInfoTypes.push_back(objType->StringIndexInfo()->GetType());
141 }
142
143 if (objType->NumberIndexInfo()) {
144 numberInfoTypes.push_back(objType->NumberIndexInfo()->GetType());
145 }
146 }
147
148 desc->callSignatures = callSignatures;
149 desc->constructSignatures = constructSignatures;
150
151 if (!stringInfoTypes.empty()) {
152 desc->stringIndexInfo = allocator_->New<IndexInfo>(CreateUnionType(std::move(stringInfoTypes)), "x", false);
153 }
154
155 if (!numberInfoTypes.empty()) {
156 desc->numberIndexInfo = allocator_->New<IndexInfo>(CreateUnionType(std::move(numberInfoTypes)), "x", false);
157 }
158
159 ObjectType *mergedType = allocator_->New<ObjectLiteralType>(desc);
160 mergedType->AddObjectFlag(ObjectFlags::RESOLVED_MEMBERS);
161 type->SetMergedObjectType(mergedType);
162 }
163
ResolveInterfaceOrClassTypeMembers(InterfaceType * type)164 void Checker::ResolveInterfaceOrClassTypeMembers(InterfaceType *type)
165 {
166 if (type->HasObjectFlag(ObjectFlags::RESOLVED_MEMBERS)) {
167 return;
168 }
169
170 ResolveDeclaredMembers(type);
171 GetBaseTypes(type);
172
173 type->AddObjectFlag(ObjectFlags::RESOLVED_MEMBERS);
174 }
175
ResolveObjectTypeMembers(ObjectType * type)176 void Checker::ResolveObjectTypeMembers(ObjectType *type)
177 {
178 if (!type->IsObjectLiteralType() || type->HasObjectFlag(ObjectFlags::RESOLVED_MEMBERS)) {
179 return;
180 }
181
182 ASSERT(type->Variable() && type->Variable()->Declaration()->Node()->IsTSTypeLiteral());
183 const ir::TSTypeLiteral *typeLiteral = type->Variable()->Declaration()->Node()->AsTSTypeLiteral();
184 ArenaVector<const ir::TSSignatureDeclaration *> signatureDeclarations(allocator_->Adapter());
185 ArenaVector<const ir::TSIndexSignature *> indexDeclarations(allocator_->Adapter());
186
187 for (auto *it : typeLiteral->Members()) {
188 ResolvePropertiesOfObjectType(type, it, signatureDeclarations, indexDeclarations, false);
189 }
190
191 type->AddObjectFlag(ObjectFlags::RESOLVED_MEMBERS);
192
193 ResolveSignaturesOfObjectType(type, signatureDeclarations);
194 ResolveIndexInfosOfObjectType(type, indexDeclarations);
195 }
196
ResolvePropertiesOfObjectType(ObjectType * type,const ir::Expression * member,ArenaVector<const ir::TSSignatureDeclaration * > & signatureDeclarations,ArenaVector<const ir::TSIndexSignature * > & indexDeclarations,bool isInterface)197 void Checker::ResolvePropertiesOfObjectType(ObjectType *type, const ir::Expression *member,
198 ArenaVector<const ir::TSSignatureDeclaration *> &signatureDeclarations,
199 ArenaVector<const ir::TSIndexSignature *> &indexDeclarations,
200 bool isInterface)
201 {
202 if (member->IsTSPropertySignature()) {
203 binder::Variable *prop = member->AsTSPropertySignature()->Variable();
204
205 if (!isInterface ||
206 ValidateInterfaceMemberRedeclaration(type, prop, member->AsTSPropertySignature()->Key()->Start())) {
207 type->AddProperty(prop->AsLocalVariable());
208 }
209
210 return;
211 }
212
213 if (member->IsTSMethodSignature()) {
214 binder::Variable *method = member->AsTSMethodSignature()->Variable();
215
216 if (!isInterface ||
217 ValidateInterfaceMemberRedeclaration(type, method, member->AsTSMethodSignature()->Key()->Start())) {
218 type->AddProperty(method->AsLocalVariable());
219 }
220
221 return;
222 }
223
224 if (member->IsTSSignatureDeclaration()) {
225 signatureDeclarations.push_back(member->AsTSSignatureDeclaration());
226 return;
227 }
228
229 ASSERT(member->IsTSIndexSignature());
230 indexDeclarations.push_back(member->AsTSIndexSignature());
231 }
232
ResolveSignaturesOfObjectType(ObjectType * type,ArenaVector<const ir::TSSignatureDeclaration * > & signatureDeclarations)233 void Checker::ResolveSignaturesOfObjectType(ObjectType *type,
234 ArenaVector<const ir::TSSignatureDeclaration *> &signatureDeclarations)
235 {
236 for (auto *it : signatureDeclarations) {
237 Type *placeholderObj = it->Check(this);
238
239 if (it->AsTSSignatureDeclaration()->Kind() ==
240 ir::TSSignatureDeclaration::TSSignatureDeclarationKind::CALL_SIGNATURE) {
241 type->AddCallSignature(placeholderObj->AsObjectType()->CallSignatures()[0]);
242 continue;
243 }
244
245 type->AddConstructSignature(placeholderObj->AsObjectType()->ConstructSignatures()[0]);
246 }
247 }
ResolveIndexInfosOfObjectType(ObjectType * type,ArenaVector<const ir::TSIndexSignature * > & indexDeclarations)248 void Checker::ResolveIndexInfosOfObjectType(ObjectType *type,
249 ArenaVector<const ir::TSIndexSignature *> &indexDeclarations)
250 {
251 for (auto *it : indexDeclarations) {
252 Type *placeholderObj = it->Check(this);
253
254 if (it->AsTSIndexSignature()->Kind() == ir::TSIndexSignature::TSIndexSignatureKind::NUMBER) {
255 IndexInfo *numberInfo = placeholderObj->AsObjectType()->NumberIndexInfo();
256
257 if (type->NumberIndexInfo()) {
258 ThrowTypeError("Duplicated index signature for type 'number'", it->Start());
259 }
260
261 type->Desc()->numberIndexInfo = numberInfo;
262 continue;
263 }
264
265 IndexInfo *stringInfo = placeholderObj->AsObjectType()->StringIndexInfo();
266
267 if (type->StringIndexInfo()) {
268 ThrowTypeError("Duplicated index signature for type 'string'", it->Start());
269 }
270
271 type->Desc()->stringIndexInfo = stringInfo;
272 }
273 }
274
GetPropertyOfType(Type * type,const util::StringView & name,bool getPartial,binder::VariableFlags propagateFlags)275 binder::Variable *Checker::GetPropertyOfType(Type *type, const util::StringView &name, bool getPartial,
276 binder::VariableFlags propagateFlags)
277 {
278 if (type->IsObjectType()) {
279 ResolveObjectTypeMembers(type->AsObjectType());
280 return type->AsObjectType()->GetProperty(name, true);
281 }
282
283 if (type->IsUnionType()) {
284 return GetPropertyOfUnionType(type->AsUnionType(), name, getPartial, propagateFlags);
285 }
286
287 return nullptr;
288 }
289
GetPropertyOfUnionType(UnionType * type,const util::StringView & name,bool getPartial,binder::VariableFlags propagateFlags)290 binder::Variable *Checker::GetPropertyOfUnionType(UnionType *type, const util::StringView &name, bool getPartial,
291 binder::VariableFlags propagateFlags)
292 {
293 auto found = type->CachedSyntheticPropertis().find(name);
294 if (found != type->CachedSyntheticPropertis().end()) {
295 return found->second;
296 }
297
298 binder::VariableFlags flags = binder::VariableFlags::PROPERTY;
299 ArenaVector<Type *> collectedTypes(allocator_->Adapter());
300
301 for (auto *it : type->ConstituentTypes()) {
302 binder::Variable *prop = GetPropertyOfType(it, name);
303
304 if (!prop) {
305 if (it->IsArrayType()) {
306 collectedTypes.push_back(it->AsArrayType()->ElementType());
307 continue;
308 }
309
310 if (!it->IsObjectType()) {
311 if (getPartial) {
312 continue;
313 }
314
315 return nullptr;
316 }
317
318 ObjectType *objType = it->AsObjectType();
319
320 if (!objType->StringIndexInfo()) {
321 if (getPartial) {
322 continue;
323 }
324
325 return nullptr;
326 }
327
328 collectedTypes.push_back(objType->StringIndexInfo()->GetType());
329 continue;
330 }
331
332 prop->AddFlag(propagateFlags);
333
334 if (prop->HasFlag(binder::VariableFlags::OPTIONAL)) {
335 flags |= binder::VariableFlags::OPTIONAL;
336 }
337
338 collectedTypes.push_back(GetTypeOfVariable(prop));
339 }
340
341 if (collectedTypes.empty()) {
342 return nullptr;
343 }
344
345 binder::Variable *syntheticProp = binder::Scope::CreateVar(allocator_, name, flags, nullptr);
346 syntheticProp->SetTsType(CreateUnionType(std::move(collectedTypes)));
347 type->CachedSyntheticPropertis().insert({name, syntheticProp});
348 return syntheticProp;
349 }
350
CheckComputedPropertyName(const ir::Expression * key)351 Type *Checker::CheckComputedPropertyName(const ir::Expression *key)
352 {
353 auto found = nodeCache_.find(key);
354 if (found != nodeCache_.end()) {
355 return found->second;
356 }
357
358 Type *keyType = key->Check(this);
359
360 if (!keyType->HasTypeFlag(TypeFlag::STRING_LIKE | TypeFlag::NUMBER_LIKE)) {
361 ThrowTypeError(
362 "A computed property name in a type literal must refer to an expression whose type is a literal "
363 "type "
364 "or a 'unique symbol' type",
365 key->Start());
366 }
367
368 nodeCache_.insert({key, keyType});
369 return keyType;
370 }
371
GetApplicableIndexInfo(Type * type,Type * indexType)372 IndexInfo *Checker::GetApplicableIndexInfo(Type *type, Type *indexType)
373 {
374 ResolveStructuredTypeMembers(type);
375 bool getNumberInfo = indexType->HasTypeFlag(TypeFlag::NUMBER_LIKE);
376
377 if (type->IsObjectType()) {
378 if (getNumberInfo) {
379 return type->AsObjectType()->NumberIndexInfo();
380 }
381
382 return type->AsObjectType()->StringIndexInfo();
383 }
384
385 if (type->IsUnionType()) {
386 ASSERT(type->AsUnionType()->MergedObjectType());
387
388 if (getNumberInfo) {
389 return type->AsUnionType()->MergedObjectType()->NumberIndexInfo();
390 }
391
392 return type->AsUnionType()->MergedObjectType()->StringIndexInfo();
393 }
394
395 return nullptr;
396 }
397
GetPropertyTypeForIndexType(Type * type,Type * indexType)398 Type *Checker::GetPropertyTypeForIndexType(Type *type, Type *indexType)
399 {
400 if (type->IsArrayType()) {
401 return type->AsArrayType()->ElementType();
402 }
403
404 if (indexType->HasTypeFlag(TypeFlag::STRING_LITERAL | TypeFlag::NUMBER_LITERAL)) {
405 binder::Variable *prop = nullptr;
406
407 if (indexType->IsStringLiteralType()) {
408 prop = GetPropertyOfType(type, indexType->AsStringLiteralType()->Value());
409 } else {
410 util::StringView propName =
411 util::Helpers::ToStringView(allocator_, indexType->AsNumberLiteralType()->Value());
412 prop = GetPropertyOfType(type, propName);
413 }
414
415 if (prop) {
416 Type *propType = GetTypeOfVariable(prop);
417
418 if (prop->HasFlag(binder::VariableFlags::READONLY)) {
419 propType->AddTypeFlag(TypeFlag::READONLY);
420 }
421
422 return propType;
423 }
424 }
425
426 if (indexType->HasTypeFlag(TypeFlag::STRING_LIKE | TypeFlag::NUMBER_LIKE)) {
427 IndexInfo *indexInfo = GetApplicableIndexInfo(type, indexType);
428
429 if (indexInfo) {
430 Type *indexInfoType = indexInfo->GetType();
431
432 if (indexInfo->Readonly()) {
433 indexInfoType->AddTypeFlag(TypeFlag::READONLY);
434 }
435
436 return indexInfoType;
437 }
438 }
439
440 return nullptr;
441 }
442
GetBaseTypes(InterfaceType * type)443 ArenaVector<ObjectType *> Checker::GetBaseTypes(InterfaceType *type)
444 {
445 if (type->HasObjectFlag(ObjectFlags::RESOLVED_BASE_TYPES)) {
446 return type->Bases();
447 }
448
449 ASSERT(type->Variable() && type->Variable()->Declaration()->IsInterfaceDecl());
450 binder::InterfaceDecl *decl = type->Variable()->Declaration()->AsInterfaceDecl();
451
452 if (!typeStack_.insert(type).second) {
453 ThrowTypeError({"Type ", type->Name(), " recursively references itself as a base type."},
454 decl->Node()->AsTSInterfaceDeclaration()->Id()->Start());
455 }
456
457 for (const auto *declaration : decl->Decls()) {
458 if (declaration->Extends().empty()) {
459 continue;
460 }
461
462 for (const auto *extends : declaration->Extends()) {
463 Type *baseType = extends->Expr()->AsTypeNode()->GetType(this);
464
465 if (!baseType->HasTypeFlag(TypeFlag::OBJECT | TypeFlag::NON_PRIMITIVE | TypeFlag::ANY)) {
466 ThrowTypeError(
467 "An interface can only extend an object type or intersection of object types with statically "
468 "known "
469 "members",
470 extends->Start());
471 }
472
473 if (!baseType->IsObjectType()) {
474 continue;
475 }
476
477 ObjectType *baseObj = baseType->AsObjectType();
478
479 if (baseType == type) {
480 ThrowTypeError({"Type ", type->Name(), " recursively references itself as a base type."},
481 decl->Node()->AsTSInterfaceDeclaration()->Id()->Start());
482 }
483
484 type->AddBase(baseObj);
485
486 if (!baseObj->IsInterfaceType()) {
487 continue;
488 }
489
490 ArenaVector<ObjectType *> extendsBases = GetBaseTypes(baseObj->AsInterfaceType());
491 for (auto *extendBase : extendsBases) {
492 if (extendBase == type) {
493 ThrowTypeError({"Type ", type->Name(), " recursively references itself as a base type."},
494 decl->Node()->AsTSInterfaceDeclaration()->Id()->Start());
495 }
496 }
497 }
498 }
499
500 type->AddObjectFlag(ObjectFlags::RESOLVED_BASE_TYPES);
501 typeStack_.erase(type);
502 return type->Bases();
503 }
504
ResolveDeclaredMembers(InterfaceType * type)505 void Checker::ResolveDeclaredMembers(InterfaceType *type)
506 {
507 if (type->HasObjectFlag(ObjectFlags::RESOLVED_DECLARED_MEMBERS)) {
508 return;
509 }
510
511 ASSERT(type->Variable() && type->Variable()->Declaration()->IsInterfaceDecl());
512 binder::InterfaceDecl *decl = type->Variable()->Declaration()->AsInterfaceDecl();
513
514 ArenaVector<const ir::TSSignatureDeclaration *> signatureDeclarations(allocator_->Adapter());
515 ArenaVector<const ir::TSIndexSignature *> indexDeclarations(allocator_->Adapter());
516
517 for (const auto *declaration : decl->Decls()) {
518 for (const auto *member : declaration->Body()->Body()) {
519 ResolvePropertiesOfObjectType(type, member, signatureDeclarations, indexDeclarations, true);
520 }
521
522 type->AddObjectFlag(ObjectFlags::RESOLVED_DECLARED_MEMBERS);
523
524 ResolveSignaturesOfObjectType(type, signatureDeclarations);
525 ResolveIndexInfosOfObjectType(type, indexDeclarations);
526 }
527 }
528
ValidateInterfaceMemberRedeclaration(ObjectType * type,binder::Variable * prop,const lexer::SourcePosition & locInfo)529 bool Checker::ValidateInterfaceMemberRedeclaration(ObjectType *type, binder::Variable *prop,
530 const lexer::SourcePosition &locInfo)
531 {
532 if (prop->HasFlag(binder::VariableFlags::COMPUTED)) {
533 return true;
534 }
535
536 binder::Variable *found = type->GetProperty(prop->Name(), false);
537
538 if (!found) {
539 return true;
540 }
541
542 Type *targetType = GetTypeOfVariable(prop);
543 Type *sourceType = GetTypeOfVariable(found);
544 IsTypeIdenticalTo(targetType, sourceType,
545 {"Subsequent property declarations must have the same type. Property ", prop->Name(),
546 " must be of type ", sourceType, ", but here has type ", targetType, "."},
547 locInfo);
548 return false;
549 }
550
551 } // namespace panda::es2panda::checker
552