@@ -213,21 +213,37 @@ class CPPCHECKLIB Token {
213213 * For example index 1 would return next token, and 2
214214 * would return next from that one.
215215 */
216- const Token *tokAt (int index) const ;
217- Token *tokAt (int index);
216+ const Token *tokAt (int index) const
217+ {
218+ return tokAtImpl (this , index);
219+ }
220+ Token *tokAt (int index)
221+ {
222+ return tokAtImpl (this , index);
223+ }
218224
219225 /* *
220226 * @return the link to the token in given index, related to this token.
221227 * For example index 1 would return the link to next token.
222228 */
223- const Token *linkAt (int index) const ;
224- Token *linkAt (int index);
229+ const Token *linkAt (int index) const
230+ {
231+ return linkAtImpl (this , index);
232+ }
233+ Token *linkAt (int index)
234+ {
235+ return linkAtImpl (this , index);
236+ }
225237
226238 /* *
227239 * @return String of the token in given index, related to this token.
228240 * If that token does not exist, an empty string is being returned.
229241 */
230- const std::string &strAt (int index) const ;
242+ const std::string &strAt (int index) const
243+ {
244+ const Token *tok = this ->tokAt (index);
245+ return tok ? tok->mStr : emptyString;
246+ }
231247
232248 /* *
233249 * Match given token (or list of tokens) to a pattern list.
@@ -789,6 +805,30 @@ class CPPCHECKLIB Token {
789805 static Token *findmatch (Token * const startTok, const char pattern[], const Token * const end, const nonneg int varId = 0 );
790806
791807private:
808+ template <class T , REQUIRES(" T must be a Token class" , std::is_convertible<T*, const Token*> )>
809+ static T *tokAtImpl(T *tok, int index)
810+ {
811+ while (index > 0 && tok) {
812+ tok = tok->next ();
813+ --index;
814+ }
815+ while (index < 0 && tok) {
816+ tok = tok->previous ();
817+ ++index;
818+ }
819+ return tok;
820+ }
821+
822+ template <class T , REQUIRES(" T must be a Token class" , std::is_convertible<T*, const Token*> )>
823+ static T *linkAtImpl(T *thisTok, int index)
824+ {
825+ T *tok = thisTok->tokAt (index);
826+ if (!tok) {
827+ throw InternalError (thisTok, " Internal error. Token::linkAt called with index outside the tokens range." );
828+ }
829+ return tok->link ();
830+ }
831+
792832 /* *
793833 * Needle is build from multiple alternatives. If one of
794834 * them is equal to haystack, return value is 1. If there
0 commit comments