#include "store.ih"

void Store::calledBy(string const &spec)
{
    unordered_set<size_t> done;
    queue<size_t> todo;

    Pattern pattern{ spec };                // regex pattern to locate

    auto begin = d_defIdx.begin();          // range of defined symbol indices
    auto end = d_defIdx.end();

    cout <<                                 // the called-by listing
        setfill('-') << setw(70) << '-' << setfill(' ') << "\n"
        "CALLED-BY LISTING:\n\n";

    checkGlobals(begin, end);               // check for a GLOBALS entry with
                                            // a possible function name

    while (true)
    {
        begin = find_if(                    // find an entry matching pattern
                   begin, end, 
                   [&](size_t idx)
                   {
                       return pattern << d_xrefVector[idx].symbol();
                   }
               );

        if (begin == end)                   // no more matching entries
            break;

        todo.push(*begin == d_globals.first ? d_globals.second : *begin);
        ++begin;
        callers(done, todo);                // recursively show its callers
    }

    if (done.empty())                       // unknown spec
        cout << spec << ": not found\n";
}
