Skip to content

Commit c3e725f

Browse files
committed
Add iterator for initializers in PatternBindingDecl
This makes it safer and easier to iterate over the initializer expression in the pattern binding decl. I look forward to refactoring all the places running an index loop over the `getNumPatternEntries`.
1 parent f03df6d commit c3e725f

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

include/swift/AST/Decl.h

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1682,6 +1682,62 @@ class PatternBindingDecl final : public Decl,
16821682
return const_cast<PatternBindingDecl*>(this)->getMutablePatternList();
16831683
}
16841684

1685+
/// Clean up walking the initializers for the pattern
1686+
class InitIterator {
1687+
1688+
const PatternBindingDecl &decl;
1689+
unsigned currentPatternEntryIndex;
1690+
1691+
void next() { ++currentPatternEntryIndex; }
1692+
1693+
public:
1694+
using value_type = Expr *;
1695+
using pointer = value_type;
1696+
using reference = value_type;
1697+
using difference_type = unsigned;
1698+
1699+
InitIterator(const PatternBindingDecl &decl, unsigned start = 0)
1700+
: decl(decl), currentPatternEntryIndex(start) {}
1701+
1702+
InitIterator &operator++() {
1703+
next();
1704+
return *this;
1705+
}
1706+
1707+
InitIterator operator++(int) {
1708+
InitIterator newIterator(decl, currentPatternEntryIndex);
1709+
newIterator.next();
1710+
return newIterator;
1711+
}
1712+
1713+
pointer operator->() { return decl.getInit(currentPatternEntryIndex); }
1714+
1715+
pointer operator*() { return decl.getInit(currentPatternEntryIndex); }
1716+
1717+
difference_type operator-(const InitIterator &other) {
1718+
return currentPatternEntryIndex - other.currentPatternEntryIndex;
1719+
}
1720+
1721+
bool operator==(const InitIterator &other) const {
1722+
return &decl == &other.decl &&
1723+
currentPatternEntryIndex == other.currentPatternEntryIndex;
1724+
}
1725+
1726+
bool operator!=(const InitIterator &other) const {
1727+
return !(*this == other);
1728+
}
1729+
};
1730+
1731+
InitIterator beginInits() const { return InitIterator(*this); }
1732+
1733+
InitIterator endInits() const {
1734+
return InitIterator(*this, getNumPatternEntries());
1735+
}
1736+
1737+
llvm::iterator_range<InitIterator> initializers() const {
1738+
return llvm::make_range(beginInits(), endInits());
1739+
}
1740+
16851741
void setInitStringRepresentation(unsigned i, StringRef str) {
16861742
getMutablePatternList()[i].setInitStringRepresentation(str);
16871743
}

0 commit comments

Comments
 (0)