@abaplint/core 2.120.108 → 2.120.109

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.
@@ -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.109";
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
@@ -50,6 +50,7 @@ __exportStar(require("./cds_parser_error"), exports);
50
50
  __exportStar(require("./chain_mainly_declarations"), exports);
51
51
  __exportStar(require("./change_if_to_case"), exports);
52
52
  __exportStar(require("./changing_sorted_line"), exports);
53
+ __exportStar(require("./character_field_literal_blanks"), exports);
53
54
  __exportStar(require("./check_abstract"), exports);
54
55
  __exportStar(require("./check_comments"), exports);
55
56
  __exportStar(require("./check_ddic"), exports);
@@ -91,6 +92,7 @@ __exportStar(require("./else_after_all_returns"), exports);
91
92
  __exportStar(require("./exit_or_check"), exports);
92
93
  __exportStar(require("./expand_macros"), exports);
93
94
  __exportStar(require("./exporting"), exports);
95
+ __exportStar(require("./field_symbol_never_assigned"), exports);
94
96
  __exportStar(require("./final_newline"), exports);
95
97
  __exportStar(require("./fm_global_parameters_obsolete"), exports);
96
98
  __exportStar(require("./forbidden_identifier"), exports);
@@ -130,6 +132,7 @@ __exportStar(require("./line_only_punc"), exports);
130
132
  __exportStar(require("./local_class_naming"), exports);
131
133
  __exportStar(require("./local_testclass_consistency"), exports);
132
134
  __exportStar(require("./local_variable_names"), exports);
135
+ __exportStar(require("./loop_target_misuse"), exports);
133
136
  __exportStar(require("./macro_naming"), exports);
134
137
  __exportStar(require("./main_file_contents"), exports);
135
138
  __exportStar(require("./many_parentheses"), exports);
@@ -209,6 +212,7 @@ __exportStar(require("./space_before_colon"), exports);
209
212
  __exportStar(require("./space_before_dot"), exports);
210
213
  __exportStar(require("./sql_escape_host_variables"), exports);
211
214
  __exportStar(require("./sql_value_conversion"), exports);
215
+ __exportStar(require("./stale_subrc"), exports);
212
216
  __exportStar(require("./start_at_tab"), exports);
213
217
  __exportStar(require("./static_call_via_instance"), exports);
214
218
  __exportStar(require("./strict_sql"), exports);
@@ -224,6 +228,7 @@ __exportStar(require("./try_without_catch"), exports);
224
228
  __exportStar(require("./type_form_parameters"), exports);
225
229
  __exportStar(require("./types_naming"), exports);
226
230
  __exportStar(require("./uncaught_exception"), exports);
231
+ __exportStar(require("./unit_test_assertions"), exports);
227
232
  __exportStar(require("./unknown_types"), exports);
228
233
  __exportStar(require("./unnecessary_chaining"), exports);
229
234
  __exportStar(require("./unnecessary_copy"), exports);
