Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 42242x 42242x 42242x 42242x 42242x 42242x 42242x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21142x 21142x 21142x 21142x 21142x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 63070x 21142x 21142x 20205x 20205x 21142x 21142x 418x 418x 418x 21142x 21142x 376x 376x 21142x 21142x 628x 229x 229x 399x 399x 399x 399x 628x 409x 409x 3019x 3019x 3019x 3019x 3019x 47x 47x 47x 3019x 15x 15x 15x 2972x 2957x 2957x 3019x 6x 6x 56x 56x 56x 3019x 1x 1x 55x 55x 3019x 40x 40x 55x 3019x 3019x 3019x 8x 8x 47x 3019x 3019x 3019x 3019x 28x 28x 28x 28x 15x 15x 15x 15x 3019x 19x 19x 5x 5x 5x 3019x 20x 20x 3019x 3019x 399x 399x 399x 21142x 21142x 21142x 21142x 21142x 47x 47x 47x 2x 2x 45x 45x 45x 47x 2x 2x 43x 43x 21142x 21142x 21142x 15x 15x 15x 15x 15x 15x 15x 2x 2x 13x 13x 21142x 21142x 21142x 28x 28x 28x 2x 2x 26x 26x 28x 28x 28x 28x 5x 5x 21x 21x 28x 53x 53x 53x 28x 53x 4x 25x 53x 21x 21x 21142x 21142x 21142x 5x 5x 5x 5x 5x 3x 5x 5x 5x 21142x 21142x 25x 4x 4x 21x 25x 15x 15x 6x 6x 6x 21142x 21142x 21142x 47x 119x 28x 28x 119x 19x 19x 21142x 21142x 21142x 19x 19x 19x 3x 3x 19x 16x 16x 3x 19x 7x 7x 7x 7x 3x 3x 7x 21142x 21142x 123x 123x 123x 21142x 21142x 21142x 42x 134x 12x 12x 134x 30x 30x 21142x 21142x 134x 134x 134x 21142x 21142x 76x 76x 6x 6x 70x 70x 21142x 21142x 32x 32x 32x 32x 32x 32x 32x 32x 1x 32x 16x 1x 1x 15x 16x 31x 10x 10x 10x 10x 5x 5x 21142x 21142x 16x 16x 16x 21142x 21142x 21142x 21142x 55x 55x 55x 55x 95x 95x 44x 44x 51x 51x 95x 95x 44x 44x 21142x 21142x 21142x 50x 50x 1x 1x 49x 49x 21142x | import * as Expressions from "../abap/2_statements/expressions";
import * as Statements from "../abap/2_statements/statements";
import {BasicRuleConfig} from "./_basic_rule_config";
import {Issue} from "../issue";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {IObject} from "../objects/_iobject";
import {ABAPObject} from "../objects/_abap_object";
import {IRegistry} from "../_iregistry";
import {StructureType, TableAccessType, TableKeyType, TableType, UnknownType, VoidType} from "../abap/types/basic";
import {ExpressionNode, StatementNode} from "../abap/nodes";
import {ABAPFile} from "../abap/abap_file";
import {ISpaghettiScope} from "../abap/5_syntax/_spaghetti_scope";
import {TypedIdentifier} from "../abap/types/_typed_identifier";
import {Severity} from "../severity";
import {findTypedIdentifier} from "./_type_lookup";
import {endsLoop, innermostLoop, procedureEnd, procedureStart, startsLoop} from "./_statement_blocks";
export class SortRequiredConf extends BasicRuleConfig {
public severity?: Severity = Severity.Warning;
/** Check READ TABLE ... WITH KEY ... BINARY SEARCH */
public binarySearch: boolean = true;
/** Check DELETE ADJACENT DUPLICATES ... COMPARING */
public adjacentDuplicates: boolean = true;
}
type SortField = {name: string, descending: boolean};
/** what a statement that writes the table does to its order */
enum Fill {
/** SELECT without ORDER BY, or APPEND, INSERT or COLLECT in such a SELECT loop: rows in no defined order */
unordered,
/** CLEAR, DELETE, MODIFY, SORT, and APPEND, INSERT or COLLECT elsewhere: the code can add the rows in order */
none,
/** anything else: the rows can come sorted from elsewhere */
unknown,
}
export class SortRequired implements IRule {
private reg: IRegistry;
private conf = new SortRequiredConf();
public getMetadata(): IRuleMetadata {
return {
key: "sort_required",
title: "BINARY SEARCH or DELETE ADJACENT DUPLICATES without a matching SORT",
shortDescription: `BINARY SEARCH or DELETE ADJACENT DUPLICATES ... COMPARING on a local table not sorted by those fields`,
extendedInformation: `READ TABLE ... WITH KEY ... BINARY SEARCH only finds the row when the table is sorted ascending by
the key fields, in the order of the key. DELETE ADJACENT DUPLICATES ... COMPARING only removes all duplicates
when rows with equal values in the compared fields are next to each other. Neither statement checks the order:
on an unsorted table they give wrong results, without a dump.
Checked: a standard table declared with DATA in the method, form or function module, read with WITH KEY
and BINARY SEARCH, or with DELETE ADJACENT DUPLICATES ... COMPARING. Reported when
- the last SORT of the table before the statement is not by the key fields: for BINARY SEARCH they must be
the first sort fields, in the same order and ascending; for COMPARING the first sort fields must be the
compared fields, in any order. A SORT without BY uses the primary key.
- there is no SORT of the table before the statement, and it is filled by a SELECT without ORDER BY: the
database returns the rows in no defined order.
Not reported: parameters, attributes, global and static variables, a table that can get its rows sorted
from elsewhere (an assignment, a method or function call, APPEND or INSERT LINES OF, SELECT ... ORDER BY)
after the SORT or, without a SORT, anywhere in the procedure, a table without SORT filled only by APPEND,
INSERT or COLLECT (the code can add the rows in order), sorted and hashed tables, SORT with STABLE or with
dynamic fields, a SORT later in a loop around the statement, a SORT without BY on a default key of a
structured row, WITH TABLE KEY, USING KEY, dynamic components and COMPARING ALL FIELDS.
See also sort_empty_key and sequential_read_sorted.`,
tags: [RuleTag.SingleFile],
badExample: `SORT lt_titles BY id.
DELETE ADJACENT DUPLICATES FROM lt_titles COMPARING spras id.
SELECT * FROM tadir INTO TABLE lt_tadir WHERE devclass = lv_package.
READ TABLE lt_tadir WITH KEY object = lv_type obj_name = lv_name BINARY SEARCH TRANSPORTING NO FIELDS.`,
goodExample: `SORT lt_titles BY spras id.
DELETE ADJACENT DUPLICATES FROM lt_titles COMPARING spras id.
SELECT * FROM tadir INTO TABLE lt_tadir WHERE devclass = lv_package.
SORT lt_tadir BY object obj_name.
READ TABLE lt_tadir WITH KEY object = lv_type obj_name = lv_name BINARY SEARCH TRANSPORTING NO FIELDS.`,
};
}
public getConfig() {
return this.conf;
}
public initialize(reg: IRegistry) {
this.reg = reg;
return this;
}
public setConfig(conf: SortRequiredConf): void {
this.conf = conf;
}
public run(obj: IObject): Issue[] {
if (!(obj instanceof ABAPObject) || obj.getType() === "INTF") {
return [];
}
const issues: Issue[] = [];
let spaghetti: ISpaghettiScope | undefined = undefined;
for (const file of obj.getABAPFiles()) {
const statements = file.getStatements();
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
let table: ExpressionNode | undefined;
let fields: string[] | undefined;
let binary: boolean;
if (statement.get() instanceof Statements.ReadTable && this.conf.binarySearch !== false) {
binary = true;
table = statement.getChildren().find(c => c instanceof ExpressionNode) as ExpressionNode | undefined;
fields = this.readKey(statement);
} else if (statement.get() instanceof Statements.DeleteInternal && this.conf.adjacentDuplicates !== false) {
binary = false;
table = statement.findDirectExpression(Expressions.Target);
fields = this.comparing(statement);
} else {
continue;
}
if (table === undefined || fields === undefined || /^[\w/]+$/.test(table.concatTokens()) === false) {
continue;
}
const name = table.concatTokens().toUpperCase();
const start = procedureStart(i, statements);
if (start === undefined) {
continue;
}
const end = procedureEnd(i, statements);
if (spaghetti === undefined) {
spaghetti = new SyntaxLogic(this.reg, obj).run().spaghetti;
}
const id = findTypedIdentifier(table.getFirstToken().getStart(), spaghetti, file);
const declaration = id === undefined ? undefined : this.findDeclaration(id, file, statements, start, i);
const type = id?.getType();
if (declaration === undefined || !(type instanceof TableType) || this.isStandard(type, declaration) === false) {
continue;
}
const verb = binary ? "READ TABLE ... BINARY SEARCH" : "DELETE ADJACENT DUPLICATES ... COMPARING";
const sortIndex = this.previousSort(name, statements, start, i);
let message: string | undefined = undefined;
if (sortIndex !== undefined) {
const sortFields = this.sortFields(statements[sortIndex], type);
if (sortFields !== undefined
&& this.matches(sortFields, fields, binary) === false
&& this.filled(name, statements, sortIndex, i, Fill.unknown) === false) {
const by = sortFields.map(f => f.name.toLowerCase() + (f.descending ? " DESCENDING" : "")).join(" ");
message = `${verb} on ${table.concatTokens()} needs it sorted by ${fields.join(" ").toLowerCase()}, `
+ `the SORT before is by ${by}`;
}
} else if (this.sortedLaterInLoop(name, statements, i) === false
&& this.filled(name, statements, start, end, Fill.unknown) === false
&& this.filled(name, statements, start, end, Fill.unordered) === true) {
message = `${verb} on ${table.concatTokens()} needs it sorted by ${fields.join(" ").toLowerCase()}, `
+ `there is no SORT before`;
}
if (message !== undefined) {
issues.push(Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity));
}
}
}
return issues;
}
////////////////
/** the components of WITH KEY, for a READ TABLE ... BINARY SEARCH with a free key */
private readKey(statement: StatementNode): string[] | undefined {
if (statement.findDirectTokenByText("BINARY") === undefined
|| statement.findDirectTokenByText("USING") !== undefined
|| statement.findDirectTokenByText("COMPONENTS") !== undefined) {
return undefined;
}
const tokens = statement.getTokens().map(t => t.getStr().toUpperCase());
const withKey = tokens.findIndex((t, index) => t === "WITH" && tokens[index + 1] === "KEY");
const compare = statement.findDirectExpression(Expressions.ComponentCompareSimple);
if (withKey < 0 || compare === undefined || compare.findDirectExpression(Expressions.Dynamic) !== undefined) {
return undefined;
}
return compare.findDirectExpressions(Expressions.ComponentChainSimple).map(c => c.concatTokens().toUpperCase());
}
/** the fields after COMPARING, for a DELETE ADJACENT DUPLICATES with static fields */
private comparing(statement: StatementNode): string[] | undefined {
if (statement.findDirectTokenByText("ADJACENT") === undefined
|| statement.findDirectTokenByText("USING") !== undefined
|| statement.findDirectTokenByText("ALL") !== undefined
|| statement.findDirectTokenByText("COMPARING") === undefined
|| statement.findDirectExpression(Expressions.Dynamic) !== undefined
|| statement.findDirectExpression(Expressions.FieldOffset) !== undefined
|| statement.findDirectExpression(Expressions.FieldLength) !== undefined) {
return undefined;
}
return statement.findDirectExpressions(Expressions.SimpleFieldChain2).map(c => c.concatTokens().toUpperCase());
}
/** the sort fields of a SORT, undefined when not known */
private sortFields(statement: StatementNode, type: TableType): SortField[] | undefined {
if (statement.findDirectTokenByText("STABLE") !== undefined
|| statement.findDirectExpression(Expressions.Dynamic) !== undefined
|| statement.findDirectExpression(Expressions.SourceFieldSymbol) !== undefined) {
return undefined;
}
const children = statement.getChildren();
const by = children.findIndex(c => c.concatTokens().toUpperCase() === "BY");
const descending = children.slice(0, by < 0 ? children.length : by)
.some(c => c.concatTokens().toUpperCase() === "DESCENDING");
if (by < 0) {
return this.primaryKey(type)?.map(name => ({name, descending}));
}
const result: SortField[] = [];
for (let j = by + 1; j < children.length; j++) {
const child = children[j];
const text = child.concatTokens().toUpperCase();
if (child.get() instanceof Expressions.ComponentChain) {
result.push({name: text, descending});
} else if (text === "DESCENDING" && result.length > 0) {
result[result.length - 1].descending = true;
} else if (text === "ASCENDING" && result.length > 0) {
result[result.length - 1].descending = false;
}
}
return result;
}
/** the primary key components, undefined for a default key of a structured row or when not known */
private primaryKey(type: TableType): string[] | undefined {
const row = type.getRowType();
if (row instanceof VoidType || row instanceof UnknownType || row.isGeneric()) {
return undefined;
}
const keyType = type.getOptions().keyType;
const fields = type.getOptions().primaryKey?.keyFields || [];
if (keyType === TableKeyType.user && fields.length > 0) {
return fields;
} else if (keyType === TableKeyType.empty) {
return [];
}
return row instanceof StructureType || row instanceof TableType ? undefined : ["TABLE_LINE"];
}
private matches(sortFields: SortField[], fields: string[], binary: boolean): boolean {
if (sortFields.length < fields.length) {
return false;
}
const first = sortFields.slice(0, fields.length);
if (binary === true) {
return first.every((f, index) => f.name === fields[index] && f.descending === false);
}
const names = first.map(f => f.name);
return fields.every(f => names.includes(f));
}
/** index of the last SORT of the table before the statement, in the same procedure */
private previousSort(name: string, statements: readonly StatementNode[], start: number, index: number): number | undefined {
for (let i = index - 1; i > start; i--) {
if (this.isSortOf(statements[i], name)) {
return i;
}
}
return undefined;
}
/** a SORT of the table after the statement but inside a loop around it runs before the next pass */
private sortedLaterInLoop(name: string, statements: readonly StatementNode[], index: number): boolean {
// the outermost loop around the statement
let outer = innermostLoop(index, statements);
for (let next = outer; next !== undefined; next = innermostLoop(next, statements)) {
outer = next;
}
if (outer === undefined) {
return false;
}
let depth = 0;
for (let i = outer + 1; i < statements.length; i++) {
const statement = statements[i];
if (startsLoop(statement)) {
depth++;
} else if (endsLoop(statement)) {
if (depth === 0) {
return false;
}
depth--;
} else if (i > index && this.isSortOf(statement, name)) {
return true;
}
}
return false;
}
private isSortOf(statement: StatementNode, name: string): boolean {
return statement.get() instanceof Statements.Sort
&& statement.findDirectExpression(Expressions.Target)?.concatTokens().toUpperCase() === name;
}
/** true when a statement between from and to, both excluded, fills the table in the given way */
private filled(name: string, statements: readonly StatementNode[], from: number, to: number, kind: Fill): boolean {
for (let i = from + 1; i < to; i++) {
if (this.writes(statements[i], name) && this.fillKind(i, statements, name) === kind) {
return true;
}
}
return false;
}
private writes(statement: StatementNode, name: string): boolean {
return statement.get() instanceof Statements.Data === false
&& statement.findAllExpressions(Expressions.Target).some(t => this.targetName(t) === name);
}
private targetName(target: ExpressionNode): string {
const inline = target.findDirectExpression(Expressions.InlineData);
if (inline !== undefined) {
return inline.findDirectExpression(Expressions.TargetField)?.concatTokens().toUpperCase() || "";
}
return target.concatTokens().toUpperCase();
}
private fillKind(index: number, statements: readonly StatementNode[], name: string): Fill {
const statement = statements[index];
const s = statement.get();
if (s instanceof Statements.Clear
|| s instanceof Statements.Refresh
|| s instanceof Statements.Free
|| s instanceof Statements.DeleteInternal
|| s instanceof Statements.ModifyInternal
|| s instanceof Statements.Sort) {
return Fill.none;
} else if (s instanceof Statements.Append || s instanceof Statements.InsertInternal || s instanceof Statements.Collect) {
if (statement.findDirectTokenByText("LINES") !== undefined || statement.findDirectTokenByText("SORTED") !== undefined) {
return Fill.unknown;
}
const loop = innermostLoop(index, statements);
return loop !== undefined && this.selectsUnordered(statements[loop]) ? Fill.unordered : Fill.none;
} else if (s instanceof Statements.Select || s instanceof Statements.SelectLoop) {
const target = statement.findFirstExpression(Expressions.SQLIntoTable)?.findFirstExpression(Expressions.Target);
return target !== undefined && this.targetName(target) === name && this.selectsUnordered(statement)
? Fill.unordered : Fill.unknown;
}
return Fill.unknown;
}
private selectsUnordered(statement: StatementNode): boolean {
return (statement.get() instanceof Statements.Select || statement.get() instanceof Statements.SelectLoop)
&& statement.findFirstExpression(Expressions.SQLOrderBy) === undefined;
}
/** the DATA statement or inline declaration of the table inside the procedure, before the statement;
* parameters, attributes, globals and statics are declared elsewhere or with another statement */
private findDeclaration(id: TypedIdentifier, file: ABAPFile, statements: readonly StatementNode[],
start: number, index: number): StatementNode | undefined {
if (id.getFilename() !== file.getFilename()) {
return undefined;
}
const position = id.getStart();
for (let i = start + 1; i < index; i++) {
const statement = statements[i];
if (position.isBetween(statement.getStart(), statement.getEnd()) === false) {
continue;
}
const inline = statement.findAllExpressions(Expressions.InlineData)
.some(d => position.isBetween(d.getFirstToken().getStart(), d.getLastToken().getEnd()));
return statement.get() instanceof Statements.Data || inline ? statement : undefined;
}
return undefined;
}
/** a standard table; the result of an inline SELECT has no access type set, it is a standard table */
private isStandard(type: TableType, declaration: StatementNode): boolean {
const access = type.getAccessType();
if (access === undefined) {
return declaration.get() instanceof Statements.Select || declaration.get() instanceof Statements.SelectLoop;
}
return access === TableAccessType.standard;
}
}
|