|
| 1 | +import type { Reporter } from '../algorithm-error-reporter-type'; |
| 2 | +import type { Seq } from '../../expr-parser'; |
| 3 | +import type { OrderedListItemNode } from 'ecmarkdown'; |
| 4 | +import { offsetToLineAndColumn } from '../../utils'; |
| 5 | + |
| 6 | +const ruleId = 'for-each-of'; |
| 7 | + |
| 8 | +/* |
| 9 | +Checks that "For each" loops use "of", not "in". |
| 10 | +*/ |
| 11 | +export default function ( |
| 12 | + report: Reporter, |
| 13 | + step: OrderedListItemNode, |
| 14 | + algorithmSource: string, |
| 15 | + parsedSteps: Map<OrderedListItemNode, Seq>, |
| 16 | +) { |
| 17 | + const stepSeq = parsedSteps.get(step); |
| 18 | + if (stepSeq == null || stepSeq.items.length < 3) { |
| 19 | + return; |
| 20 | + } |
| 21 | + const first = stepSeq.items[0]; |
| 22 | + if (!(first.name === 'text' && first.contents.startsWith('For each '))) { |
| 23 | + return; |
| 24 | + } |
| 25 | + // Find the loop variable (underscore), then check the text after it |
| 26 | + for (let i = 1; i < stepSeq.items.length - 1; i++) { |
| 27 | + const item = stepSeq.items[i]; |
| 28 | + if (item.name === 'underscore') { |
| 29 | + const next = stepSeq.items[i + 1]; |
| 30 | + if (next.name === 'text' && /^ in\b/.test(next.contents)) { |
| 31 | + report({ |
| 32 | + ruleId, |
| 33 | + ...offsetToLineAndColumn(algorithmSource, next.location.start.offset + 1), |
| 34 | + message: 'expected "of" instead of "in" in "for each"', |
| 35 | + }); |
| 36 | + } |
| 37 | + break; |
| 38 | + } |
| 39 | + } |
| 40 | +} |
0 commit comments