@@ -0,0 +1,301 @@
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.LoopTargetMisuse = exports.LoopTargetMisuseConf = 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
+ class LoopTargetMisuseConf extends _basic_rule_config_1.BasicRuleConfig {
44
+ constructor() {
45
+ super(...arguments);
46
+ /** Report a LOOP inside a LOOP with the same target, when the outer loop body uses the target after the inner ENDLOOP */
47
+ this.nestedLoop = true;
48
+ /** Report LOOP AT ... INTO <fs> and READ TABLE ... INTO <fs> when the local field symbol is only bound by ASSIGNING,
49
+ * so the statement overwrites a table row */
50
+ this.intoFieldSymbol = true;
51
+ }
52
+ }
53
+ exports.LoopTargetMisuseConf = LoopTargetMisuseConf;
54
+ class LoopTargetMisuse extends _abap_rule_1.ABAPRule {
55
+ constructor() {
56
+ super(...arguments);
57
+ this.conf = new LoopTargetMisuseConf();
58
+ }
59
+ getMetadata() {
60
+ return {
61
+ key: "loop_target_misuse",
62
+ title: "LOOP and READ TABLE targets used wrongly",
63
+ shortDescription: `Reports a nested LOOP that reuses the target of the enclosing LOOP, and INTO <fs> where ASSIGNING was meant`,
64
+ extendedInformation: `Option nestedLoop: a LOOP inside a LOOP with the same INTO, REFERENCE INTO or ASSIGNING target.
65
+ After the inner ENDLOOP, the target holds the last row of the inner table, not the row of the
66
+ outer loop. Reported when the outer loop body uses the target after the inner ENDLOOP, before
67
+ it is assigned again.
68
+ Not reported: a target of a loop that has already ended, a target that is not a plain variable
69
+ or field symbol, an enclosing LOOP with GROUP BY, and a target the outer loop body does not use
70
+ after the inner loop.
71
+
72
+ Option intoFieldSymbol: LOOP AT ... INTO <fs> or READ TABLE ... INTO <fs>. INTO copies the row
73
+ into the data object the field symbol points to. When <fs> was bound by ASSIGNING, that data
74
+ object is a row of a table, and the statement overwrites it. ASSIGNING was meant.
75
+ Reported only for a field symbol declared in the method, form or function module, and only when
76
+ no ASSIGN and no STRUCTURE ... DEFAULT binds it there, so it can only point to a table row.`,
77
+ tags: [_irule_1.RuleTag.SingleFile],
78
+ badExample: `LOOP AT lt_header INTO ls_row.
79
+ LOOP AT lt_items INTO ls_row WHERE parent = ls_row-id.
80
+ lv_sum = lv_sum + ls_row-amount.
81
+ ENDLOOP.
82
+ ls_row-amount = lv_sum.
83
+ APPEND ls_row TO lt_result.
84
+ ENDLOOP.
85
+
86
+ LOOP AT lt_a ASSIGNING <ls_a>.
87
+ ENDLOOP.
88
+ READ TABLE lt_a INTO <ls_a> INDEX 1.`,
89
+ goodExample: `LOOP AT lt_header INTO ls_row.
90
+ LOOP AT lt_items INTO ls_item WHERE parent = ls_row-id.
91
+ lv_sum = lv_sum + ls_item-amount.
92
+ ENDLOOP.
93
+ ls_row-amount = lv_sum.
94
+ APPEND ls_row TO lt_result.
95
+ ENDLOOP.
96
+
97
+ LOOP AT lt_a ASSIGNING <ls_a>.
98
+ ENDLOOP.
99
+ READ TABLE lt_a ASSIGNING <ls_a> INDEX 1.`,
100
+ };
101
+ }
102
+ getConfig() {
103
+ return this.conf;
104
+ }
105
+ setConfig(conf) {
106
+ this.conf = conf;
107
+ }
108
+ runParsed(file) {
109
+ const issues = [];
110
+ const statements = file.getStatements();
111
+ if (this.conf.nestedLoop !== false) {
112
+ issues.push(...this.checkNestedLoop(file, statements));
113
+ }
114
+ if (this.conf.intoFieldSymbol !== false) {
115
+ issues.push(...this.checkIntoFieldSymbol(file, statements));
116
+ }
117
+ return issues;
118
+ }
119
+ ////////////////
120
+ checkNestedLoop(file, statements) {
121
+ const issues = [];
122
+ // one entry per open LOOP, key undefined when the LOOP has no target to compare
123
+ let open = [];
124
+ for (let i = 0; i < statements.length; i++) {
125
+ const statement = statements[i];
126
+ const s = statement.get();
127
+ if (this.isBlockBoundary(statement)) {
128
+ open = [];
129
+ }
130
+ else if (s instanceof Statements.EndLoop) {
131
+ open.pop();
132
+ }
133
+ else if (s instanceof Statements.Loop) {
134
+ const node = this.loopTarget(statement);
135
+ const target = node ? this.targetName(node) : undefined;
136
+ // INTO <fs> inside LOOP ... ASSIGNING <fs> is left to the option intoFieldSymbol
137
+ const key = target === undefined ? undefined : ((node === null || node === void 0 ? void 0 : node.get()) instanceof Expressions.Target ? "INTO " : "ASSIGNING ") + target;
138
+ const outer = key === undefined ? undefined : [...open].reverse().find(o => o.key === key);
139
+ if (node !== undefined && target !== undefined && outer !== undefined) {
140
+ const innerEnd = this.findEndLoop(statements, i);
141
+ const outerEnd = this.findEndLoop(statements, outer.index);
142
+ if (innerEnd !== undefined && outerEnd !== undefined && this.usedBetween(statements, innerEnd + 1, outerEnd, target)) {
143
+ const name = node.concatTokens();
144
+ const message = `Inner LOOP reuses ${name}, the target of the enclosing LOOP, `
145
+ + `which is used after the inner ENDLOOP and then holds a row of the inner table`;
146
+ issues.push(issue_1.Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity));
147
+ }
148
+ }
149
+ const grouped = statement.findDirectExpression(Expressions.LoopGroupBy) !== undefined;
150
+ open.push({ index: i, key: grouped ? undefined : key });
151
+ }
152
+ }
153
+ return issues;
154
+ }
155
+ /** the Target or FSTarget after INTO, REFERENCE INTO or ASSIGNING of a LOOP */
156
+ loopTarget(statement) {
157
+ const target = statement.findDirectExpression(Expressions.LoopTarget);
158
+ return (target === null || target === void 0 ? void 0 : target.findDirectExpression(Expressions.Target)) || (target === null || target === void 0 ? void 0 : target.findDirectExpression(Expressions.FSTarget));
159
+ }
160
+ /** upper case name of a Target or FSTarget that is a plain variable or field symbol, also declared inline */
161
+ targetName(node) {
162
+ var _a, _b;
163
+ const inline = ((_a = node.findDirectExpression(Expressions.InlineData)) === null || _a === void 0 ? void 0 : _a.findDirectExpression(Expressions.TargetField))
164
+ || ((_b = node.findDirectExpression(Expressions.InlineFS)) === null || _b === void 0 ? void 0 : _b.findDirectExpression(Expressions.TargetFieldSymbol));
165
+ const tokens = (inline || node).getAllTokens();
166
+ return tokens.length === 1 ? tokens[0].getStr().toUpperCase() : undefined;
167
+ }
168
+ /** index of the ENDLOOP that closes the LOOP at the index */
169
+ findEndLoop(statements, index) {
170
+ let depth = 0;
171
+ for (let i = index + 1; i < statements.length && this.isBlockBoundary(statements[i]) === false; i++) {
172
+ const s = statements[i].get();
173
+ if (s instanceof Statements.Loop) {
174
+ depth++;
175
+ }
176
+ else if (s instanceof Statements.EndLoop) {
177
+ if (depth === 0) {
178
+ return i;
179
+ }
180
+ depth--;
181
+ }
182
+ }
183
+ return undefined;
184
+ }
185
+ /** true when a statement in [from, to) uses the variable before a statement assigns all of it */
186
+ usedBetween(statements, from, to, name) {
187
+ for (let i = from; i < to; i++) {
188
+ const statement = statements[i];
189
+ const s = statement.get();
190
+ if (s instanceof Statements.Data || s instanceof Statements.FieldSymbol) {
191
+ continue;
192
+ }
193
+ const whole = new Set();
194
+ for (const t of [...statement.findAllExpressions(Expressions.Target), ...statement.findAllExpressions(Expressions.FSTarget)]) {
195
+ if (this.targetName(t) === name) {
196
+ t.getAllTokens().forEach(token => whole.add(token));
197
+ }
198
+ }
199
+ const tokens = statement.getTokens();
200
+ for (let j = 0; j < tokens.length; j++) {
201
+ const previous = j > 0 ? tokens[j - 1].getStr() : "";
202
+ if (tokens[j].getStr().toUpperCase() === name
203
+ && whole.has(tokens[j]) === false
204
+ && ["-", "->", "=>", "~"].includes(previous) === false) {
205
+ return s instanceof Statements.Unassign ? false : true;
206
+ }
207
+ }
208
+ if (whole.size > 0) {
209
+ return false;
210
+ }
211
+ }
212
+ return false;
213
+ }
214
+ checkIntoFieldSymbol(file, statements) {
215
+ const issues = [];
216
+ for (let i = 0; i < statements.length; i++) {
217
+ const statement = statements[i];
218
+ const s = statement.get();
219
+ if (!(s instanceof Statements.Loop) && !(s instanceof Statements.ReadTable)) {
220
+ continue;
221
+ }
222
+ const target = statement.findDirectExpression(Expressions.LoopTarget)
223
+ || statement.findDirectExpression(Expressions.ReadTableTarget);
224
+ const into = target === null || target === void 0 ? void 0 : target.findDirectExpression(Expressions.Target);
225
+ const fs = into === null || into === void 0 ? void 0 : into.findDirectExpression(Expressions.TargetFieldSymbol);
226
+ if (into === undefined || fs === undefined || fs.concatTokens() !== into.concatTokens()) {
227
+ continue;
228
+ }
229
+ const name = fs.concatTokens().toUpperCase();
230
+ if (this.onlyBoundToRows(statements, i, name) === false) {
231
+ continue;
232
+ }
233
+ const what = s instanceof Statements.Loop ? "LOOP AT" : "READ TABLE";
234
+ const message = `${what} ... INTO ${fs.concatTokens()} overwrites the row the field symbol points to, use ASSIGNING`;
235
+ issues.push(issue_1.Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity));
236
+ }
237
+ return issues;
238
+ }
239
+ /** true when the field symbol is declared in the block around the statement and every binding of it
240
+ * in that block is an ASSIGNING, so it can only point to a table row */
241
+ onlyBoundToRows(statements, index, name) {
242
+ var _a;
243
+ let start = index;
244
+ while (start > 0 && this.isBlockBoundary(statements[start]) === false) {
245
+ start--;
246
+ }
247
+ if (this.startsBlock(statements[start]) === false) {
248
+ return false;
249
+ }
250
+ let declared = false;
251
+ let assigning = false;
252
+ for (let i = start + 1; i < statements.length && this.endsBlock(statements[i]) === false; i++) {
253
+ const statement = statements[i];
254
+ if (statement.get() instanceof Statements.FieldSymbol) {
255
+ if (((_a = statement.findDirectExpression(Expressions.FieldSymbol)) === null || _a === void 0 ? void 0 : _a.concatTokens().toUpperCase()) === name) {
256
+ if (statement.findDirectTokenByText("DEFAULT") !== undefined) {
257
+ return false;
258
+ }
259
+ declared = true;
260
+ }
261
+ continue;
262
+ }
263
+ for (const fsTarget of statement.findAllExpressions(Expressions.FSTarget)) {
264
+ if (this.fsName(fsTarget) !== name) {
265
+ continue;
266
+ }
267
+ if (statement.get() instanceof Statements.Assign) {
268
+ return false;
269
+ }
270
+ assigning = true;
271
+ if (fsTarget.findDirectExpression(Expressions.InlineFS) !== undefined) {
272
+ declared = true;
273
+ }
274
+ }
275
+ }
276
+ return declared && assigning;
277
+ }
278
+ fsName(fsTarget) {
279
+ var _a;
280
+ return (_a = fsTarget.findFirstExpression(Expressions.FieldSymbol)) === null || _a === void 0 ? void 0 : _a.concatTokens().toUpperCase();
281
+ }
282
+ isBlockBoundary(statement) {
283
+ return this.startsBlock(statement) || this.endsBlock(statement);
284
+ }
285
+ startsBlock(statement) {
286
+ const s = statement.get();
287
+ return s instanceof Statements.MethodImplementation
288
+ || s instanceof Statements.Form
289
+ || s instanceof Statements.FunctionModule
290
+ || s instanceof Statements.Module;
291
+ }
292
+ endsBlock(statement) {
293
+ const s = statement.get();
294
+ return s instanceof Statements.EndMethod
295
+ || s instanceof Statements.EndForm
296
+ || s instanceof Statements.EndFunction
297
+ || s instanceof Statements.EndModule;
298
+ }
299
+ }
300
+ exports.LoopTargetMisuse = LoopTargetMisuse;
301
+ //# sourceMappingURL=loop_target_misuse.js.map
@@ -0,0 +1,176 @@
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.StaleSubrc = exports.StaleSubrcConf = 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 _statement_1 = require("../abap/2_statements/statements/_statement");
44
+ const severity_1 = require("../severity");
45
+ const _builtin_1 = require("../abap/5_syntax/_builtin");
46
+ class StaleSubrcConf extends _basic_rule_config_1.BasicRuleConfig {
47
+ constructor() {
48
+ super(...arguments);
49
+ this.severity = severity_1.Severity.Warning;
50
+ }
51
+ }
52
+ exports.StaleSubrcConf = StaleSubrcConf;
53
+ class StaleSubrc extends _abap_rule_1.ABAPRule {
54
+ constructor() {
55
+ super(...arguments);
56
+ this.conf = new StaleSubrcConf();
57
+ }
58
+ getMetadata() {
59
+ return {
60
+ key: "stale_subrc",
61
+ title: "sy-subrc checked after a method call",
62
+ shortDescription: `Reports IF, CHECK, ASSERT or CASE on sy-subrc directly after a method call without EXCEPTIONS`,
63
+ extendedInformation: `A method call without EXCEPTIONS does not set sy-subrc. After the call, sy-subrc holds whatever
64
+ the last statement inside the method set, so the check depends on the method's implementation
65
+ and breaks silently when the method changes.
66
+
67
+ Check the result of the method instead, eg. a returning parameter or an exception, or move the
68
+ check directly after the statement that sets sy-subrc.
69
+
70
+ Reported: the statement directly before the check is a method call, CALL METHOD, or an
71
+ assignment with a method call or NEW in its source.
72
+
73
+ Not reported: a call with EXCEPTIONS or EXCEPTION-TABLE, an assignment that only calls built-in
74
+ functions like lines( ), and any other statement before the check, eg. CALL FUNCTION or
75
+ CREATE OBJECT, a check that is the first statement of a block, or a check after ENDIF.
76
+ An assignment or CLEAR without a call does not change sy-subrc, so a check after it still
77
+ reads the statement before it, which is not reported either.
78
+ See also check_subrc and subrc_after_assign.`,
79
+ tags: [_irule_1.RuleTag.SingleFile],
80
+ badExample: `lv_parent = read_parent( ).
81
+ IF sy-subrc = 0.
82
+ WRITE lv_parent.
83
+ ENDIF.`,
84
+ goodExample: `lv_parent = read_parent( ).
85
+ IF lv_parent IS NOT INITIAL.
86
+ WRITE lv_parent.
87
+ ENDIF.`,
88
+ };
89
+ }
90
+ getConfig() {
91
+ return this.conf;
92
+ }
93
+ setConfig(conf) {
94
+ this.conf = conf;
95
+ }
96
+ runParsed(file) {
97
+ const issues = [];
98
+ const statements = file.getStatements();
99
+ for (let i = 0; i < statements.length; i++) {
100
+ const statement = statements[i];
101
+ if (this.isSubrcCheck(statement) === false) {
102
+ continue;
103
+ }
104
+ const previous = this.previousStatement(i, statements);
105
+ if (previous === undefined || this.isCallWithoutExceptions(previous) === false) {
106
+ continue;
107
+ }
108
+ const message = "sy-subrc checked after a method call without EXCEPTIONS, the call does not set sy-subrc";
109
+ issues.push(issue_1.Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity));
110
+ }
111
+ return issues;
112
+ }
113
+ ////////////////
114
+ isSubrcCheck(statement) {
115
+ const s = statement.get();
116
+ if (!(s instanceof Statements.If
117
+ || s instanceof Statements.Check
118
+ || s instanceof Statements.Assert
119
+ || s instanceof Statements.Case)) {
120
+ return false;
121
+ }
122
+ return this.readsSubrc(statement);
123
+ }
124
+ readsSubrc(statement) {
125
+ for (const field of statement.findAllExpressions(Expressions.FieldChain)) {
126
+ if (field.concatTokens().toUpperCase() === "SY-SUBRC") {
127
+ return true;
128
+ }
129
+ }
130
+ return false;
131
+ }
132
+ /** the statement directly before, skipping comments */
133
+ previousStatement(index, statements) {
134
+ for (let i = index - 1; i >= 0; i--) {
135
+ if (statements[i].get() instanceof _statement_1.Comment) {
136
+ continue;
137
+ }
138
+ return statements[i];
139
+ }
140
+ return undefined;
141
+ }
142
+ /** a standalone method call, or an assignment with a method call or NEW in its source */
143
+ isCallWithoutExceptions(statement) {
144
+ const s = statement.get();
145
+ if (s instanceof Statements.Call) {
146
+ return this.hasClassicExceptions(statement) === false;
147
+ }
148
+ else if (!(s instanceof Statements.Move) || this.hasClassicExceptions(statement) === true) {
149
+ return false;
150
+ }
151
+ if (statement.findFirstExpression(Expressions.NewObject) !== undefined) {
152
+ return true;
153
+ }
154
+ const tokens = statement.getTokens();
155
+ for (const call of statement.findAllExpressions(Expressions.MethodCall)) {
156
+ const name = call.getFirstToken();
157
+ const index = tokens.indexOf(name);
158
+ const before = index > 0 ? tokens[index - 1].getStr() : "";
159
+ if (before === "->" || before === "=>" || _builtin_1.BuiltIn.methods[name.getStr().toUpperCase()] === undefined) {
160
+ return true;
161
+ }
162
+ }
163
+ return false;
164
+ }
165
+ hasClassicExceptions(statement) {
166
+ for (const token of statement.getTokens()) {
167
+ const str = token.getStr().toUpperCase();
168
+ if (str === "EXCEPTIONS" || str === "EXCEPTION-TABLE") {
169
+ return true;
170
+ }
171
+ }
172
+ return false;
173
+ }
174
+ }
175
+ exports.StaleSubrc = StaleSubrc;
176
+ //# sourceMappingURL=stale_subrc.js.map
@@ -0,0 +1,263 @@
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.UnitTestAssertions = exports.UnitTestAssertionsConf = void 0;
37
+ const Statements = __importStar(require("../abap/2_statements/statements"));
38
+ const Expressions = __importStar(require("../abap/2_statements/expressions"));
39
+ const Structures = __importStar(require("../abap/3_structures/structures"));
40
+ const issue_1 = require("../issue");
41
+ const _basic_rule_config_1 = require("./_basic_rule_config");
42
+ const _abap_rule_1 = require("./_abap_rule");
43
+ const Tokens = __importStar(require("../abap/1_lexer/tokens"));
44
+ const severity_1 = require("../severity");
45
+ class UnitTestAssertionsConf extends _basic_rule_config_1.BasicRuleConfig {
46
+ constructor() {
47
+ super(...arguments);
48
+ this.severity = severity_1.Severity.Warning;
49
+ /** Report assertions that cannot fail: assert_equals or assert_equals_float with the same operand for act and exp,
50
+ * assert_true with abap_true or 'X', assert_false with abap_false, space or ' ' */
51
+ this.cannotFail = true;
52
+ /** Report the ASSERT statement in FOR TESTING classes */
53
+ this.assertStatement = true;
54
+ }
55
+ }
56
+ exports.UnitTestAssertionsConf = UnitTestAssertionsConf;
57
+ const ASSERT_CLASSES = ["CL_ABAP_UNIT_ASSERT", "CL_AUNIT_ASSERT"];
58
+ class UnitTestAssertions extends _abap_rule_1.ABAPRule {
59
+ constructor() {
60
+ super(...arguments);
61
+ this.conf = new UnitTestAssertionsConf();
62
+ }
63
+ getMetadata() {
64
+ return {
65
+ key: "unit_test_assertions",
66
+ title: "Unit test assertions",
67
+ shortDescription: `Reports unit test assertions that cannot fail, and the ASSERT statement in FOR TESTING classes`,
68
+ extendedInformation: `Only code in FOR TESTING classes is checked. Each check has its own option.
69
+
70
+ cannotFail: an assertion of cl_abap_unit_assert or cl_aunit_assert that passes whatever the code under test does.
71
+ assert_equals and assert_equals_float with the same operand for act and exp, assert_true with abap_true or 'X',
72
+ assert_false with abap_false, space or ' '. Not reported: operands that contain a method call or NEW, as two calls
73
+ can return different values; two different literals or constants; assertions that always fail.
74
+
75
+ assertStatement: the ASSERT statement. A failing ASSERT ends in the runtime error ASSERTION_FAILED, so the test
76
+ run shows a short dump instead of a failed test with act, exp and a message. Use cl_abap_unit_assert instead.
77
+ Not reported: ASSERT in classes that are not FOR TESTING.`,
78
+ tags: [],
79
+ badExample: `CLASS ltcl_test DEFINITION FINAL FOR TESTING DURATION SHORT RISK LEVEL HARMLESS.
80
+ PRIVATE SECTION.
81
+ DATA mt_rows TYPE string_table.
82
+ METHODS test FOR TESTING.
83
+ ENDCLASS.
84
+
85
+ CLASS ltcl_test IMPLEMENTATION.
86
+ METHOD test.
87
+ DATA(lv_count) = lines( mt_rows ).
88
+ cl_abap_unit_assert=>assert_equals( act = lv_count exp = lv_count ).
89
+ cl_abap_unit_assert=>assert_true( abap_true ).
90
+ ASSERT lv_count = 2.
91
+ ENDMETHOD.
92
+ ENDCLASS.`,
93
+ goodExample: `CLASS ltcl_test DEFINITION FINAL FOR TESTING DURATION SHORT RISK LEVEL HARMLESS.
94
+ PRIVATE SECTION.
95
+ DATA mt_rows TYPE string_table.
96
+ METHODS test FOR TESTING.
97
+ ENDCLASS.
98
+
99
+ CLASS ltcl_test IMPLEMENTATION.
100
+ METHOD test.
101
+ DATA(lv_count) = lines( mt_rows ).
102
+ cl_abap_unit_assert=>assert_equals( act = lv_count exp = 2 ).
103
+ cl_abap_unit_assert=>assert_true( xsdbool( lv_count > 0 ) ).
104
+ ENDMETHOD.
105
+ ENDCLASS.`,
106
+ };
107
+ }
108
+ getConfig() {
109
+ return this.conf;
110
+ }
111
+ setConfig(conf) {
112
+ this.conf = conf;
113
+ }
114
+ runParsed(file, obj) {
115
+ var _a, _b;
116
+ const issues = [];
117
+ const structure = file.getStructure();
118
+ if (structure === undefined) {
119
+ return [];
120
+ }
121
+ const testClasses = this.testClassNames(obj);
122
+ if (testClasses.size === 0) {
123
+ return [];
124
+ }
125
+ for (const implementation of structure.findAllStructures(Structures.ClassImplementation)) {
126
+ const name = (_b = (_a = implementation.findFirstStatement(Statements.ClassImplementation)) === null || _a === void 0 ? void 0 : _a.findFirstExpression(Expressions.ClassName)) === null || _b === void 0 ? void 0 : _b.concatTokens().toUpperCase();
127
+ if (name === undefined || testClasses.has(name) === false) {
128
+ continue;
129
+ }
130
+ for (const statement of implementation.findAllStatementNodes()) {
131
+ if (this.conf.assertStatement === true && statement.get() instanceof Statements.Assert) {
132
+ const message = "Use cl_abap_unit_assert instead of ASSERT in a test class";
133
+ issues.push(issue_1.Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity));
134
+ }
135
+ else if (this.conf.cannotFail === true && statement.get() instanceof Statements.Call) {
136
+ const message = this.cannotFail(statement);
137
+ if (message !== undefined) {
138
+ issues.push(issue_1.Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity));
139
+ }
140
+ }
141
+ }
142
+ }
143
+ return issues;
144
+ }
145
+ /** names of the FOR TESTING classes defined in any file of the object, upper case */
146
+ testClassNames(obj) {
147
+ const ret = new Set();
148
+ for (const f of obj.getABAPFiles()) {
149
+ for (const def of f.getInfo().listClassDefinitions()) {
150
+ if (def.isForTesting === true) {
151
+ ret.add(def.name.toUpperCase());
152
+ }
153
+ }
154
+ }
155
+ return ret;
156
+ }
157
+ /** returns the message if the call is an assertion that cannot fail */
158
+ cannotFail(statement) {
159
+ const call = this.assertCall(statement);
160
+ if (call === undefined) {
161
+ return undefined;
162
+ }
163
+ if (call.method === "ASSERT_EQUALS" || call.method === "ASSERT_EQUALS_FLOAT") {
164
+ const act = call.parameters.get("ACT");
165
+ const exp = call.parameters.get("EXP");
166
+ if (act === undefined || exp === undefined || this.hasCall(act) || this.hasCall(exp)) {
167
+ return undefined;
168
+ }
169
+ if (this.normalized(act) === this.normalized(exp)) {
170
+ return "Assertion cannot fail, act and exp are the same";
171
+ }
172
+ }
173
+ else if (call.method === "ASSERT_TRUE" || call.method === "ASSERT_FALSE") {
174
+ const act = call.parameters.get("ACT");
175
+ if (act === undefined) {
176
+ return undefined;
177
+ }
178
+ const value = this.normalized(act);
179
+ if (call.method === "ASSERT_TRUE" && (value === "ABAP_TRUE" || value === "'X'")) {
180
+ return "Assertion cannot fail, act is abap_true";
181
+ }
182
+ else if (call.method === "ASSERT_FALSE"
183
+ && (value === "ABAP_FALSE" || value === "SPACE" || value === "''" || value === "' '")) {
184
+ return "Assertion cannot fail, act is abap_false";
185
+ }
186
+ }
187
+ return undefined;
188
+ }
189
+ /** class method call of cl_abap_unit_assert or cl_aunit_assert: method name and the sources by parameter name, upper case */
190
+ assertCall(statement) {
191
+ var _a, _b;
192
+ let className;
193
+ let methodName;
194
+ let parameters;
195
+ const chain = statement.findDirectExpression(Expressions.MethodCallChain);
196
+ const source = statement.findDirectExpression(Expressions.MethodSource);
197
+ if (chain !== undefined) {
198
+ const children = chain.getChildren();
199
+ const methodCall = chain.findDirectExpression(Expressions.MethodCall);
200
+ if (children.length !== 3 || methodCall === undefined) {
201
+ return undefined;
202
+ }
203
+ className = chain.findDirectExpression(Expressions.ClassName);
204
+ methodName = methodCall.findDirectExpression(Expressions.MethodName);
205
+ parameters = methodCall.findDirectExpression(Expressions.MethodCallParam);
206
+ }
207
+ else if (source !== undefined) {
208
+ const children = source.getChildren();
209
+ if (children.length !== 3) {
210
+ return undefined;
211
+ }
212
+ className = source.findDirectExpression(Expressions.ClassName);
213
+ methodName = source.findDirectExpression(Expressions.AttributeName);
214
+ parameters = statement.findDirectExpression(Expressions.MethodCallBody);
215
+ }
216
+ if (className === undefined
217
+ || methodName === undefined
218
+ || parameters === undefined
219
+ || ASSERT_CLASSES.includes(className.concatTokens().toUpperCase()) === false) {
220
+ return undefined;
221
+ }
222
+ // CALL METHOD x( ... ) and the functional call have a MethodCallParam, CALL METHOD x EXPORTING ... has not
223
+ const param = parameters.get() instanceof Expressions.MethodCallParam
224
+ ? parameters : parameters.findDirectExpression(Expressions.MethodCallParam);
225
+ const list = (param === null || param === void 0 ? void 0 : param.findDirectExpression(Expressions.ParameterListS))
226
+ || ((_a = (param || parameters).findDirectExpression(Expressions.MethodParameters)) === null || _a === void 0 ? void 0 : _a.findDirectExpression(Expressions.ParameterListS));
227
+ const map = new Map();
228
+ const single = param === null || param === void 0 ? void 0 : param.findDirectExpression(Expressions.Source);
229
+ if (single !== undefined) {
230
+ // only the preferred parameter is given, for the assertions checked here it is ACT
231
+ map.set("ACT", single);
232
+ }
233
+ for (const parameter of (list === null || list === void 0 ? void 0 : list.findDirectExpressions(Expressions.ParameterS)) || []) {
234
+ const name = (_b = parameter.findDirectExpression(Expressions.ParameterName)) === null || _b === void 0 ? void 0 : _b.concatTokens().toUpperCase();
235
+ const value = parameter.findDirectExpression(Expressions.Source);
236
+ if (name !== undefined && value !== undefined) {
237
+ map.set(name, value);
238
+ }
239
+ }
240
+ return { method: methodName.concatTokens().toUpperCase(), parameters: map };
241
+ }
242
+ /** two evaluations of the source can give different values */
243
+ hasCall(source) {
244
+ return source.findFirstExpression(Expressions.MethodCallChain) !== undefined
245
+ || source.findFirstExpression(Expressions.MethodCall) !== undefined
246
+ || source.findFirstExpression(Expressions.NewObject) !== undefined;
247
+ }
248
+ /** the tokens of the source, upper case outside of literals */
249
+ normalized(source) {
250
+ return source.getAllTokens().map(token => {
251
+ if (token instanceof Tokens.StringToken
252
+ || token instanceof Tokens.StringTemplate
253
+ || token instanceof Tokens.StringTemplateBegin
254
+ || token instanceof Tokens.StringTemplateMiddle
255
+ || token instanceof Tokens.StringTemplateEnd) {
256
+ return token.getStr();
257
+ }
258
+ return token.getStr().toUpperCase();
259
+ }).join(" ");
260
+ }
261
+ }
262
+ exports.UnitTestAssertions = UnitTestAssertions;
263
+ //# sourceMappingURL=unit_test_assertions.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abaplint/core",
3
- "version": "2.120.108",
3
+ "version": "2.120.109",
4
4
  "description": "abaplint - Core API",
5
5
  "main": "build/src/index.js",
6
6
  "typings": "build/abaplint.d.ts",