@abaplint/core 2.120.108 → 2.120.110

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.
@@ -1591,6 +1591,8 @@ export declare class CurrentScope {
1591
1591
  protected allowHeaderUse: string | undefined;
1592
1592
  protected parentObj: IObject;
1593
1593
  private readonly localFriends;
1594
+ /** types of the FOR and LET names used in a procedure, key is the scope node of the procedure */
1595
+ private readonly localNameTypes;
1594
1596
  static buildDefault(reg: IRegistry, obj: IObject): CurrentScope;
1595
1597
  private static addBuiltIn;
1596
1598
  private constructor();
@@ -1651,6 +1653,16 @@ export declare class CurrentScope {
1651
1653
  isInStaticMethod(): boolean;
1652
1654
  addLocalFriend(className: string, friendName: string): void;
1653
1655
  isLocalFriend(className: string, friendName: string): boolean;
1656
+ /**
1657
+ * Checks a local name of a constructor expression, FOR, LET and REDUCE INIT, before it is added,
1658
+ * returns the error message, or undefined when the name can be declared.
1659
+ * The name cannot be a data object of the procedure or of an enclosing expression, attributes and
1660
+ * globals seen from a method or a form are only obscured, which ABAP reports as a warning.
1661
+ * Within a procedure, a name can be reused by another expression only with the same type.
1662
+ */
1663
+ checkLocalName(name: string, type: AbstractType | undefined): string | undefined;
1664
+ /** types are compared by their structure, ABAP compares the declared types, so this finds a subset of the errors */
1665
+ private static isComparable;
1654
1666
  getEnclosingMethodName(): string | undefined;
1655
1667
  getEnclosingClassName(): string | undefined;
1656
1668
  isGlobalOO(): boolean;
@@ -8,6 +8,9 @@ const spaghetti_scope_1 = require("./spaghetti_scope");
8
8
  const _identifier_1 = require("../4_file_information/_identifier");
9
9
  const _scope_type_1 = require("./_scope_type");
10
10
  const syntax_1 = require("./syntax");
11
+ const basic_1 = require("../types/basic");
12
+ /** scopes of constructor expressions, their names are local to the expression */
13
+ const EXPRESSION_SCOPES = new Set([_scope_type_1.ScopeType.For, _scope_type_1.ScopeType.Let, _scope_type_1.ScopeType.OpenSQL]);
11
14
  class CurrentScope {
12
15
  static buildDefault(reg, obj) {
13
16
  const s = new CurrentScope(reg, obj);
@@ -30,6 +33,8 @@ class CurrentScope {
30
33
  }
31
34
  constructor(reg, obj) {
32
35
  this.localFriends = new Map();
36
+ /** types of the FOR and LET names used in a procedure, key is the scope node of the procedure */
37
+ this.localNameTypes = new WeakMap();
33
38
  this.current = undefined;
34
39
  this.parentObj = obj;
35
40
  this.reg = reg;
@@ -518,6 +523,50 @@ class CurrentScope {
518
523
  var _a;
519
524
  return ((_a = this.localFriends.get(className.toUpperCase())) === null || _a === void 0 ? void 0 : _a.includes(friendName.toUpperCase())) === true;
520
525
  }
526
+ /**
527
+ * Checks a local name of a constructor expression, FOR, LET and REDUCE INIT, before it is added,
528
+ * returns the error message, or undefined when the name can be declared.
529
+ * The name cannot be a data object of the procedure or of an enclosing expression, attributes and
530
+ * globals seen from a method or a form are only obscured, which ABAP reports as a warning.
531
+ * Within a procedure, a name can be reused by another expression only with the same type.
532
+ */
533
+ checkLocalName(name, type) {
534
+ const upper = name.toUpperCase();
535
+ let procedure = this.current;
536
+ while (procedure !== undefined) {
537
+ if (procedure.getData().vars[upper] !== undefined) {
538
+ return `Variable ${name} already defined`;
539
+ }
540
+ if (EXPRESSION_SCOPES.has(procedure.getIdentifier().stype) === false) {
541
+ break;
542
+ }
543
+ procedure = procedure.getParent();
544
+ }
545
+ if (procedure === undefined || type === undefined || CurrentScope.isComparable(type) === false) {
546
+ return undefined;
547
+ }
548
+ let names = this.localNameTypes.get(procedure);
549
+ if (names === undefined) {
550
+ names = new Map();
551
+ this.localNameTypes.set(procedure, names);
552
+ }
553
+ const previous = names.get(upper);
554
+ if (previous === undefined) {
555
+ names.set(upper, type);
556
+ }
557
+ else if (previous.toText(0) !== type.toText(0)) {
558
+ return `Variable ${name} already defined with a different type`;
559
+ }
560
+ return undefined;
561
+ }
562
+ /** types are compared by their structure, ABAP compares the declared types, so this finds a subset of the errors */
563
+ static isComparable(type) {
564
+ return !(type instanceof basic_1.VoidType)
565
+ && !(type instanceof basic_1.UnknownType)
566
+ && type.containsVoid() === false
567
+ && type.isGeneric() === false
568
+ && type.toText(0).includes("Unknown type") === false;
569
+ }
521
570
  getEnclosingMethodName() {
522
571
  let curr = this.current;
523
572
  while (curr !== undefined) {
@@ -45,6 +45,7 @@ const basic_1 = require("../../types/basic");
45
45
  const _typed_identifier_1 = require("../../types/_typed_identifier");
46
46
  const _reference_1 = require("../_reference");
47
47
  const let_1 = require("./let");
48
+ const _syntax_input_1 = require("../_syntax_input");
48
49
  class For {
49
50
  static runSyntax(node, input) {
50
51
  var _a;
@@ -69,6 +70,11 @@ class For {
69
70
  inline_field_definition_1.InlineFieldDefinition.runSyntax(f, input);
70
71
  }
71
72
  if (groupsToken !== undefined) {
73
+ const message = input.scope.checkLocalName(groupsToken.getStr(), undefined);
74
+ if (message !== undefined) {
75
+ input.issues.push((0, _syntax_input_1.syntaxIssue)(input, groupsToken, message));
76
+ return scoped;
77
+ }
72
78
  const type = basic_1.VoidType.get("todoGroupBy");
73
79
  const identifier = new _typed_identifier_1.TypedIdentifier(groupsToken, input.filename, type, ["inline" /* IdentifierMeta.InlineDefinition */]);
74
80
  input.scope.addIdentifier(identifier);
@@ -66,8 +66,8 @@ class InlineFieldDefinition {
66
66
  type = new unknown_type_1.UnknownType("InlineFieldDefinition, fallback");
67
67
  }
68
68
  const name = field.getStr();
69
- if (input.scope.findVariable(name) !== undefined) {
70
- const message = `Variable ${name} already defined`;
69
+ const message = input.scope.checkLocalName(name, type);
70
+ if (message !== undefined) {
71
71
  input.issues.push((0, _syntax_input_1.syntaxIssue)(input, node.getFirstToken(), message));
72
72
  return basic_1.VoidType.get(_syntax_input_1.CheckSyntaxKey);
73
73
  }
@@ -74,6 +74,11 @@ class InlineLoopDefinition {
74
74
  input.issues.push((0, _syntax_input_1.syntaxIssue)(input, node.getFirstToken(), message));
75
75
  return;
76
76
  }
77
+ const message = input.scope.checkLocalName(target.getFirstToken().getStr(), rowType);
78
+ if (message !== undefined) {
79
+ input.issues.push((0, _syntax_input_1.syntaxIssue)(input, target.getFirstToken(), message));
80
+ return;
81
+ }
77
82
  const identifier = new _typed_identifier_1.TypedIdentifier(target.getFirstToken(), input.filename, rowType, ["inline" /* IdentifierMeta.InlineDefinition */]);
78
83
  input.scope.addReference(target.getFirstToken(), identifier, _reference_1.ReferenceType.DataWriteReference, input.filename);
79
84
  input.scope.addReference(target.getFirstToken(), identifier, _reference_1.ReferenceType.DataReadReference, input.filename);
@@ -81,6 +86,11 @@ class InlineLoopDefinition {
81
86
  }
82
87
  const index = node.findExpressionAfterToken("INTO");
83
88
  if (index && index.get() instanceof Expressions.TargetField) {
89
+ const message = input.scope.checkLocalName(index.getFirstToken().getStr(), basic_1.IntegerType.get());
90
+ if (message !== undefined) {
91
+ input.issues.push((0, _syntax_input_1.syntaxIssue)(input, index.getFirstToken(), message));
92
+ return;
93
+ }
84
94
  const identifier = new _typed_identifier_1.TypedIdentifier(index.getFirstToken(), input.filename, basic_1.IntegerType.get(), ["inline" /* IdentifierMeta.InlineDefinition */]);
85
95
  input.scope.addReference(index.getFirstToken(), identifier, _reference_1.ReferenceType.DataWriteReference, input.filename);
86
96
  input.scope.addIdentifier(identifier);
@@ -78,7 +78,7 @@ class Registry {
78
78
  }
79
79
  static abaplintVersion() {
80
80
  // magic, see build script "version.js"
81
- return "2.120.108";
81
+ return "2.120.110";
82
82
  }
83
83
  getDDICReferences() {
84
84
  return this.ddicReferences;
@@ -0,0 +1,264 @@
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.CharacterFieldLiteralBlanks = exports.CharacterFieldLiteralBlanksConf = void 0;
37
+ const Statements = __importStar(require("../abap/2_statements/statements"));
38
+ const Expressions = __importStar(require("../abap/2_statements/expressions"));
39
+ const issue_1 = require("../issue");
40
+ const _basic_rule_config_1 = require("./_basic_rule_config");
41
+ const _abap_rule_1 = require("./_abap_rule");
42
+ const _irule_1 = require("./_irule");
43
+ const nodes_1 = require("../abap/nodes");
44
+ const edit_helper_1 = require("../edit_helper");
45
+ const severity_1 = require("../severity");
46
+ class CharacterFieldLiteralBlanksConf extends _basic_rule_config_1.BasicRuleConfig {
47
+ constructor() {
48
+ super(...arguments);
49
+ this.severity = severity_1.Severity.Warning;
50
+ /** Report a FIND or REPLACE search pattern that is a character field literal containing only blanks, or space,
51
+ * the pattern is empty: ALL OCCURRENCES raises an exception, FIRST OCCURRENCE matches before the first character */
52
+ this.searchPattern = true;
53
+ /** Report a character field literal ending with a blank as an operand of &&, of CONCATENATE without
54
+ * RESPECTING BLANKS, or as an embedded expression in a string template, the trailing blanks are dropped */
55
+ this.concatenation = true;
56
+ }
57
+ }
58
+ exports.CharacterFieldLiteralBlanksConf = CharacterFieldLiteralBlanksConf;
59
+ class CharacterFieldLiteralBlanks extends _abap_rule_1.ABAPRule {
60
+ constructor() {
61
+ super(...arguments);
62
+ this.conf = new CharacterFieldLiteralBlanksConf();
63
+ }
64
+ getMetadata() {
65
+ return {
66
+ key: "character_field_literal_blanks",
67
+ title: "Ignored blanks in character field literals",
68
+ shortDescription: `Reports character field literals ('...') whose blanks are ignored where the code relies on them`,
69
+ extendedInformation: `A character field literal '...' (called text field literal in the ABAP
70
+ documentation) has type c, and trailing blanks of type c operands are ignored in many positions.
71
+ A text string literal \`...\` has type string and keeps them.
72
+
73
+ Option searchPattern: a FIND or REPLACE search pattern (SUBSTRING, character mode) that is a character field
74
+ literal containing only blanks, '' or space. The pattern is empty: FIND/REPLACE ALL OCCURRENCES raises
75
+ CX_SY_FIND_INFINITE_LOOP/CX_SY_REPLACE_INFINITE_LOOP, the first occurrence is found before the first character.
76
+ https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/abapfind_pattern.htm
77
+
78
+ Option concatenation: a character field literal ending with a blank as an operand of &&, as an operand of
79
+ CONCATENATE without RESPECTING BLANKS, or as the whole embedded expression of a string template without
80
+ formatting options. The trailing blanks are dropped, 'Hello ' && name gives "HelloJohn". space is reported
81
+ the same way.
82
+ https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/abenstring_operators.htm
83
+
84
+ The quick fix replaces the literal with a text string literal with the same content.
85
+
86
+ Not reported: text string literals, CONCATENATE ... RESPECTING BLANKS, the separator of SEPARATED BY
87
+ (its trailing blanks are kept), the literal operator &, literals with a text symbol, PCRE and REGEX
88
+ patterns, byte mode, comparisons and parameters.`,
89
+ tags: [_irule_1.RuleTag.SingleFile, _irule_1.RuleTag.Quickfix],
90
+ badExample: `REPLACE ALL OCCURRENCES OF ' ' IN lv_text WITH ''.
91
+ lv_text = 'Hello ' && lv_name.`,
92
+ goodExample: `REPLACE ALL OCCURRENCES OF \` \` IN lv_text WITH ''.
93
+ lv_text = \`Hello \` && lv_name.`,
94
+ };
95
+ }
96
+ getConfig() {
97
+ return this.conf;
98
+ }
99
+ setConfig(conf) {
100
+ this.conf = conf;
101
+ }
102
+ runParsed(file) {
103
+ const issues = [];
104
+ for (const statement of file.getStatements()) {
105
+ if (this.conf.searchPattern === true) {
106
+ const issue = this.checkSearchPattern(file, statement);
107
+ if (issue !== undefined) {
108
+ issues.push(issue);
109
+ }
110
+ }
111
+ if (this.conf.concatenation === true) {
112
+ issues.push(...this.checkConcatenation(file, statement));
113
+ }
114
+ }
115
+ return issues;
116
+ }
117
+ ////////////////
118
+ checkSearchPattern(file, statement) {
119
+ const s = statement.get();
120
+ const isFind = s instanceof Statements.Find;
121
+ if ((isFind === false && !(s instanceof Statements.Replace))
122
+ || statement.findDirectTokenByText("IN") === undefined
123
+ || statement.findDirectTokenByText("BYTE") !== undefined) {
124
+ return undefined;
125
+ }
126
+ const pattern = this.findPattern(statement);
127
+ if (pattern === undefined || pattern.getChildren().length !== 1) {
128
+ return undefined;
129
+ }
130
+ const token = this.blankOperand(pattern);
131
+ if (token === undefined || this.content(token).trim() !== "") {
132
+ return undefined;
133
+ }
134
+ const name = isFind ? "FIND" : "REPLACE";
135
+ const table = statement.findDirectTokenByText("TABLE") !== undefined;
136
+ let effect = "it is found before the first character";
137
+ if (statement.findDirectTokenByText("ALL") !== undefined) {
138
+ effect = isFind && table
139
+ ? "FIND ALL OCCURRENCES IN TABLE with an empty pattern is not possible"
140
+ : `${name} ALL OCCURRENCES raises CX_SY_${name}_INFINITE_LOOP`;
141
+ }
142
+ const message = `Search pattern ${token.getStr()} is empty, blanks of character field literals are ignored, ${effect}`;
143
+ return issue_1.Issue.atToken(file, token, message, this.getMetadata().key, this.conf.severity, this.buildFix(file, token));
144
+ }
145
+ /** the substring pattern of FIND or REPLACE, undefined for PCRE and REGEX and for REPLACE SECTION */
146
+ findPattern(statement) {
147
+ const children = statement.getChildren();
148
+ for (let i = 1; i < children.length; i++) {
149
+ const child = children[i];
150
+ if (child instanceof nodes_1.TokenNode && child.concatTokens().toUpperCase() === "IN") {
151
+ return undefined;
152
+ }
153
+ else if (!(child instanceof nodes_1.ExpressionNode) || !(child.get() instanceof Expressions.Source)) {
154
+ continue;
155
+ }
156
+ const before = children[i - 1];
157
+ if (before instanceof nodes_1.ExpressionNode && before.get() instanceof Expressions.FindType) {
158
+ return before.concatTokens().toUpperCase() === "SUBSTRING" ? child : undefined;
159
+ }
160
+ else if (before instanceof nodes_1.TokenNode && CharacterFieldLiteralBlanks.beforePattern.has(before.concatTokens().toUpperCase())) {
161
+ return child;
162
+ }
163
+ }
164
+ return undefined;
165
+ }
166
+ checkConcatenation(file, statement) {
167
+ const operands = [];
168
+ const sources = statement.findAllExpressionsRecursive(Expressions.Source);
169
+ // left operands of &&
170
+ for (const source of sources) {
171
+ if (source.findDirectTokenByText("&&") !== undefined) {
172
+ operands.push(source);
173
+ }
174
+ }
175
+ // right operands of && and &&=
176
+ for (const node of [statement, ...sources]) {
177
+ const children = node.getChildren();
178
+ for (let i = 1; i < children.length; i++) {
179
+ const before = children[i - 1].concatTokens();
180
+ const child = children[i];
181
+ if ((before === "&&" || before === "&&=")
182
+ && child instanceof nodes_1.ExpressionNode
183
+ && child.get() instanceof Expressions.Source) {
184
+ operands.push(child);
185
+ }
186
+ }
187
+ }
188
+ // embedded expressions without formatting options
189
+ for (const embedded of statement.findAllExpressionsRecursive(Expressions.StringTemplateSource)) {
190
+ const source = embedded.findDirectExpression(Expressions.Source);
191
+ if (source !== undefined
192
+ && source.getChildren().length === 1
193
+ && embedded.findDirectExpression(Expressions.StringTemplateFormatting) === undefined) {
194
+ operands.push(source);
195
+ }
196
+ }
197
+ // CONCATENATE without RESPECTING BLANKS, the separator keeps its blanks
198
+ if (statement.get() instanceof Statements.Concatenate
199
+ && statement.findDirectTokenByText("RESPECTING") === undefined
200
+ && statement.findDirectTokenByText("BYTE") === undefined) {
201
+ for (const child of statement.getChildren()) {
202
+ if (child instanceof nodes_1.TokenNode && child.concatTokens().toUpperCase() === "INTO") {
203
+ break;
204
+ }
205
+ else if (child instanceof nodes_1.ExpressionNode && child.get() instanceof Expressions.SimpleSource3) {
206
+ operands.push(child);
207
+ }
208
+ }
209
+ }
210
+ const issues = [];
211
+ const reported = new Set();
212
+ for (const operand of operands) {
213
+ const token = this.blankOperand(operand);
214
+ if (token === undefined || reported.has(token)) {
215
+ continue;
216
+ }
217
+ const content = this.content(token);
218
+ if (content === "" || content.endsWith(" ") === false) {
219
+ continue;
220
+ }
221
+ reported.add(token);
222
+ const message = token.getStr().startsWith("'")
223
+ ? `Trailing blanks of ${token.getStr()} are ignored here, use a text string literal`
224
+ : `${token.getStr()} is ignored here, use \` \``;
225
+ issues.push(issue_1.Issue.atToken(file, token, message, this.getMetadata().key, this.conf.severity, this.buildFix(file, token)));
226
+ }
227
+ return issues;
228
+ }
229
+ /** the token of a character field literal or of space at the start of the operand */
230
+ blankOperand(operand) {
231
+ var _a;
232
+ const first = operand.getChildren()[0];
233
+ if (!(first instanceof nodes_1.ExpressionNode)) {
234
+ return undefined;
235
+ }
236
+ if (first.get() instanceof Expressions.Constant) {
237
+ const str = (_a = first.findDirectExpression(Expressions.ConstantString)) === null || _a === void 0 ? void 0 : _a.getFirstToken();
238
+ return (str === null || str === void 0 ? void 0 : str.getStr().startsWith("'")) ? str : undefined;
239
+ }
240
+ else if (first.get() instanceof Expressions.FieldChain && first.concatTokens().toUpperCase() === "SPACE") {
241
+ return first.getFirstToken();
242
+ }
243
+ return undefined;
244
+ }
245
+ /** the value of a character field literal, " " for space */
246
+ content(token) {
247
+ const str = token.getStr();
248
+ if (str.startsWith("'") === false) {
249
+ return " ";
250
+ }
251
+ return str.substring(1, str.length - 1).replace(/''/g, "'");
252
+ }
253
+ buildFix(file, token) {
254
+ const content = this.content(token);
255
+ if (content === "") {
256
+ return undefined;
257
+ }
258
+ return edit_helper_1.EditHelper.replaceToken(file, token, "`" + content.replace(/`/g, "``") + "`");
259
+ }
260
+ }
261
+ exports.CharacterFieldLiteralBlanks = CharacterFieldLiteralBlanks;
262
+ // tokens directly before the pattern of FIND and REPLACE, when no FindType is given
263
+ CharacterFieldLiteralBlanks.beforePattern = new Set(["FIND", "REPLACE", "OF", "OCCURRENCE", "OCCURRENCES", "OCCURENCE", "OCCURENCES"]);
264
+ //# sourceMappingURL=character_field_literal_blanks.js.map
@@ -0,0 +1,194 @@
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.FieldSymbolNeverAssigned = exports.FieldSymbolNeverAssignedConf = void 0;
37
+ const Statements = __importStar(require("../abap/2_statements/statements"));
38
+ const Expressions = __importStar(require("../abap/2_statements/expressions"));
39
+ const issue_1 = require("../issue");
40
+ const _basic_rule_config_1 = require("./_basic_rule_config");
41
+ const _abap_rule_1 = require("./_abap_rule");
42
+ const _irule_1 = require("./_irule");
43
+ const token_node_1 = require("../abap/nodes/token_node");
44
+ const _statement_1 = require("../abap/2_statements/statements/_statement");
45
+ class FieldSymbolNeverAssignedConf extends _basic_rule_config_1.BasicRuleConfig {
46
+ }
47
+ exports.FieldSymbolNeverAssignedConf = FieldSymbolNeverAssignedConf;
48
+ class FieldSymbolNeverAssigned extends _abap_rule_1.ABAPRule {
49
+ constructor() {
50
+ super(...arguments);
51
+ this.conf = new FieldSymbolNeverAssignedConf();
52
+ }
53
+ getMetadata() {
54
+ return {
55
+ key: "field_symbol_never_assigned",
56
+ title: "Field symbol never assigned",
57
+ shortDescription: `Reports a local field symbol that is used, but never assigned in its method, form or function module`,
58
+ extendedInformation: `A field symbol declared with FIELD-SYMBOLS in a method, form or function module can only be
59
+ assigned in that procedure. If no ASSIGN ... TO <fs> or ... ASSIGNING <fs> of it exists there,
60
+ reading or writing it raises the runtime error GETWA_NOT_ASSIGNED. This is typically a copy-paste
61
+ error, where a statement uses a field symbol other than the one assigned before it.
62
+
63
+ Assignments are ASSIGN, ASSIGN LOCAL COPY, and ASSIGNING of LOOP, READ TABLE, INSERT, APPEND,
64
+ MODIFY and COLLECT, anywhere in the procedure. The order of the statements is not checked.
65
+
66
+ Not reported: field symbols only used in IS [NOT] ASSIGNED or UNASSIGN, field symbols declared
67
+ with DEFAULT, inline declarations, global field symbols, and procedures that contain a macro
68
+ call, an INCLUDE or a statement that cannot be parsed.`,
69
+ tags: [_irule_1.RuleTag.SingleFile],
70
+ badExample: `FIELD-SYMBOLS <type> TYPE ty_type.
71
+ FIELD-SYMBOLS <attr> TYPE ty_attr.
72
+ LOOP AT types ASSIGNING <type>.
73
+ CLEAR <attr>-author.
74
+ ENDLOOP.`,
75
+ goodExample: `FIELD-SYMBOLS <type> TYPE ty_type.
76
+ LOOP AT types ASSIGNING <type>.
77
+ CLEAR <type>-author.
78
+ ENDLOOP.`,
79
+ };
80
+ }
81
+ getConfig() {
82
+ return this.conf;
83
+ }
84
+ setConfig(conf) {
85
+ this.conf = conf;
86
+ }
87
+ runParsed(file) {
88
+ const issues = [];
89
+ const statements = file.getStatements();
90
+ let start = undefined;
91
+ for (let i = 0; i < statements.length; i++) {
92
+ const s = statements[i].get();
93
+ if (s instanceof Statements.MethodImplementation
94
+ || s instanceof Statements.Form
95
+ || s instanceof Statements.FunctionModule) {
96
+ start = i;
97
+ }
98
+ else if (start !== undefined
99
+ && (s instanceof Statements.EndMethod
100
+ || s instanceof Statements.EndForm
101
+ || s instanceof Statements.EndFunction)) {
102
+ issues.push(...this.checkProcedure(file, statements.slice(start, i + 1)));
103
+ start = undefined;
104
+ }
105
+ }
106
+ return issues;
107
+ }
108
+ ////////////////
109
+ checkProcedure(file, statements) {
110
+ var _a;
111
+ const declared = new Map();
112
+ const assigned = new Set();
113
+ const used = new Map();
114
+ for (const statement of statements) {
115
+ const s = statement.get();
116
+ if (s instanceof _statement_1.Unknown
117
+ || s instanceof _statement_1.MacroCall
118
+ || s instanceof Statements.Include) {
119
+ return [];
120
+ }
121
+ else if (s instanceof Statements.FieldSymbol) {
122
+ const name = (_a = statement.findDirectExpression(Expressions.FieldSymbol)) === null || _a === void 0 ? void 0 : _a.concatTokens();
123
+ if (name !== undefined && statement.findDirectTokenByText("DEFAULT") === undefined) {
124
+ declared.set(name.toUpperCase(), name);
125
+ }
126
+ continue;
127
+ }
128
+ else if (s instanceof Statements.Unassign) {
129
+ continue;
130
+ }
131
+ this.walk(statement, assigned, used);
132
+ }
133
+ const issues = [];
134
+ const procedure = this.procedureName(statements[0]);
135
+ for (const [upper, name] of declared) {
136
+ const token = used.get(upper);
137
+ if (token === undefined || assigned.has(upper)) {
138
+ continue;
139
+ }
140
+ const message = `Field symbol ${name} is never assigned in this ${procedure}`;
141
+ issues.push(issue_1.Issue.atToken(file, token, message, this.getMetadata().key, this.conf.severity));
142
+ }
143
+ return issues;
144
+ }
145
+ /** collects the assigned field symbols, and the first use of each other field symbol */
146
+ walk(node, assigned, used) {
147
+ var _a;
148
+ for (const child of node.getChildren()) {
149
+ if (child instanceof token_node_1.TokenNode) {
150
+ continue;
151
+ }
152
+ const e = child.get();
153
+ if (e instanceof Expressions.FSTarget
154
+ || e instanceof Expressions.InlineFS
155
+ || (e instanceof Expressions.TargetFieldSymbol && this.isBinding(node))) {
156
+ const name = (_a = child.findFirstExpression(Expressions.FieldSymbol)) === null || _a === void 0 ? void 0 : _a.concatTokens();
157
+ if (name !== undefined) {
158
+ assigned.add(name.toUpperCase());
159
+ }
160
+ }
161
+ else if (e instanceof Expressions.Compare && child.findDirectTokenByText("ASSIGNED") !== undefined) {
162
+ continue;
163
+ }
164
+ else if (e instanceof Expressions.FieldSymbol) {
165
+ const upper = child.concatTokens().toUpperCase();
166
+ if (used.has(upper) === false) {
167
+ used.set(upper, child.getFirstToken());
168
+ }
169
+ }
170
+ else {
171
+ this.walk(child, assigned, used);
172
+ }
173
+ }
174
+ }
175
+ /** TargetFieldSymbol directly in these binds the field symbol, elsewhere it is a write to the assigned data */
176
+ isBinding(parent) {
177
+ const p = parent.get();
178
+ return p instanceof Statements.AssignLocalCopy
179
+ || p instanceof Expressions.For
180
+ || p instanceof Expressions.InlineLoopDefinition;
181
+ }
182
+ procedureName(statement) {
183
+ const s = statement.get();
184
+ if (s instanceof Statements.Form) {
185
+ return "form";
186
+ }
187
+ else if (s instanceof Statements.FunctionModule) {
188
+ return "function module";
189
+ }
190
+ return "method";
191
+ }
192
+ }
193
+ exports.FieldSymbolNeverAssigned = FieldSymbolNeverAssigned;
194
+ //# sourceMappingURL=field_symbol_never_assigned.js.map