generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSourceFileLinter.ts
1798 lines (1601 loc) · 65.4 KB
/
SourceFileLinter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ts from "typescript";
import path from "node:path/posix";
import {getLogger} from "@ui5/logger";
import SourceFileReporter from "./SourceFileReporter.js";
import {ResourcePath, CoverageCategory, LintMetadata} from "../LinterContext.js";
import {MESSAGE} from "../messages.js";
import analyzeComponentJson from "./asyncComponentFlags.js";
import {deprecatedLibraries, deprecatedThemes} from "../../utils/deprecations.js";
import {
getPropertyNameText,
getSymbolForPropertyInConstructSignatures,
getPropertyAssignmentInObjectLiteralExpression,
getPropertyAssignmentsInObjectLiteralExpression,
findClassMember,
isClassMethod,
} from "./utils/utils.js";
import {taskStart} from "../../utils/perf.js";
import {getPositionsForNode} from "../../utils/nodePosition.js";
import {SourceMapInput, TraceMap, originalPositionFor} from "@jridgewell/trace-mapping";
import type {ApiExtract} from "../../utils/ApiExtract.js";
import {findDirectives} from "./directives.js";
import BindingLinter from "../binding/BindingLinter.js";
import {RequireDeclaration} from "../xmlTemplate/Parser.js";
import {createResource} from "@ui5/fs/resourceFactory";
import {AbstractAdapter} from "@ui5/fs";
import type {AmbientModuleCache} from "./AmbientModuleCache.js";
import type TypeLinter from "./TypeLinter.js";
const log = getLogger("linter:ui5Types:SourceFileLinter");
const QUNIT_FILE_EXTENSION = /\.qunit\.(js|ts)$/;
// This is the same check as in the framework and prevents false-positives
// https://github.com/SAP/openui5/blob/32c21c33d9dc29a32bf7ee7f41d7bae23dcf086b/src/sap.ui.core/src/sap/ui/test/starter/_utils.js#L287
const VALID_TESTSUITE = /\/testsuite(?:\.[a-z][a-z0-9-]*)*\.qunit\.(?:js|ts)$/;
const DEPRECATED_VIEW_TYPES = ["JS", "JSON", "HTML", "Template"];
const ALLOWED_RENDERER_API_VERSIONS = ["2", "4"];
interface DeprecationInfo {
symbol: ts.Symbol;
messageDetails: string;
}
function isSourceFileOfUi5Type(sourceFile: ts.SourceFile) {
return /\/types\/(@openui5|@sapui5|@ui5\/linter\/overrides)\//.test(sourceFile.fileName);
}
function isSourceFileOfUi5OrThirdPartyType(sourceFile: ts.SourceFile) {
return isSourceFileOfUi5Type(sourceFile) || /\/types\/(@types\/jquery)\//.test(sourceFile.fileName);
}
function isSourceFileOfJquerySapType(sourceFile: ts.SourceFile) {
return sourceFile.fileName === "/types/@ui5/linter/overrides/jquery.sap.d.ts";
}
function isSourceFileOfPseudoModuleType(sourceFile: ts.SourceFile) {
return sourceFile.fileName.startsWith("/types/@ui5/linter/overrides/pseudo-modules/");
}
function isSourceFileOfTypeScriptLib(sourceFile: ts.SourceFile) {
return sourceFile.fileName.startsWith("/types/typescript/lib/");
}
export default class SourceFileLinter {
#reporter: SourceFileReporter;
#boundVisitNode: (node: ts.Node) => void;
#fileName: string;
#isComponent: boolean;
#hasTestStarterFindings: boolean;
#metadata: LintMetadata;
#xmlContents: {xml: string; pos: ts.LineAndCharacter; documentKind: "fragment" | "view"}[];
private resourcePath: ResourcePath;
constructor(
private typeLinter: TypeLinter,
private sourceFile: ts.SourceFile,
private checker: ts.TypeChecker,
private reportCoverage = false,
private messageDetails = false,
private apiExtract: ApiExtract,
private filePathsWorkspace: AbstractAdapter,
private workspace: AbstractAdapter,
private ambientModuleCache: AmbientModuleCache,
private manifestContent?: string
) {
this.#reporter = typeLinter.getSourceFileReporter(sourceFile);
this.#boundVisitNode = this.visitNode.bind(this);
this.resourcePath = sourceFile.fileName;
this.#fileName = path.basename(this.resourcePath);
this.#isComponent = this.#fileName === "Component.js" || this.#fileName === "Component.ts";
this.#hasTestStarterFindings = false;
this.#metadata = this.typeLinter.getContext().getMetadata(this.resourcePath);
this.#xmlContents = [];
}
async lint() {
try {
if (!this.#metadata.directives) {
// Directives might have already been extracted by the amd transpiler
// This is done since the transpile process might loose comments
findDirectives(this.sourceFile, this.#metadata);
}
this.visitNode(this.sourceFile);
if (this.sourceFile.fileName.endsWith(".qunit.js") && // TS files do not have sap.ui.define
!this.#metadata?.transformedImports?.get("sap.ui.define")) {
this.#reportTestStarter(this.sourceFile);
}
let i = 0;
for (const xmlContent of this.#xmlContents) {
const fileName = `${this.sourceFile.fileName.replace(/(\.js|\.ts)$/, "")}.inline-${++i}.${xmlContent.documentKind}.xml`;
const metadata = this.typeLinter.getContext().getMetadata(fileName);
const newResource = createResource({path: fileName, string: xmlContent.xml});
metadata.jsToXmlPosMapping = {
pos: xmlContent.pos,
originalPath: this.sourceFile.fileName,
};
await Promise.all([
await this.filePathsWorkspace.write(newResource),
await this.workspace.write(newResource),
]);
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
log.verbose(`Error while linting ${this.resourcePath}: ${message}`);
if (err instanceof Error) {
log.verbose(`Call stack: ${err.stack}`);
}
this.typeLinter.getContext().addLintingMessage(this.resourcePath, MESSAGE.PARSING_ERROR, {message});
}
}
visitNode(node: ts.Node) {
if (node.kind === ts.SyntaxKind.NewExpression) { // e.g. "new Button({\n\t\t\t\tblocked: true\n\t\t\t})"
this.analyzeNewExpression(node as ts.NewExpression);
} else if (node.kind === ts.SyntaxKind.CallExpression) { // ts.isCallLikeExpression too?
// const nodeType = this.checker.getTypeAtLocation(node);
this.analyzePropertyAccessExpression(node as ts.CallExpression); // Check for global
this.analyzeCallExpression(node as ts.CallExpression); // Check for deprecation
} else if (node.kind === ts.SyntaxKind.PropertyAccessExpression ||
node.kind === ts.SyntaxKind.ElementAccessExpression) {
// First, check for deprecation
const deprecationMessageReported = this.analyzePropertyAccessExpressionForDeprecation(
node as (ts.PropertyAccessExpression | ts.ElementAccessExpression));
// If not deprecated, check for global.
// We prefer the deprecation message over the global one as it contains more information.
if (!deprecationMessageReported) {
this.analyzePropertyAccessExpression(
node as (ts.PropertyAccessExpression | ts.ElementAccessExpression)); // Check for global
}
this.analyzeExportedValuesByLib(node as (ts.PropertyAccessExpression | ts.ElementAccessExpression));
} else if (node.kind === ts.SyntaxKind.ObjectBindingPattern &&
node.parent?.kind === ts.SyntaxKind.VariableDeclaration) {
// e.g. `const { Button } = sap.m;`
// This is a destructuring assignment and we need to check each property for deprecation
this.analyzeObjectBindingPattern(node as ts.ObjectBindingPattern);
} else if (node.kind === ts.SyntaxKind.ImportDeclaration) {
this.analyzeImportDeclaration(node as ts.ImportDeclaration); // Check for deprecation
} else if (this.#isComponent && this.isUi5ClassDeclaration(node, "sap/ui/core/Component")) {
analyzeComponentJson({
classDeclaration: node,
manifestContent: this.manifestContent,
resourcePath: this.resourcePath,
reporter: this.#reporter,
context: this.typeLinter.getContext(),
checker: this.checker,
isUiComponent: this.isUi5ClassDeclaration(node, "sap/ui/core/UIComponent"),
});
} else if (
ts.isPropertyDeclaration(node) &&
getPropertyNameText(node.name) === "metadata" &&
node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword) &&
this.isUi5ClassDeclaration(node.parent, "sap/ui/base/ManagedObject")
) {
const visitMetadataNodes = (childNode: ts.Node) => {
if (ts.isPropertyAssignment(childNode)) { // Skip nodes out of interest
this.analyzeMetadataProperty(childNode);
}
ts.forEachChild(childNode, visitMetadataNodes);
};
ts.forEachChild(node, visitMetadataNodes);
} else if (this.isUi5ClassDeclaration(node, "sap/ui/core/Control")) {
this.analyzeControlRendererDeclaration(node);
this.analyzeControlRerenderMethod(node);
} else if (ts.isPropertyAssignment(node) && getPropertyNameText(node.name) === "theme") {
this.analyzeTestsuiteThemeProperty(node);
}
// Traverse the whole AST from top to bottom
ts.forEachChild(node, this.#boundVisitNode);
}
isUi5ClassDeclaration(node: ts.Node, baseClassModule: string | string[]): node is ts.ClassDeclaration {
if (!ts.isClassDeclaration(node)) {
return false;
}
const baseClassModules = Array.isArray(baseClassModule) ? baseClassModule : [baseClassModule];
const baseClasses = baseClassModules.map((baseClassModule) => {
return {module: baseClassModule, name: baseClassModule.split("/").pop()};
});
// Go up the hierarchy chain to find whether the class extends from the provided base class
const isClassUi5Subclass = (node: ts.ClassDeclaration): boolean => {
return node?.heritageClauses?.flatMap((parentClasses: ts.HeritageClause) => {
return parentClasses.types.map((parentClass) => {
const parentClassType = this.checker.getTypeAtLocation(parentClass);
return parentClassType.symbol?.declarations?.some((declaration) => {
if (!ts.isClassDeclaration(declaration)) {
return false;
}
for (const baseClass of baseClasses) {
if (declaration.name?.text === baseClass.name &&
(
// Declaration via type definitions
(
declaration.parent.parent &&
ts.isModuleDeclaration(declaration.parent.parent) &&
declaration.parent.parent.name?.text === baseClass.module
) ||
// Declaration via real class (e.g. within sap.ui.core project)
(
ts.isSourceFile(declaration.parent) &&
(
declaration.parent.fileName === `/resources/${baseClass.module}.js` ||
declaration.parent.fileName === `/resources/${baseClass.module}.ts`
)
)
)
) {
return true;
}
}
return isClassUi5Subclass(declaration);
});
});
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
}).reduce((acc, cur) => cur || acc, false) ?? false;
};
return isClassUi5Subclass(node);
}
analyzeControlRendererDeclaration(node: ts.ClassDeclaration) {
const className = node.name?.text ?? "<unknown>";
const rendererMember = findClassMember(node, "renderer", [{modifier: ts.SyntaxKind.StaticKeyword}]);
if (!rendererMember) {
const nonStaticRender = findClassMember(node, "renderer");
if (nonStaticRender) {
// Renderer must be a static member
this.#reporter.addMessage(MESSAGE.NOT_STATIC_CONTROL_RENDERER, {className}, nonStaticRender);
return;
}
// Special cases: Some base classes do not require sub-classes to have a renderer defined:
if (this.isUi5ClassDeclaration(node, [
"sap/ui/core/mvc/View",
// XMLComposite is deprecated, but there still shouldn't be a false-positive about a missing renderer
"sap/ui/core/XMLComposite",
"sap/ui/core/webc/WebComponent",
"sap/uxap/BlockBase",
])) {
return;
}
// No definition of renderer causes the runtime to load the corresponding Renderer module synchronously
this.#reporter.addMessage(MESSAGE.MISSING_CONTROL_RENDERER_DECLARATION, {className}, node);
return;
}
if (ts.isPropertyDeclaration(rendererMember) && rendererMember.initializer) {
const initializerType = this.checker.getTypeAtLocation(rendererMember.initializer);
if (initializerType.flags & ts.TypeFlags.Undefined ||
initializerType.flags & ts.TypeFlags.Null) {
// null / undefined can be used to declare that a control does not have a renderer
return;
}
if (initializerType.flags & ts.TypeFlags.StringLiteral) {
let rendererName;
if (ts.isStringLiteralLike(rendererMember.initializer)) {
rendererName = rendererMember.initializer.text;
}
// Declaration as string requires sync loading of renderer module
this.#reporter.addMessage(MESSAGE.CONTROL_RENDERER_DECLARATION_STRING, {
className, rendererName,
}, rendererMember.initializer);
}
// Analyze renderer property when it's referenced by a variable or even another module
// i.e. { renderer: Renderer }
if (ts.isIdentifier(rendererMember.initializer)) {
const {symbol} = this.checker.getTypeAtLocation(rendererMember);
const originalDeclarations = symbol?.getDeclarations()?.filter((decl) =>
!decl.getSourceFile().isDeclarationFile);
// If the original raw render file is available, we can analyze it directly
originalDeclarations?.forEach((declaration) => this.analyzeControlRendererInternals(declaration));
} else {
// Analyze renderer property when it's directly embedded in the renderer object
// i.e. { renderer: {apiVersion: 2, render: () => {}} }
this.analyzeControlRendererInternals(rendererMember.initializer);
}
}
}
analyzeControlRendererInternals(node: ts.Node) {
const findApiVersionNode = (potentialApiVersionNode: ts.Node) => {
// const myControlRenderer = {apiVersion: 2, render: () => {}}
if (ts.isObjectLiteralExpression(potentialApiVersionNode)) {
const foundNode = getPropertyAssignmentInObjectLiteralExpression("apiVersion", potentialApiVersionNode);
if (foundNode) {
return foundNode;
}
}
// const myControlRenderer = {}
// const myControlRenderer.apiVersion = 2;
let rendererObjectName = null;
if ((ts.isPropertyAssignment(potentialApiVersionNode.parent) ||
ts.isPropertyDeclaration(potentialApiVersionNode.parent) ||
ts.isVariableDeclaration(potentialApiVersionNode.parent)) &&
ts.isIdentifier(potentialApiVersionNode.parent.name)) {
rendererObjectName = potentialApiVersionNode.parent.name.text;
}
let apiVersionNode: ts.Expression | undefined;
const visitChildNodes = (childNode: ts.Node) => {
if (ts.isBinaryExpression(childNode)) {
if (ts.isPropertyAccessExpression(childNode.left)) {
let objectName;
if (ts.isIdentifier(childNode.left.expression)) {
objectName = childNode.left.expression.text; // myControlRenderer
}
let propertyName;
if (ts.isIdentifier(childNode.left.name)) {
propertyName = childNode.left.name.text; // apiVersion
}
if (objectName === rendererObjectName && propertyName === "apiVersion") {
apiVersionNode = childNode.right;
}
}
}
if (!apiVersionNode) { // If found, stop traversing
ts.forEachChild(childNode, visitChildNodes);
}
};
ts.forEachChild(potentialApiVersionNode.getSourceFile(), visitChildNodes);
return apiVersionNode;
};
const getNodeToHighlight = (apiVersionNode: ts.Node | undefined) => {
if (!apiVersionNode) { // No 'apiVersion' property
return node;
}
if (ts.isPropertyAssignment(apiVersionNode)) {
apiVersionNode = apiVersionNode.initializer;
}
if (!ts.isNumericLiteral(apiVersionNode)) {
return apiVersionNode;
}
if (!ALLOWED_RENDERER_API_VERSIONS.includes(apiVersionNode.text)) {
return apiVersionNode;
}
return undefined;
};
const nodeType = this.checker.getTypeAtLocation(node);
const nodeValueDeclaration = nodeType.getSymbol()?.valueDeclaration;
// Analyze renderer property when it's an ObjectLiteralExpression
// i.e. { renderer: {apiVersion: 2, render: () => {}} }
if (node && (ts.isObjectLiteralExpression(node) || ts.isVariableDeclaration(node))) {
const apiVersionNode = findApiVersionNode(node);
const nodeToHighlight = getNodeToHighlight(apiVersionNode);
if (nodeToHighlight) {
// The findings can be in different file i.e. Control being analyzed,
// but reporting might be in ControlRenderer
const nodeSourceFile = nodeToHighlight.getSourceFile();
this.typeLinter.getSourceFileReporter(nodeSourceFile)
.addMessage(MESSAGE.NO_DEPRECATED_RENDERER, nodeToHighlight);
}
this.analyzeIconCallInRenderMethod(node);
// Analyze renderer property when it's a function i.e. { renderer: () => {} }
} else if (ts.isMethodDeclaration(node) || ts.isArrowFunction(node) ||
ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || (
nodeValueDeclaration && (
ts.isFunctionExpression(nodeValueDeclaration) ||
ts.isFunctionDeclaration(nodeValueDeclaration) ||
ts.isArrowFunction(nodeValueDeclaration)
)
)) {
// The findings can be in different file i.e. Control being analyzed,
// but reporting might be in ControlRenderer
const nodeSourceFile = node.getSourceFile();
this.typeLinter.getSourceFileReporter(nodeSourceFile)
.addMessage(MESSAGE.NO_DEPRECATED_RENDERER, node);
this.analyzeIconCallInRenderMethod(node);
}
}
// If there's an oRm.icon() call in the render method, we need to check if IconPool is imported.
// Currently, we're only able to analyze whether oRm.icon is called in the render method as
// there's no reliable way to find if the method icon() is actually a member of RenderManager in other places.
analyzeIconCallInRenderMethod(node: ts.Node) {
let renderMethodNode: ts.Node | undefined = node;
// When the render is a plain function
if (ts.isMethodDeclaration(node) || ts.isArrowFunction(node) ||
ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node)) {
renderMethodNode = node;
} else if (ts.isObjectLiteralExpression(node)) {
// When the render is embed into the renderer object
const renderProperty = getPropertyAssignmentInObjectLiteralExpression("render", node);
renderMethodNode = (renderProperty && ts.isPropertyAssignment(renderProperty)) ?
renderProperty.initializer :
undefined;
// When the renderer is a separate module and the render method is assigned
// to the renderer object later i.e. myControlRenderer.render = function (oRm, oMyControl) {}
if (!renderMethodNode) {
let rendererObjectName = null;
if ((ts.isPropertyAssignment(node.parent) || ts.isPropertyDeclaration(node.parent) ||
ts.isVariableDeclaration(node.parent)) && ts.isIdentifier(node.parent.name)) {
rendererObjectName = node.parent.name.text;
}
const findRenderMethod = (childNode: ts.Node) => {
if (ts.isBinaryExpression(childNode)) {
if (ts.isPropertyAccessExpression(childNode.left)) {
let objectName;
if (ts.isIdentifier(childNode.left.expression)) {
objectName = childNode.left.expression.text; // myControlRenderer
}
let propertyName;
if (ts.isIdentifier(childNode.left.name)) {
propertyName = childNode.left.name.text; // render
}
if (objectName === rendererObjectName && propertyName === "render") {
renderMethodNode = childNode.right;
}
}
}
if (!renderMethodNode) { // If found, stop traversing
ts.forEachChild(childNode, findRenderMethod);
}
};
ts.forEachChild(node.getSourceFile(), findRenderMethod);
}
}
if (!renderMethodNode) {
return;
}
// If there's a dependency to IconPool from the Renderer,
// it's fine and we can skip the rest of the checks
const rendererSource = renderMethodNode.getSourceFile();
const hasIconPoolImport = rendererSource.statements.some((importNode: ts.Statement) => {
return ts.isImportDeclaration(importNode) &&
ts.isStringLiteralLike(importNode.moduleSpecifier) &&
importNode.moduleSpecifier.text === "sap/ui/core/IconPool";
});
if (hasIconPoolImport) {
return;
}
const findIconCallExpression = (childNode: ts.Node) => {
if (ts.isCallExpression(childNode) &&
ts.isPropertyAccessExpression(childNode.expression) &&
childNode.expression.name.text === "icon"
) {
// The findings can be in different file i.e. Control being analyzed,
// but reporting might be in ControlRenderer, so we have to use the corresponding reporter
const nodeSourceFile = childNode.getSourceFile();
this.typeLinter.getSourceFileReporter(nodeSourceFile)
.addMessage(MESSAGE.NO_ICON_POOL_RENDERER, childNode);
}
ts.forEachChild(childNode, findIconCallExpression);
};
// When the renderer is a separate module we can say with some certainty that the .icon() call
// is a RenderManager's
if (rendererSource.fileName !== this.sourceFile.fileName) {
ts.forEachChild(rendererSource, findIconCallExpression);
} else {
// When the renderer is embedded in the control file, then we can analyze only the icon call
// within the render method.
ts.forEachChild(renderMethodNode, findIconCallExpression);
}
}
analyzeControlRerenderMethod(node: ts.ClassDeclaration) {
const className = node.name?.text ?? "<unknown>";
// Search for the rerender instance method
const rerenderMember = findClassMember(node, "rerender", [{not: true, modifier: ts.SyntaxKind.StaticKeyword}]);
if (!rerenderMember || !isClassMethod(rerenderMember, this.checker)) {
return;
}
this.#reporter.addMessage(MESSAGE.NO_CONTROL_RERENDER_OVERRIDE, {className}, rerenderMember);
}
analyzeMetadataProperty(node: ts.PropertyAssignment) {
const type = getPropertyNameText(node.name);
if (!type) {
return;
}
const analyzeMetadataDone = taskStart(`analyzeMetadataProperty: ${type}`, this.resourcePath, true);
if (type === "interfaces") {
if (ts.isArrayLiteralExpression(node.initializer)) {
node.initializer.elements.forEach((elem) => {
const interfaceName = (elem as ts.StringLiteral).text;
const deprecationInfo = this.apiExtract.getDeprecationInfo(interfaceName);
if (deprecationInfo) {
this.#reporter.addMessage(MESSAGE.DEPRECATED_INTERFACE, {
interfaceName: interfaceName,
details: deprecationInfo.text,
}, elem);
}
});
}
} else if (type === "altTypes" && ts.isArrayLiteralExpression(node.initializer)) {
node.initializer.elements.forEach((element) => {
const nodeType = ts.isStringLiteralLike(element) ? element.text : "";
const deprecationInfo = this.apiExtract.getDeprecationInfo(nodeType);
if (deprecationInfo) {
this.#reporter.addMessage(MESSAGE.DEPRECATED_TYPE, {
typeName: nodeType,
details: deprecationInfo.text,
}, element);
}
});
} else if (type === "defaultValue") {
const defaultValueType = ts.isStringLiteralLike(node.initializer) ?
node.initializer.text :
"";
const typeNode = getPropertyAssignmentInObjectLiteralExpression("type", node.parent);
const fullyQuantifiedName = (typeNode &&
ts.isPropertyAssignment(typeNode) &&
ts.isStringLiteralLike(typeNode.initializer)) ?
[typeNode.initializer.text, defaultValueType].join(".") :
"";
const deprecationInfo = this.apiExtract.getDeprecationInfo(fullyQuantifiedName);
if (deprecationInfo) {
this.#reporter.addMessage(MESSAGE.DEPRECATED_TYPE, {
typeName: defaultValueType,
details: deprecationInfo.text,
}, node);
}
// This one is too generic and should always be at the last place
// It's for "types" and event arguments' types
} else if (ts.isStringLiteralLike(node.initializer)) {
// Strip all the complex type definitions and create a list of "simple" types
// i.e. Record<string, Map<my.custom.type, Record<another.type, number[]>>>
// -> string, my.custom.type, another.type, number
const nodeTypes = node.initializer.text.replace(/\w+<|>|\[\]/gi, "")
.split(",").map((type) => type.trim());
nodeTypes.forEach((nodeType) => {
const deprecationInfo = this.apiExtract.getDeprecationInfo(nodeType);
if (deprecationInfo?.symbolKind === "UI5Class") {
this.#reporter.addMessage(MESSAGE.DEPRECATED_CLASS, {
className: nodeType,
details: deprecationInfo.text,
}, node.initializer);
} else if (deprecationInfo?.symbolKind === "UI5Typedef" || deprecationInfo?.symbolKind === "UI5Enum") {
this.#reporter.addMessage(MESSAGE.DEPRECATED_TYPE, {
typeName: nodeType,
details: deprecationInfo.text,
}, node.initializer);
}
});
}
analyzeMetadataDone();
}
analyzeIdentifier(node: ts.Identifier) {
const type = this.checker.getTypeAtLocation(node);
if (!type?.symbol || !this.isSymbolOfUi5OrThirdPartyType(type.symbol)) {
return false;
}
const deprecationInfo = this.getDeprecationInfo(type.symbol);
if (deprecationInfo) {
this.#reporter.addMessage(MESSAGE.DEPRECATED_API_ACCESS, {
apiName: node.text,
details: deprecationInfo.messageDetails,
}, node);
return true;
}
return false;
}
analyzeObjectBindingPattern(node: ts.ObjectBindingPattern) {
const objectBindingPatternType = this.checker.getTypeAtLocation(node);
node.elements.forEach((element) => {
if (element.kind === ts.SyntaxKind.BindingElement &&
element.name.kind === ts.SyntaxKind.Identifier) {
let identifier;
if (element.propertyName) {
if (!ts.isIdentifier(element.propertyName)) {
return;
}
identifier = element.propertyName;
} else {
identifier = element.name;
}
if (this.analyzeIdentifier(identifier)) {
return;
}
const property = objectBindingPatternType.getProperty(identifier.text);
const deprecationInfo = this.getDeprecationInfo(property);
if (deprecationInfo) {
this.#reporter.addMessage(MESSAGE.DEPRECATED_API_ACCESS, {
apiName: identifier.text,
details: deprecationInfo.messageDetails,
}, element.name);
return;
}
}
// Currently this lacks support for handling nested destructuring, e.g.
// `const { SomeObject: { SomeOtherObject } } = coreLib;`
// Also not covered is destructuring with computed property names, e.g.
// const propName = "SomeObject"
// const {[propName]: SomeVar} = coreLib;
// Neither is expected to be relevant in the context of UI5 API usage.
});
}
analyzeNewExpression(node: ts.NewExpression) {
if (this.hasQUnitFileExtension() &&
((ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "jsUnitTestSuite") ||
(ts.isIdentifier(node.expression) && node.expression.text === "jsUnitTestSuite")
)) {
this.#reportTestStarter(node);
}
const nodeType = this.checker.getTypeAtLocation(node); // checker.getContextualType(node);
if (!nodeType.symbol || !this.isSymbolOfUi5OrThirdPartyType(nodeType.symbol)) {
return;
}
const classType = this.checker.getTypeAtLocation(node.expression);
const moduleDeclaration = this.getSymbolModuleDeclaration(nodeType.symbol);
if (moduleDeclaration?.name.text === "sap/ui/core/routing/Router") {
this.#analyzeNewCoreRouter(node);
} else if (moduleDeclaration?.name.text === "sap/ui/model/odata/v4/ODataModel") {
this.#analyzeNewOdataModelV4(node);
} else if (nodeType.symbol.declarations?.some(
(declaration) => this.isUi5ClassDeclaration(declaration, "sap/ui/base/ManagedObject"))) {
const originalFilename = this.#metadata?.xmlCompiledResource;
// Do not process xml-s. This case would be handled separately within the BindingParser
if (!originalFilename ||
![".view.xml", ".fragment.xml"].some((ending) => originalFilename.endsWith(ending))) {
this.#analyzeNewAndApplySettings(node);
}
}
if (!node.arguments?.length) {
// Nothing to check
return;
}
// There can be multiple and we need to find the right one
const allConstructSignatures = classType.getConstructSignatures();
// We can ignore all signatures that have a different number of parameters
const possibleConstructSignatures = allConstructSignatures.filter((constructSignature) => {
return constructSignature.getParameters().length === node.arguments?.length;
});
node.arguments.forEach((arg, argIdx) => {
// Only handle object literals, ignoring the optional first id argument or other unrelated arguments
if (!ts.isObjectLiteralExpression(arg)) {
return;
}
arg.properties.forEach((prop) => {
if (!ts.isPropertyAssignment(prop)) {
return;
}
const propertyName = getPropertyNameText(prop.name);
if (!propertyName) {
return;
}
const propertySymbol = getSymbolForPropertyInConstructSignatures(
possibleConstructSignatures, argIdx, propertyName
);
if (!propertySymbol) {
return;
}
const deprecationInfo = this.getDeprecationInfo(propertySymbol);
if (!deprecationInfo) {
return;
}
this.#reporter.addMessage(MESSAGE.DEPRECATED_PROPERTY_OF_CLASS,
{
propertyName: propertySymbol.escapedName as string,
className: this.checker.typeToString(nodeType),
details: deprecationInfo.messageDetails,
},
prop
);
});
});
}
extractNamespace(node: ts.PropertyAccessExpression | ts.ElementAccessExpression | ts.CallExpression): string {
const propAccessChain: string[] = [];
propAccessChain.push(node.expression.getText());
let scanNode: ts.Node = node;
while (ts.isPropertyAccessExpression(scanNode)) {
if (!ts.isIdentifier(scanNode.name)) {
throw new Error(
`Unexpected PropertyAccessExpression node: Expected name to be identifier but got ` +
ts.SyntaxKind[scanNode.name.kind]);
}
propAccessChain.push(scanNode.name.text);
scanNode = scanNode.parent;
}
return propAccessChain.join(".");
}
/**
* Extracts the sap.ui API namespace from a symbol name and a module declaration
* (from @sapui5/types sap.ui.core.d.ts), e.g. sap.ui.view.
*/
extractSapUiNamespace(symbolName: string, moduleDeclaration: ts.ModuleDeclaration): string | undefined {
const namespace: string[] = [];
let currentModuleDeclaration: ts.Node | undefined = moduleDeclaration;
while (
currentModuleDeclaration &&
ts.isModuleDeclaration(currentModuleDeclaration) &&
currentModuleDeclaration.flags & ts.NodeFlags.Namespace
) {
namespace.unshift(currentModuleDeclaration.name.text);
currentModuleDeclaration = currentModuleDeclaration.parent?.parent;
}
if (!namespace.length) {
return undefined;
} else {
namespace.push(symbolName);
return namespace.join(".");
}
}
getDeprecationText(deprecatedTag: ts.JSDocTagInfo): string {
// (Workaround) There's an issue in some UI5 TS definition versions and where the
// deprecation text gets merged with the description. Splitting on double
// new line could be considered as a clear separation between them.
// https://github.com/SAP/ui5-typescript/issues/429
return deprecatedTag.text?.reduce((acc, text) => acc + text.text, "").split("\n\n")[0] ?? "";
}
getDeprecationInfo(symbol: ts.Symbol | undefined): DeprecationInfo | null {
if (symbol && this.isSymbolOfUi5Type(symbol)) {
const jsdocTags = symbol.getJsDocTags(this.checker);
const deprecatedTag = jsdocTags.find((tag) => tag.name === "deprecated");
if (deprecatedTag) {
const deprecationInfo: DeprecationInfo = {
symbol, messageDetails: "",
};
if (this.messageDetails) {
deprecationInfo.messageDetails = this.getDeprecationText(deprecatedTag);
}
return deprecationInfo;
}
}
return null;
}
analyzeCallExpression(node: ts.CallExpression) {
const exprNode = node.expression;
const exprType = this.checker.getTypeAtLocation(exprNode);
if (!exprType?.symbol || !this.isSymbolOfUi5OrThirdPartyType(exprType.symbol)) {
if (this.reportCoverage) {
this.handleCallExpressionUnknownType(exprType, node);
}
return;
}
if (ts.isNewExpression(exprNode)) {
// e.g. new Class()();
// This is usually unexpected and there are currently no known deprecations of functions
// returned by a class constructor.
// However, the OPA Matchers are a known exception where constructors do return a function.
return;
} else if (exprNode.kind === ts.SyntaxKind.SuperKeyword) {
// Ignore super calls
return;
}
if (!ts.isPropertyAccessExpression(exprNode) && // Lib.init()
!ts.isElementAccessExpression(exprNode) && // Lib["init"]()
!ts.isIdentifier(exprNode) && // Assignment `const LibInit = Library.init` and destructuring
!ts.isCallExpression(exprNode)) {
// TODO: Transform into coverage message if it's really ok not to handle this
throw new Error(`Unhandled CallExpression expression syntax: ${ts.SyntaxKind[exprNode.kind]}`);
}
const moduleDeclaration = this.getSymbolModuleDeclaration(exprType.symbol);
let globalApiName;
if (exprType.symbol && moduleDeclaration) {
const symbolName = exprType.symbol.getName();
const moduleName = moduleDeclaration.name.text;
const nodeType = this.checker.getTypeAtLocation(node);
globalApiName = this.extractSapUiNamespace(symbolName, moduleDeclaration);
if (symbolName === "init" && moduleName === "sap/ui/core/Lib") {
// Check for sap/ui/core/Lib.init usages
this.#analyzeLibInitCall(node, exprNode);
} else if (symbolName === "get" && moduleName === "sap/ui/core/theming/Parameters") {
this.#analyzeParametersGetCall(node);
} else if (symbolName === "createComponent" && moduleName === "sap/ui/core/Component") {
this.#analyzeCreateComponentCall(node);
} else if (symbolName === "loadData" && moduleName === "sap/ui/model/json/JSONModel") {
this.#analyzeJsonModelLoadDataCall(node);
} else if (symbolName === "createEntry" && moduleName === "sap/ui/model/odata/v2/ODataModel") {
this.#analyzeOdataModelV2CreateEntry(node);
} else if (symbolName === "init" && moduleName === "sap/ui/util/Mobile") {
this.#analyzeMobileInit(node);
} else if (symbolName === "setTheme" && moduleName === "sap/ui/core/Theming") {
this.#analyzeThemingSetTheme(node);
} else if (symbolName === "create" && moduleName === "sap/ui/core/mvc/View") {
this.#analyzeViewCreate(node);
} else if (
(symbolName === "load" && moduleName === "sap/ui/core/Fragment") ||
// Controller#loadFragment calls Fragment.load internally
(symbolName === "loadFragment" && moduleName === "sap/ui/core/mvc/Controller")
) {
this.#analyzeFragmentLoad(node, symbolName);
} else if (this.hasQUnitFileExtension() &&
!VALID_TESTSUITE.test(this.sourceFile.fileName) &&
symbolName === "ready" && moduleName === "sap/ui/core/Core") {
this.#reportTestStarter(node);
} else if (symbolName === "applySettings" &&
nodeType.symbol?.declarations?.some((declaration) =>
this.isUi5ClassDeclaration(declaration, "sap/ui/base/ManagedObject"))) {
this.#analyzeNewAndApplySettings(node);
} else if (["bindProperty", "bindAggregation"].includes(symbolName) &&
moduleName === "sap/ui/base/ManagedObject" &&
node.arguments[1] && ts.isObjectLiteralExpression(node.arguments[1])) {
this.#analyzePropertyBindings(node.arguments[1], ["type", "formatter"]);
} else if (symbolName.startsWith("bind") &&
nodeType.symbol?.declarations?.some((declaration) =>
this.isUi5ClassDeclaration(declaration, "sap/ui/base/ManagedObject")) &&
node.arguments[0] && ts.isObjectLiteralExpression(node.arguments[0])) {
// Setting names in UI5 are case sensitive. So, we're not sure of the exact name of the property.
// Check decapitalized version of the property name as well.
const propName = symbolName.replace("bind", "");
const alternativePropName = propName.charAt(0).toLowerCase() + propName.slice(1);
if (this.#isPropertyBinding(node, [propName, alternativePropName])) {
this.#analyzePropertyBindings(node.arguments[0], ["type", "formatter"]);
}
} else if (
globalApiName === "sap.ui.view" ||
globalApiName === "sap.ui.xmlview" ||
globalApiName === "sap.ui.fragment" ||
globalApiName === "sap.ui.xmlfragment"
) {
this.#extractXmlFromJs(node, globalApiName);
} else if (symbolName === "create" && moduleName === "sap/ui/core/mvc/XMLView") {
this.#extractXmlFromJs(node, "XMLView.create");
}
}
const deprecationInfo = this.getDeprecationInfo(exprType.symbol);
if (!deprecationInfo) {
return;
}
let reportNode;
if (ts.isPropertyAccessExpression(exprNode)) {
reportNode = exprNode.name;
} else if (ts.isElementAccessExpression(exprNode)) {
reportNode = exprNode.argumentExpression;
} else { // Identifier / CallExpression
reportNode = exprNode;
}
let additionalMessage = "";
if (exprNode.kind === ts.SyntaxKind.PropertyAccessExpression ||
exprNode.kind === ts.SyntaxKind.ElementAccessExpression) {
// Get the type to the left of the call expression (i.e. what the function is being called on)
const lhsExpr = exprNode.expression;
const lhsExprType = this.checker.getTypeAtLocation(lhsExpr);
if (lhsExprType.isClassOrInterface()) {
// left-hand-side is an instance of a class, e.g. "instance.deprecatedMethod()"
additionalMessage = `of class '${this.checker.typeToString(lhsExprType)}'`;
} else if (ts.isCallExpression(lhsExpr)) {
// left-hand-side is a function call, e.g. "function().deprecatedMethod()"
// Use the (return) type of that function call
additionalMessage = `of module '${this.checker.typeToString(lhsExprType)}'`;
} else if (ts.isPropertyAccessExpression(exprNode)) {
// left-hand-side is a module or namespace, e.g. "module.deprecatedMethod()"
additionalMessage = `(${this.extractNamespace(exprNode)})`;
}
} else if (globalApiName) {
additionalMessage = `(${globalApiName})`;
}
let propName;
if (ts.isPropertyName(reportNode)) {
propName = getPropertyNameText(reportNode);
}
if (!propName) {
propName = reportNode.getText();
}
this.#reporter.addMessage(MESSAGE.DEPRECATED_FUNCTION_CALL, {
functionName: propName,
additionalMessage,
details: deprecationInfo.messageDetails,
}, reportNode);
if (
propName === "attachInit" && this.hasQUnitFileExtension() &&
!VALID_TESTSUITE.test(this.sourceFile.fileName)
) {
this.#reportTestStarter(reportNode);
}
}
getSymbolModuleDeclaration(symbol: ts.Symbol) {
let parent = symbol.valueDeclaration?.parent;
while (parent && !ts.isModuleDeclaration(parent)) {
parent = parent.parent;
}
return parent;
}
#analyzeLibInitCall(
node: ts.CallExpression,
exprNode: ts.CallExpression | ts.ElementAccessExpression | ts.PropertyAccessExpression | ts.Identifier) {
const initArg = node?.arguments[0] &&
ts.isObjectLiteralExpression(node.arguments[0]) &&
node.arguments[0];
let nodeToHighlight;
if (!initArg) {
nodeToHighlight = node;
} else {
const apiVersionNode = getPropertyAssignmentInObjectLiteralExpression("apiVersion", initArg);
if (!apiVersionNode) { // No arguments or no 'apiVersion' property
nodeToHighlight = node;
} else if (
!ts.isNumericLiteral(apiVersionNode.initializer) || // Must be a number, not a string
apiVersionNode.initializer.text !== "2"
) {
nodeToHighlight = apiVersionNode;
}
}
if (nodeToHighlight) {
let importedVarName: string;
if (ts.isIdentifier(exprNode)) {
importedVarName = exprNode.text;
} else {
importedVarName = exprNode.expression.getText() + ".init";
}
this.#reporter.addMessage(MESSAGE.LIB_INIT_API_VERSION, {
libInitFunction: importedVarName,
}, nodeToHighlight);
}
if (initArg) {
this.#analyzeLibInitDeprecatedLibs(initArg);
}
}
#analyzeLibInitDeprecatedLibs(initArg: ts.ObjectLiteralExpression) {
const dependenciesNode = getPropertyAssignmentInObjectLiteralExpression(
"dependencies", initArg