@abaplint/core 2.120.80 → 2.120.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1204 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SourceKind = exports.PredicateKind = exports.Procedure = exports.ObjectAnalysis = exports.Variable = exports.OccurrenceKind = void 0;
37
+ exports.findStructures = findStructures;
38
+ exports.expressionPath = expressionPath;
39
+ exports.plainMove = plainMove;
40
+ exports.singleField = singleField;
41
+ exports.singleTarget = singleTarget;
42
+ exports.plainClear = plainClear;
43
+ exports.plainData = plainData;
44
+ exports.isImmutable = isImmutable;
45
+ exports.isReferenceType = isReferenceType;
46
+ exports.identicalTypes = identicalTypes;
47
+ exports.simplePredicate = simplePredicate;
48
+ exports.characterConstant = characterConstant;
49
+ exports.sameCharacters = sameCharacters;
50
+ exports.isCondition = isCondition;
51
+ exports.dataSource = dataSource;
52
+ exports.targetType = targetType;
53
+ exports.unchangedBetween = unchangedBetween;
54
+ exports.mergeEdits = mergeEdits;
55
+ exports.deleteRegion = deleteRegion;
56
+ exports.deleteStatement = deleteStatement;
57
+ exports.rawText = rawText;
58
+ exports.nodeText = nodeText;
59
+ exports.ifBranches = ifBranches;
60
+ exports.selfContained = selfContained;
61
+ exports.foldIf = foldIf;
62
+ exports.foldIssues = foldIssues;
63
+ const Expressions = __importStar(require("../abap/2_statements/expressions"));
64
+ const Statements = __importStar(require("../abap/2_statements/statements"));
65
+ const Structures = __importStar(require("../abap/3_structures/structures"));
66
+ const _statement_1 = require("../abap/2_statements/statements/_statement");
67
+ const tokens_1 = require("../abap/1_lexer/tokens");
68
+ const _reference_1 = require("../abap/5_syntax/_reference");
69
+ const syntax_1 = require("../abap/5_syntax/syntax");
70
+ const nodes_1 = require("../abap/nodes");
71
+ const _typed_identifier_1 = require("../abap/types/_typed_identifier");
72
+ const basic_1 = require("../abap/types/basic");
73
+ const _abap_object_1 = require("../objects/_abap_object");
74
+ const edit_helper_1 = require("../edit_helper");
75
+ const position_1 = require("../position");
76
+ const issue_1 = require("../issue");
77
+ // Shared analysis for the rules that remove redundant code around local variables:
78
+ // clear_after_declaration, unnecessary_copy, constant_condition, copy_chain, copy_of_initial_variable,
79
+ // bound_check_after_create, boolean_flag_via_if, alias_never_reassigned, single_use_expression_temp
80
+ // and try_cast_empty_catch.
81
+ //
82
+ // Everything is derived from the syntax tree and the resolved references of the syntax check,
83
+ // statements are never matched as text.
84
+ var OccurrenceKind;
85
+ (function (OccurrenceKind) {
86
+ /** the value is read, or only used to reach a referenced object (ref->attr, ref->*) */
87
+ OccurrenceKind["Read"] = "read";
88
+ /** the variable itself is changed */
89
+ OccurrenceKind["Write"] = "write";
90
+ /** address taken, field symbol binding, USING/TABLES, dynamic, type reference, or a statement
91
+ * that is not known to only read its operands */
92
+ OccurrenceKind["Escape"] = "escape";
93
+ })(OccurrenceKind || (exports.OccurrenceKind = OccurrenceKind = {}));
94
+ class Variable {
95
+ constructor(identifier, declaration, inline, occurrences, complete) {
96
+ this.identifier = identifier;
97
+ this.declaration = declaration;
98
+ this.inline = inline;
99
+ this.occurrences = occurrences;
100
+ this.complete = complete;
101
+ }
102
+ /** declared by DATA, or inline, in the procedure; not a parameter, attribute or STATICS */
103
+ isLocal() {
104
+ return this.declaration !== undefined;
105
+ }
106
+ reads() {
107
+ return this.occurrences.filter(o => o.kind === OccurrenceKind.Read);
108
+ }
109
+ writes() {
110
+ return this.occurrences.filter(o => o.kind === OccurrenceKind.Write);
111
+ }
112
+ escapes() {
113
+ return this.occurrences.some(o => o.kind === OccurrenceKind.Escape);
114
+ }
115
+ }
116
+ exports.Variable = Variable;
117
+ /** References of one object, after a successful syntax check */
118
+ class ObjectAnalysis {
119
+ /** returns undefined if the object is not supported, or has syntax errors */
120
+ static run(reg, obj) {
121
+ var _a;
122
+ if (!(obj instanceof _abap_object_1.ABAPObject)) {
123
+ return undefined;
124
+ }
125
+ const syntax = new syntax_1.SyntaxLogic(reg, obj).run();
126
+ // the rules run one after the other on the same object, the syntax result changes when the object changes
127
+ if (((_a = ObjectAnalysis.last) === null || _a === void 0 ? void 0 : _a.obj) === obj && ObjectAnalysis.last.syntax === syntax) {
128
+ return ObjectAnalysis.last.analysis;
129
+ }
130
+ const analysis = ObjectAnalysis.build(obj, syntax);
131
+ ObjectAnalysis.last = { obj, syntax, analysis };
132
+ return analysis;
133
+ }
134
+ static build(obj, syntax) {
135
+ // Neither macro expansion nor unknown statements have reliable references.
136
+ for (const file of obj.getABAPFiles()) {
137
+ for (const statement of file.getStatements()) {
138
+ const type = statement.get();
139
+ if (type instanceof _statement_1.Unknown || type instanceof Statements.Define
140
+ || type instanceof _statement_1.MacroCall || type instanceof _statement_1.MacroContent || type instanceof _statement_1.MacroRecursion) {
141
+ return undefined;
142
+ }
143
+ }
144
+ }
145
+ if (syntax.issues.length > 0) {
146
+ return undefined;
147
+ }
148
+ return new ObjectAnalysis(obj, syntax.spaghetti);
149
+ }
150
+ constructor(obj, spaghetti) {
151
+ this.procedures = [];
152
+ this.byResolved = new Map();
153
+ this.byPosition = new Map();
154
+ this.obj = obj;
155
+ this.spaghetti = spaghetti;
156
+ const stack = [spaghetti.getTop()];
157
+ while (stack.length > 0) {
158
+ const node = stack.pop();
159
+ for (const reference of node.getData().references) {
160
+ const position = ObjectAnalysis.key(reference.position);
161
+ const atPosition = this.byPosition.get(position) || [];
162
+ atPosition.push(reference);
163
+ this.byPosition.set(position, atPosition);
164
+ if (reference.resolved !== undefined) {
165
+ const resolved = ObjectAnalysis.key(reference.resolved);
166
+ const list = this.byResolved.get(resolved) || [];
167
+ list.push(reference);
168
+ this.byResolved.set(resolved, list);
169
+ }
170
+ }
171
+ stack.push(...node.getChildren());
172
+ }
173
+ for (const file of obj.getABAPFiles()) {
174
+ const structure = file.getStructure();
175
+ if (structure === undefined) {
176
+ continue;
177
+ }
178
+ for (const procedure of findStructures(structure, [Structures.Method, Structures.Form, Structures.FunctionModule])) {
179
+ this.procedures.push(new Procedure(this, file, procedure));
180
+ }
181
+ }
182
+ }
183
+ static key(identifier) {
184
+ const start = identifier.getStart();
185
+ return identifier.getFilename() + "," + start.getRow() + "," + start.getCol();
186
+ }
187
+ static tokenKey(filename, token) {
188
+ return filename + "," + token.getRow() + "," + token.getCol();
189
+ }
190
+ referencesTo(identifier) {
191
+ return this.byResolved.get(ObjectAnalysis.key(identifier)) || [];
192
+ }
193
+ referencesAt(filename, token) {
194
+ return this.byPosition.get(ObjectAnalysis.tokenKey(filename, token)) || [];
195
+ }
196
+ /** all resolved identifiers, with the positions of their references */
197
+ allReferences() {
198
+ return this.byResolved.entries();
199
+ }
200
+ }
201
+ exports.ObjectAnalysis = ObjectAnalysis;
202
+ const LOOPS = [Structures.Loop, Structures.Do, Structures.While, Structures.Select,
203
+ Structures.Provide, Structures.LoopAtScreen, Structures.LoopExtract, Structures.With];
204
+ /** Statements whose data read references are known to only read the value */
205
+ const READING = [Statements.Move, Statements.Call, Statements.If, Statements.ElseIf,
206
+ Statements.Case, Statements.When, Statements.While, Statements.Check, Statements.Assert, Statements.Append,
207
+ Statements.InsertInternal, Statements.ModifyInternal, Statements.DeleteInternal, Statements.ReadTable,
208
+ Statements.Loop, Statements.CreateObject, Statements.Raise, Statements.Message, Statements.Concatenate,
209
+ Statements.Split, Statements.Condense, Statements.Translate, Statements.Replace, Statements.Find,
210
+ Statements.Select, Statements.SelectLoop, Statements.Do, Statements.Write, Statements.Collect,
211
+ Statements.Describe, Statements.Shift, Statements.Return, Statements.Clear, Statements.Sort,
212
+ Statements.InsertDatabase, Statements.ModifyDatabase, Statements.UpdateDatabase, Statements.DeleteDatabase];
213
+ /** Statements which cannot run other ABAP code, unless they contain a method call or NEW */
214
+ const CALL_FREE = [Statements.Move, Statements.Data, Statements.Clear, Statements.Free,
215
+ Statements.Append, Statements.InsertInternal, Statements.ModifyInternal, Statements.DeleteInternal,
216
+ Statements.ReadTable, Statements.Sort, Statements.Concatenate, Statements.Condense, Statements.Split,
217
+ Statements.Translate, Statements.Replace, Statements.Find, Statements.Shift, Statements.Collect,
218
+ Statements.Describe, Statements.FieldSymbol, Statements.Constant, Statements.Type, Statements.Unassign,
219
+ Statements.If, Statements.ElseIf, Statements.Else, Statements.EndIf, Statements.Case, Statements.When,
220
+ Statements.WhenOthers, Statements.EndCase, Statements.Do, Statements.EndDo, Statements.While, Statements.EndWhile,
221
+ Statements.Loop, Statements.EndLoop, Statements.Check, Statements.Exit, Statements.Continue, Statements.Return,
222
+ Statements.Try, Statements.Catch, Statements.Cleanup, Statements.EndTry];
223
+ /** A METHOD, FORM or FUNCTION implementation */
224
+ class Procedure {
225
+ constructor(analysis, file, structure) {
226
+ var _a, _b, _c;
227
+ /** all statements, including METHOD and ENDMETHOD */
228
+ this.statements = [];
229
+ this.info = new Map();
230
+ this.parents = new Map();
231
+ /** identifier tokens by lower case name, positions as row * 100000 + column, the procedure is in one file */
232
+ this.names = new Map();
233
+ this.declarations = new Map();
234
+ this.declarationTokens = [];
235
+ this.tokens = new Map();
236
+ this.variables = new Map();
237
+ this.own = undefined;
238
+ this.comments = undefined;
239
+ this.analysis = analysis;
240
+ this.file = file;
241
+ this.structure = structure;
242
+ this.walk(structure, [], undefined, false);
243
+ this.supported = this.isSupported();
244
+ if (this.supported === false) {
245
+ return;
246
+ }
247
+ for (const statement of this.statements) {
248
+ const tokens = this.tokensOf(statement);
249
+ for (let i = 0; i < tokens.length; i++) {
250
+ const token = tokens[i];
251
+ const previous = tokens[i - 1];
252
+ if (!(token instanceof tokens_1.Identifier)
253
+ || (previous !== undefined && (previous.getStr() === "->" || previous.getStr() === "=>"
254
+ || previous.getStr() === "~" || previous instanceof tokens_1.Dash))) {
255
+ continue;
256
+ }
257
+ const name = token.getStr().toLowerCase();
258
+ const list = this.names.get(name);
259
+ if (list === undefined) {
260
+ this.names.set(name, [position(token)]);
261
+ }
262
+ else {
263
+ list.push(position(token));
264
+ }
265
+ }
266
+ const type = statement.get();
267
+ if (type instanceof Statements.Data && this.isSimple(statement)) {
268
+ const name = (_b = (_a = statement.findDirectExpression(Expressions.DataDefinition)) === null || _a === void 0 ? void 0 : _a.findDirectExpression(Expressions.DefinitionName)) === null || _b === void 0 ? void 0 : _b.getFirstToken();
269
+ if (name !== undefined) {
270
+ this.declarations.set(this.tokenKey(name), statement);
271
+ this.declarationTokens.push(name);
272
+ }
273
+ }
274
+ if (!(type instanceof Statements.Form) && tokens.some((t, i) => { var _a; return t.getStr().toUpperCase() === "DATA"
275
+ && ((_a = tokens[i + 1]) === null || _a === void 0 ? void 0 : _a.getStr()) === "("; })) {
276
+ for (const inline of statement.findAllExpressionsRecursive(Expressions.InlineData)) {
277
+ const name = (_c = inline.findDirectExpression(Expressions.TargetField)) === null || _c === void 0 ? void 0 : _c.getFirstToken();
278
+ if (name !== undefined) {
279
+ this.declarations.set(this.tokenKey(name), statement);
280
+ this.declarationTokens.push(name);
281
+ }
282
+ }
283
+ }
284
+ }
285
+ }
286
+ getStart() {
287
+ return this.structure.getFirstToken().getStart();
288
+ }
289
+ getEnd() {
290
+ return this.structure.getLastToken().getEnd();
291
+ }
292
+ contains(identifier) {
293
+ return identifier.getFilename() === this.file.getFilename()
294
+ && !identifier.getStart().isBefore(this.getStart())
295
+ && !identifier.getStart().isAfter(this.getEnd());
296
+ }
297
+ tokenKey(token) {
298
+ return ObjectAnalysis.tokenKey(this.file.getFilename(), token);
299
+ }
300
+ index(statement) {
301
+ var _a;
302
+ var _b;
303
+ return (_b = (_a = this.info.get(statement)) === null || _a === void 0 ? void 0 : _a.index) !== null && _b !== void 0 ? _b : -1;
304
+ }
305
+ block(statement) {
306
+ var _a;
307
+ return (_a = this.info.get(statement)) === null || _a === void 0 ? void 0 : _a.block;
308
+ }
309
+ loop(statement) {
310
+ var _a;
311
+ return (_a = this.info.get(statement)) === null || _a === void 0 ? void 0 : _a.loop;
312
+ }
313
+ /** a direct statement of its block, not the start, middle or end of a nested structure */
314
+ isSimple(statement) {
315
+ var _a;
316
+ return ((_a = this.info.get(statement)) === null || _a === void 0 ? void 0 : _a.simple) === true;
317
+ }
318
+ /** first executes before second, on every path that reaches second within one iteration:
319
+ * the block of first contains second, and first is before second */
320
+ dominates(first, second) {
321
+ const a = this.info.get(first);
322
+ const b = this.info.get(second);
323
+ return a !== undefined && b !== undefined && a.block !== undefined
324
+ && a.index < b.index && b.blockPath.includes(a.block);
325
+ }
326
+ sameLoop(first, second) {
327
+ return this.loop(first) === this.loop(second);
328
+ }
329
+ /** statements strictly between two statements of the same block,
330
+ * undefined if any of them is not a direct statement of that block */
331
+ straightBetween(first, second) {
332
+ const a = this.info.get(first);
333
+ const b = this.info.get(second);
334
+ if (a === undefined || b === undefined || a.block === undefined || a.block !== b.block || a.index >= b.index) {
335
+ return undefined;
336
+ }
337
+ const between = this.statements.slice(a.index + 1, b.index);
338
+ for (const statement of between) {
339
+ if (this.block(statement) !== a.block || this.isSimple(statement) === false) {
340
+ return undefined;
341
+ }
342
+ }
343
+ return between;
344
+ }
345
+ /** a comment line or end of line comment between the two positions */
346
+ hasComment(start, end) {
347
+ if (this.comments === undefined) {
348
+ this.comments = this.file.getStatements()
349
+ .filter(s => s.get() instanceof _statement_1.Comment
350
+ && !s.getStart().isBefore(this.getStart()) && s.getStart().isBefore(this.getEnd()))
351
+ .map(s => s.getStart());
352
+ }
353
+ return this.comments.some(c => !c.isBefore(start) && c.isBefore(end));
354
+ }
355
+ /** the IF structure of an IF or ELSEIF statement */
356
+ ifStructure(statement) {
357
+ let parent = this.parents.get(statement);
358
+ if (statement.get() instanceof Statements.ElseIf && parent !== undefined) {
359
+ parent = this.parents.get(parent);
360
+ }
361
+ return (parent === null || parent === void 0 ? void 0 : parent.get()) instanceof Structures.If ? parent : undefined;
362
+ }
363
+ /** the variable for an identifier referenced in this procedure,
364
+ * undefined for identifiers without data references, e.g. types or methods */
365
+ variable(identifier) {
366
+ if (!(identifier instanceof _typed_identifier_1.TypedIdentifier)) {
367
+ return undefined;
368
+ }
369
+ const key = ObjectAnalysis.key(identifier);
370
+ if (this.variables.has(key)) {
371
+ return this.variables.get(key);
372
+ }
373
+ const declaration = this.contains(identifier) ? this.declarations.get(key) : undefined;
374
+ const inline = declaration !== undefined && !(declaration.get() instanceof Statements.Data);
375
+ const occurrences = [];
376
+ const known = new Set([position(identifier.getToken())]);
377
+ for (const reference of this.analysis.referencesTo(identifier)) {
378
+ if (!this.contains(reference.position)) {
379
+ continue;
380
+ }
381
+ const token = reference.position.getToken();
382
+ known.add(position(token));
383
+ if (inline && reference.position.getStart().equals(identifier.getStart())
384
+ && reference.referenceType === _reference_1.ReferenceType.DataWriteReference) {
385
+ continue;
386
+ }
387
+ const statement = this.statementOf(token);
388
+ if (statement === undefined) {
389
+ this.variables.set(key, undefined);
390
+ return undefined;
391
+ }
392
+ occurrences.push({ token, statement, index: this.index(statement), kind: this.classify(reference, statement) });
393
+ }
394
+ // several references at the same position, e.g. read and write in LOOP AT itab ASSIGNING
395
+ occurrences.sort((a, b) => a.token.getStart().isBefore(b.token.getStart()) ? -1
396
+ : a.token.getStart().equals(b.token.getStart()) ? 0 : 1);
397
+ const merged = [];
398
+ for (const occurrence of occurrences) {
399
+ const last = merged[merged.length - 1];
400
+ if (last !== undefined && last.token.getStart().equals(occurrence.token.getStart())) {
401
+ if (last.kind !== occurrence.kind) {
402
+ merged[merged.length - 1] = Object.assign(Object.assign({}, last), { kind: rank(last.kind) > rank(occurrence.kind) ? last.kind : occurrence.kind });
403
+ }
404
+ continue;
405
+ }
406
+ merged.push(occurrence);
407
+ }
408
+ let complete = true;
409
+ for (const named of this.names.get(identifier.getName().toLowerCase()) || []) {
410
+ if (!known.has(named)) {
411
+ complete = false;
412
+ }
413
+ }
414
+ const variable = new Variable(identifier, declaration, inline, merged, complete);
415
+ this.variables.set(key, variable);
416
+ return variable;
417
+ }
418
+ /** local variable, declared in the procedure by DATA or inline, and with all its references understood */
419
+ local(identifier) {
420
+ const variable = this.variable(identifier);
421
+ if (variable === undefined || variable.isLocal() === false || variable.complete === false
422
+ || variable.identifier.getMeta().includes("static" /* IdentifierMeta.Static */)) {
423
+ return undefined;
424
+ }
425
+ return variable;
426
+ }
427
+ /** all local variables declared in the procedure */
428
+ locals() {
429
+ var _a;
430
+ const ret = [];
431
+ for (const token of this.declarationTokens) {
432
+ const variable = this.local((_a = this.identifierAt(token)) !== null && _a !== void 0 ? _a : this.declaredIdentifier(token));
433
+ if (variable !== undefined) {
434
+ ret.push(variable);
435
+ }
436
+ }
437
+ return ret;
438
+ }
439
+ /** tokens of the statement, getTokens() builds a new list on every call */
440
+ tokensOf(statement) {
441
+ let tokens = this.tokens.get(statement);
442
+ if (tokens === undefined) {
443
+ tokens = statement.getTokens();
444
+ this.tokens.set(statement, tokens);
445
+ }
446
+ return tokens;
447
+ }
448
+ /** the resolved identifier of the data reference at the token, if any */
449
+ identifierAt(token) {
450
+ for (const reference of this.analysis.referencesAt(this.file.getFilename(), token)) {
451
+ if (reference.referenceType === _reference_1.ReferenceType.DataReadReference
452
+ || reference.referenceType === _reference_1.ReferenceType.DataWriteReference) {
453
+ return reference.resolved;
454
+ }
455
+ }
456
+ return undefined;
457
+ }
458
+ /** the identifier declared at the token, also when it is never referenced */
459
+ declaredIdentifier(token) {
460
+ var _a;
461
+ const found = (_a = this.analysis.spaghetti.lookupPosition(token.getStart(), this.file.getFilename())) === null || _a === void 0 ? void 0 : _a.findVariable(token.getStr());
462
+ return found !== undefined && found.getFilename() === this.file.getFilename()
463
+ && found.getStart().equals(token.getStart()) ? found : undefined;
464
+ }
465
+ /** identifiers declared in the procedure, with all their references */
466
+ ownReferences() {
467
+ if (this.own === undefined) {
468
+ this.own = [];
469
+ for (const [, references] of this.analysis.allReferences()) {
470
+ const resolved = references[0].resolved;
471
+ if (resolved !== undefined && this.contains(resolved)) {
472
+ this.own.push([resolved, references]);
473
+ }
474
+ }
475
+ }
476
+ return this.own;
477
+ }
478
+ statementOf(token) {
479
+ // statement ends are increasing, also for chained statements which share their first tokens
480
+ let low = 0;
481
+ let high = this.statements.length;
482
+ const start = token.getStart();
483
+ while (low < high) {
484
+ const middle = Math.floor((low + high) / 2);
485
+ if (this.statements[middle].getEnd().isBefore(start)) {
486
+ low = middle + 1;
487
+ }
488
+ else {
489
+ high = middle;
490
+ }
491
+ }
492
+ for (let i = low; i < this.statements.length && !start.isBefore(this.statements[i].getStart()); i++) {
493
+ if (this.statements[i].includesToken(token)) {
494
+ return this.statements[i];
495
+ }
496
+ }
497
+ return undefined;
498
+ }
499
+ /** the statement cannot run other ABAP code: no method, function or form call, no constructor, no event */
500
+ isCallFree(statement) {
501
+ var _a;
502
+ const type = statement.get();
503
+ if (!CALL_FREE.some(t => type instanceof t)) {
504
+ return false;
505
+ }
506
+ for (const call of statement.findAllExpressionsRecursive(Expressions.MethodCall)) {
507
+ const name = (_a = call.findDirectExpression(Expressions.MethodName)) === null || _a === void 0 ? void 0 : _a.getFirstToken();
508
+ if (name === undefined) {
509
+ return false;
510
+ }
511
+ const references = this.analysis.referencesAt(this.file.getFilename(), name);
512
+ if (references.length === 0 || references.some(r => r.referenceType !== _reference_1.ReferenceType.BuiltinMethodReference)) {
513
+ return false;
514
+ }
515
+ }
516
+ return statement.findFirstExpression(Expressions.NewObject) === undefined;
517
+ }
518
+ /** every data write in the statement goes to a local variable, a pass-by-value parameter or the
519
+ * RETURNING parameter, ie. memory that no other data object, field symbol or reference can share */
520
+ writesOnlyPrivate(statement) {
521
+ var _a;
522
+ const tokens = this.tokensOf(statement);
523
+ for (let i = 0; i < tokens.length; i++) {
524
+ for (const reference of this.analysis.referencesAt(this.file.getFilename(), tokens[i])) {
525
+ if (reference.referenceType !== _reference_1.ReferenceType.DataWriteReference) {
526
+ continue;
527
+ }
528
+ if (((_a = tokens[i + 1]) === null || _a === void 0 ? void 0 : _a.getStr()) === "->") {
529
+ return false;
530
+ }
531
+ const variable = this.variable(reference.resolved);
532
+ if (variable === undefined || variable.escapes()) {
533
+ return false;
534
+ }
535
+ const meta = variable.identifier.getMeta();
536
+ if (!variable.isLocal() && !meta.includes("returning" /* IdentifierMeta.MethodReturning */)
537
+ && !meta.includes("pass_by_value" /* IdentifierMeta.PassByValue */)) {
538
+ return false;
539
+ }
540
+ }
541
+ }
542
+ // writes without any reference, e.g. to field symbols assigned dynamically, are not expected after the
543
+ // syntax check, but field symbol targets are excluded explicitly
544
+ return statement.findFirstExpression(Expressions.TargetFieldSymbol) === undefined
545
+ && statement.findFirstExpression(Expressions.Dereference) === undefined;
546
+ }
547
+ classify(reference, statement) {
548
+ var _a;
549
+ if (reference.referenceType !== _reference_1.ReferenceType.DataReadReference
550
+ && reference.referenceType !== _reference_1.ReferenceType.DataWriteReference) {
551
+ return OccurrenceKind.Escape;
552
+ }
553
+ const token = reference.position.getToken();
554
+ const tokens = this.tokensOf(statement);
555
+ const index = tokens.findIndex(t => t.getStart().equals(token.getStart()));
556
+ if (index < 0) {
557
+ return OccurrenceKind.Escape;
558
+ }
559
+ const path = expressionPath(statement, token);
560
+ if (path.some(e => e.get() instanceof Expressions.Dynamic)) {
561
+ return OccurrenceKind.Escape;
562
+ }
563
+ if (((_a = tokens[index + 1]) === null || _a === void 0 ? void 0 : _a.getStr()) === "->") {
564
+ // the reference itself is not changed, nor exposed, only the object or data it points to
565
+ return OccurrenceKind.Read;
566
+ }
567
+ if (reference.referenceType === _reference_1.ReferenceType.DataWriteReference) {
568
+ return OccurrenceKind.Write;
569
+ }
570
+ const type = statement.get();
571
+ if (!READING.some(t => type instanceof t)
572
+ || statement.findFirstExpression(Expressions.FSTarget) !== undefined
573
+ || statement.findTokenSequencePosition("REFERENCE", "INTO") !== undefined
574
+ || path.some(e => e.get() instanceof Expressions.Source && isRefConstructor(e))) {
575
+ return OccurrenceKind.Escape;
576
+ }
577
+ return OccurrenceKind.Read;
578
+ }
579
+ isSupported() {
580
+ for (const statement of this.statements) {
581
+ const type = statement.get();
582
+ if (type instanceof Statements.Include || type instanceof _statement_1.NativeSQL
583
+ || type instanceof Statements.TestSeam || type instanceof Statements.TestInjection
584
+ || type instanceof Statements.Enhancement || type instanceof Statements.EnhancementSection
585
+ || type instanceof Statements.ExecSQL
586
+ || statement.findFirstExpression(Expressions.Dynamic) !== undefined) {
587
+ return false;
588
+ }
589
+ }
590
+ return true;
591
+ }
592
+ walk(node, blockPath, loop, simple) {
593
+ const type = node.get();
594
+ if (type instanceof Structures.Body) {
595
+ blockPath = [...blockPath, node];
596
+ }
597
+ else if (LOOPS.some(l => type instanceof l) || (type instanceof Structures.Try && retries(node))) {
598
+ loop = node;
599
+ }
600
+ for (const child of node.getChildren()) {
601
+ this.parents.set(child, node);
602
+ if (child instanceof nodes_1.StructureNode) {
603
+ this.walk(child, blockPath, loop, child.get() instanceof Structures.Normal);
604
+ }
605
+ else if (child instanceof nodes_1.StatementNode) {
606
+ this.info.set(child, {
607
+ index: this.statements.length,
608
+ block: blockPath[blockPath.length - 1],
609
+ blockPath,
610
+ loop,
611
+ simple: simple && type instanceof Structures.Normal,
612
+ });
613
+ this.statements.push(child);
614
+ }
615
+ }
616
+ }
617
+ }
618
+ exports.Procedure = Procedure;
619
+ function position(token) {
620
+ return token.getRow() * 100000 + token.getCol();
621
+ }
622
+ function rank(kind) {
623
+ return kind === OccurrenceKind.Escape ? 2 : kind === OccurrenceKind.Write ? 1 : 0;
624
+ }
625
+ /** RETRY and RESUME jump back into the TRY block, as does a CATCH BEFORE UNWIND handler */
626
+ function retries(node) {
627
+ return node.findAllStatements(Statements.Retry).length > 0
628
+ || node.findAllStatements(Statements.Resume).length > 0
629
+ || node.findAllStatements(Statements.Catch).some(c => c.findDirectTokenByText("UNWIND") !== undefined);
630
+ }
631
+ function isRefConstructor(source) {
632
+ const first = source.getChildren()[0];
633
+ return first instanceof nodes_1.TokenNode && first.getFirstToken().getStr().toUpperCase() === "REF"
634
+ && source.findDirectExpression(Expressions.TypeNameOrInfer) !== undefined;
635
+ }
636
+ function findStructures(node, types) {
637
+ if (types.some(t => node.get() instanceof t)) {
638
+ return [node];
639
+ }
640
+ const ret = [];
641
+ for (const child of node.getChildren()) {
642
+ if (child instanceof nodes_1.StructureNode) {
643
+ ret.push(...findStructures(child, types));
644
+ }
645
+ }
646
+ return ret;
647
+ }
648
+ /** expression nodes from the statement down to the token */
649
+ function expressionPath(statement, token) {
650
+ const ret = [];
651
+ let children = statement.getChildren();
652
+ for (;;) {
653
+ let next = undefined;
654
+ for (const child of children) {
655
+ if (child instanceof nodes_1.ExpressionNode
656
+ && !token.getStart().isBefore(child.getFirstToken().getStart())
657
+ && !child.getLastToken().getStart().isBefore(token.getStart())) {
658
+ next = child;
659
+ break;
660
+ }
661
+ }
662
+ if (next === undefined) {
663
+ return ret;
664
+ }
665
+ ret.push(next);
666
+ children = next.getChildren();
667
+ }
668
+ }
669
+ /** target = source. or target ?= source. without chaining, pragmas or MOVE */
670
+ function plainMove(statement) {
671
+ if (!(statement.get() instanceof Statements.Move) || statement.getColon() !== undefined
672
+ || statement.getPragmas().length > 0) {
673
+ return undefined;
674
+ }
675
+ const target = statement.findDirectExpression(Expressions.Target);
676
+ const source = statement.findDirectExpression(Expressions.Source);
677
+ const tokens = statement.getTokens();
678
+ if (target === undefined || source === undefined
679
+ || tokens.length !== target.countTokens() + source.countTokens() + 2) {
680
+ return undefined;
681
+ }
682
+ const operator = tokens[target.countTokens()].getStr();
683
+ if (operator !== "=" && operator !== "?=") {
684
+ return undefined;
685
+ }
686
+ return { target, source, operator };
687
+ }
688
+ /** the source is a single field, ie. one token */
689
+ function singleField(source) {
690
+ var _a;
691
+ if (source.getChildren().length !== 1 || source.countTokens() !== 1) {
692
+ return undefined;
693
+ }
694
+ const field = (_a = source.findDirectExpression(Expressions.FieldChain)) === null || _a === void 0 ? void 0 : _a.findDirectExpression(Expressions.SourceField);
695
+ return field === null || field === void 0 ? void 0 : field.getFirstToken();
696
+ }
697
+ /** the target is a single field, ie. one token, not an inline declaration */
698
+ function singleTarget(target) {
699
+ if (target.countTokens() !== 1 || target.findDirectExpression(Expressions.TargetField) === undefined) {
700
+ return undefined;
701
+ }
702
+ return target.getFirstToken();
703
+ }
704
+ /** CLEAR name. without chaining or WITH */
705
+ function plainClear(statement) {
706
+ if (!(statement.get() instanceof Statements.Clear) || statement.getPragmas().length > 0) {
707
+ return undefined;
708
+ }
709
+ const targets = statement.findDirectExpressions(Expressions.Target);
710
+ const tokens = statement.getTokens();
711
+ if (targets.length !== 1 || tokens.length !== 3 || tokens[0].getStr().toUpperCase() !== "CLEAR") {
712
+ return undefined;
713
+ }
714
+ return singleTarget(targets[0]);
715
+ }
716
+ /** DATA name TYPE/LIKE ... without VALUE, without chaining */
717
+ function plainData(statement) {
718
+ var _a;
719
+ return statement.get() instanceof Statements.Data
720
+ && ((_a = statement.findDirectExpression(Expressions.DataDefinition)) === null || _a === void 0 ? void 0 : _a.findDirectExpression(Expressions.Value)) === undefined;
721
+ }
722
+ /** constants of the class or program, builtin constants like abap_true, and me: never change */
723
+ function isImmutable(identifier) {
724
+ if (!(identifier instanceof _typed_identifier_1.TypedIdentifier)) {
725
+ return false;
726
+ }
727
+ const meta = identifier.getMeta();
728
+ if (identifier.getName().toLowerCase() === "me" && identifier.getType() instanceof basic_1.ObjectReferenceType) {
729
+ return true;
730
+ }
731
+ return meta.includes("read_only" /* IdentifierMeta.ReadOnly */)
732
+ && (meta.includes("static" /* IdentifierMeta.Static */) || (meta.includes("built-in" /* IdentifierMeta.BuiltIn */) && identifier.getValue() !== undefined));
733
+ }
734
+ function isReferenceType(type) {
735
+ return type instanceof basic_1.ObjectReferenceType || type instanceof basic_1.DataReference;
736
+ }
737
+ /** same runtime type, so assignments between the two never convert */
738
+ function identicalTypes(first, second) {
739
+ var _a, _b;
740
+ if (first instanceof basic_1.UnknownType || second instanceof basic_1.UnknownType
741
+ || first instanceof basic_1.VoidType || second instanceof basic_1.VoidType
742
+ || first.isGeneric() || second.isGeneric()
743
+ || first.constructor !== second.constructor) {
744
+ return false;
745
+ }
746
+ if (first instanceof basic_1.StructureType || first instanceof basic_1.TableType) {
747
+ const firstName = (_a = first.getQualifiedName()) === null || _a === void 0 ? void 0 : _a.toUpperCase();
748
+ return firstName !== undefined && firstName === ((_b = second.getQualifiedName()) === null || _b === void 0 ? void 0 : _b.toUpperCase());
749
+ }
750
+ if (isReferenceType(first)) {
751
+ return first.toABAP().toUpperCase() === second.toABAP().toUpperCase();
752
+ }
753
+ return first.toABAP() === second.toABAP();
754
+ }
755
+ ////////////////////////////////////////
756
+ // conditions
757
+ var PredicateKind;
758
+ (function (PredicateKind) {
759
+ PredicateKind["Equal"] = "equal";
760
+ PredicateKind["Initial"] = "initial";
761
+ PredicateKind["Bound"] = "bound";
762
+ })(PredicateKind || (exports.PredicateKind = PredicateKind = {}));
763
+ /** the condition of IF or ELSEIF is one comparison: a = b, a EQ b, a <> b, a NE b,
764
+ * a IS [NOT] INITIAL, a IS [NOT] BOUND, optionally prefixed with NOT */
765
+ function simplePredicate(statement) {
766
+ if (!(statement.get() instanceof Statements.If || statement.get() instanceof Statements.ElseIf)
767
+ || statement.getColon() !== undefined) {
768
+ return undefined;
769
+ }
770
+ const cond = statement.findDirectExpression(Expressions.Cond);
771
+ if (cond === undefined || cond.getChildren().length !== 1) {
772
+ return undefined;
773
+ }
774
+ const compare = cond.findDirectExpression(Expressions.Compare);
775
+ if (compare === undefined) {
776
+ return undefined;
777
+ }
778
+ const children = compare.getChildren();
779
+ let negated = false;
780
+ let i = 0;
781
+ if (children[0] instanceof nodes_1.TokenNode && children[0].getFirstToken().getStr().toUpperCase() === "NOT") {
782
+ negated = true;
783
+ i = 1;
784
+ }
785
+ const left = children[i];
786
+ if (!(left instanceof nodes_1.ExpressionNode) || !(left.get() instanceof Expressions.Source)) {
787
+ return undefined;
788
+ }
789
+ const rest = children.slice(i + 1);
790
+ const words = rest.map(c => c instanceof nodes_1.TokenNode ? c.getFirstToken().getStr().toUpperCase() : "");
791
+ if (rest.length === 2 && rest[0].get() instanceof Expressions.CompareOperator
792
+ && rest[1] instanceof nodes_1.ExpressionNode && rest[1].get() instanceof Expressions.Source) {
793
+ const operator = rest[0].getFirstToken().getStr().toUpperCase();
794
+ if (rest[0].countTokens() !== 1 || !["=", "EQ", "<>", "NE"].includes(operator)) {
795
+ return undefined;
796
+ }
797
+ return { kind: PredicateKind.Equal, left, right: rest[1], negated: negated !== (operator === "<>" || operator === "NE") };
798
+ }
799
+ else if (words.join(" ") === "IS INITIAL" || words.join(" ") === "IS NOT INITIAL") {
800
+ return { kind: PredicateKind.Initial, left, negated: negated !== (words.length === 3) };
801
+ }
802
+ else if (words.join(" ") === "IS BOUND" || words.join(" ") === "IS NOT BOUND") {
803
+ return { kind: PredicateKind.Bound, left, negated: negated !== (words.length === 3) };
804
+ }
805
+ return undefined;
806
+ }
807
+ /** value of a character literal 'abc', or of a character constant like abap_true, undefined otherwise */
808
+ function characterConstant(procedure, source) {
809
+ var _a;
810
+ if (source.getChildren().length !== 1) {
811
+ return undefined;
812
+ }
813
+ const literal = (_a = source.findDirectExpression(Expressions.Constant)) === null || _a === void 0 ? void 0 : _a.findDirectExpression(Expressions.ConstantString);
814
+ if (literal !== undefined) {
815
+ return literal.countTokens() === 1 ? textLiteral(literal.getFirstToken().getStr()) : undefined;
816
+ }
817
+ const field = singleField(source);
818
+ const identifier = field === undefined ? undefined : procedure.identifierAt(field);
819
+ if (identifier instanceof _typed_identifier_1.TypedIdentifier && isImmutable(identifier)
820
+ && identifier.getType() instanceof basic_1.CharacterType) {
821
+ const value = identifier.getValue();
822
+ return typeof value === "string" ? textLiteral(value) : undefined;
823
+ }
824
+ return undefined;
825
+ }
826
+ function textLiteral(text) {
827
+ if (text.length < 2 || !text.startsWith("'") || !text.endsWith("'")) {
828
+ return undefined;
829
+ }
830
+ return text.substring(1, text.length - 1).replace(/''/g, "'");
831
+ }
832
+ /** character values compare after padding the shorter one with blanks */
833
+ function sameCharacters(first, second) {
834
+ return first.replace(/ +$/, "") === second.replace(/ +$/, "");
835
+ }
836
+ /** IF, ELSEIF, WHILE, CHECK, CASE or WHEN: a constant compared there is left for constant_condition,
837
+ * instead of replacing a variable by a constant and comparing two constants */
838
+ function isCondition(statement) {
839
+ const type = statement.get();
840
+ return type instanceof Statements.If || type instanceof Statements.ElseIf || type instanceof Statements.While
841
+ || type instanceof Statements.Check || type instanceof Statements.Case || type instanceof Statements.When;
842
+ }
843
+ ////////////////////////////////////////
844
+ // data sources
845
+ var SourceKind;
846
+ (function (SourceKind) {
847
+ /** constants and me, never change */
848
+ SourceKind["Immutable"] = "immutable";
849
+ /** a local variable, or a component of it, changes only by references to the variable */
850
+ SourceKind["Local"] = "local";
851
+ /** attributes, parameters, globals, anything reached via a reference: may change by other code */
852
+ SourceKind["Volatile"] = "volatile";
853
+ })(SourceKind || (exports.SourceKind = SourceKind = {}));
854
+ /** a plain data object: field, constant, attribute or component chain without calls, offsets, table
855
+ * expressions, field symbols or dereferencing with ->* */
856
+ function dataSource(procedure, source) {
857
+ var _a;
858
+ if (source.getChildren().length !== 1) {
859
+ return undefined;
860
+ }
861
+ const chain = source.findDirectExpression(Expressions.FieldChain);
862
+ if (chain === undefined) {
863
+ return undefined;
864
+ }
865
+ const children = chain.getChildren();
866
+ let first;
867
+ let next;
868
+ if (children[0] instanceof nodes_1.ExpressionNode && children[0].get() instanceof Expressions.SourceField) {
869
+ first = procedure.identifierAt(children[0].getFirstToken());
870
+ next = 1;
871
+ }
872
+ else if (children[0] instanceof nodes_1.ExpressionNode && children[0].get() instanceof Expressions.ClassName
873
+ && ((_a = children[1]) === null || _a === void 0 ? void 0 : _a.getFirstToken().getStr()) === "=>" && children[2] instanceof nodes_1.ExpressionNode
874
+ && children[2].get() instanceof Expressions.AttributeName) {
875
+ first = procedure.identifierAt(children[2].getFirstToken());
876
+ next = 3;
877
+ }
878
+ else {
879
+ return undefined;
880
+ }
881
+ if (!(first instanceof _typed_identifier_1.TypedIdentifier)
882
+ || (first.getMeta().includes("built-in" /* IdentifierMeta.BuiltIn */) && !isImmutable(first))) {
883
+ // system fields like sy-subrc and sy-tabix are changed by many statements without a write reference
884
+ return undefined;
885
+ }
886
+ let type = first.getType();
887
+ let deref = false;
888
+ for (let i = next; i < children.length; i += 2) {
889
+ const separator = children[i];
890
+ const name = children[i + 1];
891
+ if (!(separator instanceof nodes_1.TokenNode) || !(name instanceof nodes_1.ExpressionNode) || type === undefined) {
892
+ return undefined;
893
+ }
894
+ if (type instanceof basic_1.TableType && type.isWithHeader()) {
895
+ return undefined;
896
+ }
897
+ else if (separator.getFirstToken().getStr() === "->" && name.get() instanceof Expressions.AttributeName) {
898
+ const attribute = procedure.identifierAt(name.getFirstToken());
899
+ type = attribute instanceof _typed_identifier_1.TypedIdentifier ? attribute.getType() : undefined;
900
+ deref = true;
901
+ }
902
+ else if (separator.getFirstToken().getStr() === "-" && name.get() instanceof Expressions.ComponentName
903
+ && type instanceof basic_1.StructureType) {
904
+ type = type.getComponentByName(name.getFirstToken().getStr());
905
+ }
906
+ else {
907
+ return undefined;
908
+ }
909
+ }
910
+ if (type === undefined || type.isGeneric() || (type instanceof basic_1.TableType && type.isWithHeader())) {
911
+ return undefined;
912
+ }
913
+ const local = next === 1 ? procedure.local(first) : undefined;
914
+ let kind = SourceKind.Volatile;
915
+ if (deref === false && isImmutable(first)) {
916
+ kind = SourceKind.Immutable;
917
+ }
918
+ else if (deref === false && local !== undefined) {
919
+ kind = SourceKind.Local;
920
+ }
921
+ return { text: nodeText(procedure.file, source), kind, base: local, type };
922
+ }
923
+ /** type of a plain target: variable, field symbol, attribute or component chain, not an inline declaration,
924
+ * without offsets, table expressions or ->* */
925
+ function targetType(procedure, target) {
926
+ var _a;
927
+ const children = target.getChildren();
928
+ let identifier;
929
+ let next;
930
+ const first = children[0];
931
+ if (first instanceof nodes_1.ExpressionNode
932
+ && (first.get() instanceof Expressions.TargetField || first.get() instanceof Expressions.TargetFieldSymbol)) {
933
+ identifier = procedure.identifierAt(first.getFirstToken());
934
+ next = 1;
935
+ }
936
+ else if (first instanceof nodes_1.ExpressionNode && first.get() instanceof Expressions.ClassName
937
+ && ((_a = children[1]) === null || _a === void 0 ? void 0 : _a.getFirstToken().getStr()) === "=>" && children[2] instanceof nodes_1.ExpressionNode
938
+ && children[2].get() instanceof Expressions.AttributeName) {
939
+ identifier = procedure.identifierAt(children[2].getFirstToken());
940
+ next = 3;
941
+ }
942
+ else {
943
+ return undefined;
944
+ }
945
+ let type = identifier instanceof _typed_identifier_1.TypedIdentifier ? identifier.getType() : undefined;
946
+ for (let i = next; i < children.length; i += 2) {
947
+ const separator = children[i];
948
+ const name = children[i + 1];
949
+ if (!(separator instanceof nodes_1.TokenNode) || !(name instanceof nodes_1.ExpressionNode) || type === undefined) {
950
+ return undefined;
951
+ }
952
+ if (separator.getFirstToken().getStr() === "->" && name.get() instanceof Expressions.AttributeName) {
953
+ const attribute = procedure.identifierAt(name.getFirstToken());
954
+ type = attribute instanceof _typed_identifier_1.TypedIdentifier ? attribute.getType() : undefined;
955
+ }
956
+ else if (separator.getFirstToken().getStr() === "-" && name.get() instanceof Expressions.ComponentName
957
+ && type instanceof basic_1.StructureType) {
958
+ type = type.getComponentByName(name.getFirstToken().getStr());
959
+ }
960
+ else {
961
+ return undefined;
962
+ }
963
+ }
964
+ if (type === undefined || (type instanceof basic_1.TableType && type.isWithHeader())) {
965
+ return undefined;
966
+ }
967
+ return type;
968
+ }
969
+ /**
970
+ * The data source has the same value at the end of statement "to" as at the end of statement "from".
971
+ * When "read" is given, it is the token in statement "to" that reads the value; writes of statement "to"
972
+ * after its sources are evaluated, ie. the target of a MOVE or the call after evaluating its receiver, do not count.
973
+ */
974
+ function unchangedBetween(procedure, source, from, to, read) {
975
+ if (source.kind === SourceKind.Immutable) {
976
+ return true;
977
+ }
978
+ const start = procedure.index(from);
979
+ const end = procedure.index(to);
980
+ if (start < 0 || end < start) {
981
+ return false;
982
+ }
983
+ if (source.base !== undefined && (source.base.escapes()
984
+ || source.base.writes().some(w => w.index > start && w.index <= end))) {
985
+ return false;
986
+ }
987
+ if (source.kind === SourceKind.Local) {
988
+ return source.base !== undefined;
989
+ }
990
+ for (let index = start + 1; index <= end; index++) {
991
+ const statement = procedure.statements[index];
992
+ if (index === end && read !== undefined) {
993
+ if (isReceiver(statement, read)
994
+ || (statement.get() instanceof Statements.Move && procedure.isCallFree(statement))) {
995
+ continue;
996
+ }
997
+ }
998
+ if (!procedure.isCallFree(statement) || !procedure.writesOnlyPrivate(statement)) {
999
+ return false;
1000
+ }
1001
+ }
1002
+ return true;
1003
+ }
1004
+ /** the token is the receiver of the method call chain of the statement: a->m( ). or x = a->m( ).
1005
+ * The receiver is evaluated before the arguments and the call */
1006
+ function isReceiver(statement, token) {
1007
+ var _a, _b;
1008
+ let chain;
1009
+ if (statement.get() instanceof Statements.Call) {
1010
+ chain = statement.findDirectExpression(Expressions.MethodCallChain);
1011
+ }
1012
+ else if (((_a = plainMove(statement)) === null || _a === void 0 ? void 0 : _a.source.getChildren().length) === 1) {
1013
+ chain = plainMove(statement).source.findDirectExpression(Expressions.MethodCallChain);
1014
+ }
1015
+ const receiver = chain === null || chain === void 0 ? void 0 : chain.getChildren()[0];
1016
+ return receiver instanceof nodes_1.ExpressionNode && receiver.get() instanceof Expressions.FieldChain
1017
+ && receiver.countTokens() === 1 && receiver.getFirstToken().getStart().equals(token.getStart())
1018
+ && ((_b = chain === null || chain === void 0 ? void 0 : chain.getChildren()[1]) === null || _b === void 0 ? void 0 : _b.getFirstToken().getStr()) === "->";
1019
+ }
1020
+ ////////////////////////////////////////
1021
+ // edits
1022
+ const rowCache = new WeakMap();
1023
+ /** getRawRows() splits the source on every call; a file is never changed, edits create a new one */
1024
+ function rowsOf(file) {
1025
+ let rows = rowCache.get(file);
1026
+ if (rows === undefined) {
1027
+ rows = file.getRawRows();
1028
+ rowCache.set(file, rows);
1029
+ }
1030
+ return rows;
1031
+ }
1032
+ /** edits of one fix, sorted so that applying them one after the other keeps the positions valid */
1033
+ function mergeEdits(file, edits) {
1034
+ const list = [];
1035
+ for (const edit of edits) {
1036
+ list.push(...edit[file.getFilename()] || []);
1037
+ }
1038
+ list.sort((a, b) => {
1039
+ if (a.range.start.equals(b.range.start)) {
1040
+ return 0;
1041
+ }
1042
+ return a.range.start.isAfter(b.range.start) ? -1 : 1;
1043
+ });
1044
+ return { [file.getFilename()]: list };
1045
+ }
1046
+ /** deletes the statements from first to last, the full lines if nothing else is on them */
1047
+ function deleteRegion(file, first, last) {
1048
+ if (first === last && first.getColon() !== undefined) {
1049
+ return edit_helper_1.EditHelper.deleteStatement(file, first);
1050
+ }
1051
+ const rows = rowsOf(file);
1052
+ const start = first.getStart();
1053
+ const end = last.getEnd();
1054
+ const before = rows[start.getRow() - 1].substring(0, start.getCol() - 1);
1055
+ const after = rows[end.getRow() - 1].substring(end.getCol() - 1);
1056
+ if (before.trim() === "" && after.trim() === "" && end.getRow() < rows.length) {
1057
+ return edit_helper_1.EditHelper.deleteRange(file, new position_1.Position(start.getRow(), 1), new position_1.Position(end.getRow() + 1, 1));
1058
+ }
1059
+ return edit_helper_1.EditHelper.deleteRange(file, start, end);
1060
+ }
1061
+ function deleteStatement(file, statement) {
1062
+ return deleteRegion(file, statement, statement);
1063
+ }
1064
+ /** the source code between two positions, as written */
1065
+ function rawText(file, start, end) {
1066
+ const rows = rowsOf(file);
1067
+ if (start.getRow() === end.getRow()) {
1068
+ return rows[start.getRow() - 1].substring(start.getCol() - 1, end.getCol() - 1);
1069
+ }
1070
+ const ret = [rows[start.getRow() - 1].substring(start.getCol() - 1)];
1071
+ for (let row = start.getRow() + 1; row < end.getRow(); row++) {
1072
+ ret.push(rows[row - 1]);
1073
+ }
1074
+ ret.push(rows[end.getRow() - 1].substring(0, end.getCol() - 1));
1075
+ return ret.join("\n");
1076
+ }
1077
+ function nodeText(file, node) {
1078
+ return rawText(file, node.getFirstToken().getStart(), node.getLastToken().getEnd());
1079
+ }
1080
+ /** the IF, ELSEIF and ELSE branches of an IF structure */
1081
+ function ifBranches(structure) {
1082
+ const branches = [];
1083
+ for (const child of structure.getChildren()) {
1084
+ if (child instanceof nodes_1.StatementNode) {
1085
+ if (child.get() instanceof Statements.If) {
1086
+ branches.push({ statement: child, body: undefined });
1087
+ }
1088
+ }
1089
+ else if (child.get() instanceof Structures.Body) {
1090
+ if (branches.length !== 1) {
1091
+ return undefined;
1092
+ }
1093
+ branches[0].body = child;
1094
+ }
1095
+ else if (child.get() instanceof Structures.ElseIf || child.get() instanceof Structures.Else) {
1096
+ const statement = child.getFirstStatement();
1097
+ if (statement === undefined) {
1098
+ return undefined;
1099
+ }
1100
+ branches.push({ statement, body: child.findDirectStructure(Structures.Body) });
1101
+ }
1102
+ }
1103
+ return branches.length > 0 ? branches : undefined;
1104
+ }
1105
+ /** a region of statements can be deleted if nothing declared in it is used outside of it */
1106
+ function selfContained(procedure, first, last) {
1107
+ const filename = procedure.file.getFilename();
1108
+ const start = first.getStart();
1109
+ const end = last.getEnd();
1110
+ const inside = (identifier) => identifier.getFilename() === filename
1111
+ && !identifier.getStart().isBefore(start) && !identifier.getStart().isAfter(end);
1112
+ for (const [resolved, references] of procedure.ownReferences()) {
1113
+ if (inside(resolved) && references.some(r => !inside(r.position))) {
1114
+ return false;
1115
+ }
1116
+ }
1117
+ return true;
1118
+ }
1119
+ /**
1120
+ * Removes an IF branch whose condition is known.
1121
+ * decided: the IF or ELSEIF statement whose condition always has the given value.
1122
+ * Returns undefined if a removed branch declares something used outside of it.
1123
+ */
1124
+ function foldIf(procedure, structure, decided, value) {
1125
+ var _a;
1126
+ const file = procedure.file;
1127
+ const branches = ifBranches(structure);
1128
+ const endIf = structure.findDirectStatement(Statements.EndIf);
1129
+ const k = (_a = branches === null || branches === void 0 ? void 0 : branches.findIndex(b => b.statement === decided)) !== null && _a !== void 0 ? _a : -1;
1130
+ if (branches === undefined || endIf === undefined || k < 0
1131
+ || branches[k].statement.get() instanceof Statements.Else
1132
+ || structure.getChildren().some(c => c instanceof nodes_1.StatementNode && c.getColon() !== undefined)
1133
+ || branches.some(b => b.statement.getColon() !== undefined)) {
1134
+ return undefined;
1135
+ }
1136
+ const lastOf = (index) => {
1137
+ var _a;
1138
+ const statements = ((_a = branches[index].body) === null || _a === void 0 ? void 0 : _a.findAllStatementNodes()) || [];
1139
+ return statements.length > 0 ? statements[statements.length - 1] : branches[index].statement;
1140
+ };
1141
+ const dead = (from, to) => {
1142
+ // branches from..to are removed, including their statements
1143
+ return selfContained(procedure, branches[from].statement, lastOf(to));
1144
+ };
1145
+ const last = branches.length - 1;
1146
+ const edits = [];
1147
+ if (value === true) {
1148
+ if (k < last && !dead(k + 1, last)) {
1149
+ return undefined;
1150
+ }
1151
+ if (k === 0) {
1152
+ edits.push(deleteStatement(file, branches[0].statement));
1153
+ edits.push(k < last ? deleteRegion(file, branches[k + 1].statement, endIf) : deleteStatement(file, endIf));
1154
+ }
1155
+ else {
1156
+ edits.push(edit_helper_1.EditHelper.replaceRange(file, decided.getStart(), decided.getEnd(), "ELSE."));
1157
+ if (k < last) {
1158
+ edits.push(deleteRegion(file, branches[k + 1].statement, lastOf(last)));
1159
+ }
1160
+ }
1161
+ }
1162
+ else {
1163
+ if (!dead(k, k)) {
1164
+ return undefined;
1165
+ }
1166
+ if (k === 0) {
1167
+ if (last === 0) {
1168
+ edits.push(deleteRegion(file, branches[0].statement, endIf));
1169
+ }
1170
+ else {
1171
+ edits.push(deleteRegion(file, branches[0].statement, lastOf(0)));
1172
+ const next = branches[1].statement;
1173
+ if (next.get() instanceof Statements.ElseIf) {
1174
+ edits.push(edit_helper_1.EditHelper.replaceToken(file, next.getFirstToken(), "IF"));
1175
+ }
1176
+ else {
1177
+ edits.push(deleteStatement(file, next));
1178
+ edits.push(deleteStatement(file, endIf));
1179
+ }
1180
+ }
1181
+ }
1182
+ else {
1183
+ edits.push(deleteRegion(file, branches[k].statement, lastOf(k)));
1184
+ }
1185
+ }
1186
+ return mergeEdits(file, edits);
1187
+ }
1188
+ /**
1189
+ * Issues for folds of IF structures. The edits of a fold inside a removed branch of another fold can not be
1190
+ * applied in the same round, and abaplint --fix only checks if the rows of a new fix cover the first or last row
1191
+ * of an accepted one. So only the outermost fold, and the first fold of an IF, keeps its quick fix; the others
1192
+ * are reported without, and get their fix in the next round.
1193
+ */
1194
+ function foldIssues(file, candidates, key, severity) {
1195
+ const contains = (outer, inner) => !inner.getFirstToken().getStart().isBefore(outer.getFirstToken().getStart())
1196
+ && !outer.getLastToken().getEnd().isBefore(inner.getLastToken().getEnd());
1197
+ return candidates.map((candidate, index) => {
1198
+ const nested = candidates.some((other, otherIndex) => other.structure === candidate.structure
1199
+ ? otherIndex < index
1200
+ : contains(other.structure, candidate.structure));
1201
+ return issue_1.Issue.atStatement(file, candidate.statement, candidate.message, key, severity, nested ? undefined : candidate.fix);
1202
+ });
1203
+ }
1204
+ //# sourceMappingURL=_procedure_analysis.js.map