aboutsummaryrefslogtreecommitdiff
path: root/build2/function.cxx
blob: e71f15868fa2459d4350204215ac569d28f6a665 (plain)
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
// file      : build2/function.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2017 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <build2/function.hxx>

#include <cstring> // strchr()

using namespace std;

namespace build2
{
  ostream&
  operator<< (ostream& os, const function_overload& f)
  {
    os << f.name << '(';

    bool v (f.arg_max == function_overload::arg_variadic);
    size_t n (v ? max (f.arg_min, f.arg_types.size ()): f.arg_max);

    // Handle variadic tail as the last pseudo-argument.
    //
    for (size_t i (0); i != n + (v ? 1 : 0); ++i)
    {
      if (i == f.arg_min)
        os << (i != 0 ? " [" : "[");

      os << (i != 0 ? ", " : "");

      if (i == n) // Variadic tail (last).
        os << "...";
      else
      {
        // If count is greater than f.arg_typed, then we assume the rest are
        // valid but untyped.
        //
        const optional<const value_type*> t (
          i < f.arg_types.size () ? f.arg_types[i] : nullopt);

        os << (t ? (*t != nullptr ? (*t)->name : "<untyped>") : "<anytype>");
      }
    }

    if (n + (v ? 1 : 0) > f.arg_min)
      os << ']';

    os << ')';

    if (f.alt_name != nullptr)
    {
      auto k (strchr (f.alt_name, '.') == nullptr
              ? "unqualified"
              : "qualified");

      os << ", " << k << " name " << f.alt_name;
    }

    return os;
  }

  bool function_map::
  defined (const string& name) const
  {
    assert (!name.empty ());

    // If this is a qualified function name then check if it is already
    // defined.
    //
    if (name.back () != '.')
      return map_.find (name) != map_.end ();

    // If any function of the specified family is already defined, then one of
    // them should be the first element that is greater than the dot-terminated
    // family name. Here we rely on the fact that the dot character is less
    // than any character of unqualified function and family names.
    //
    size_t n (name.size ());
    assert (n > 1);

    auto i (map_.upper_bound (name));
    return i != map_.end () && i->first.compare (0, n, name) == 0;
  }

  auto function_map::
  insert (string name, function_overload f) -> iterator
  {
    // Sanity checks.
    //
    assert (f.arg_min <= f.arg_max &&
            f.arg_types.size () <= f.arg_max &&
            f.impl != nullptr);

    auto i (map_.emplace (move (name), move (f)));

    i->second.name = i->first.c_str ();
    return i;
  }

  pair<value, bool> function_map::
  call (const scope* base,
        const string& name,
        vector_view<value> args,
        const location& loc,
        bool fa) const
  {
    auto print_call = [&name, &args] (ostream& os)
    {
      os << name << '(';

      for (size_t i (0); i != args.size (); ++i)
      {
        const value_type* t (args[i].type);
        os << (i != 0 ? ", " : "") << (t != nullptr ? t->name : "<untyped>");
      }

      os << ')';
    };

    // Overload resolution.
    //
    // Ours is pretty simple: if all the arguments match exactly, then we have
    // a perfect match. Otherwise, if any argument matches via the derived-to-
    // base conversion, then we have an imperfect match. More than one perfect
    // or imperfect match is ambiguous (i.e., we don't try to rank imperfect
    // matches).
    //
    size_t count (args.size ());
    auto ip (map_.equal_range (name));

    // First look for a perfect match, then for imperfect. We do it this way
    // to make sure we always stay small in the successful case.
    //
    small_vector<const function_overload*, 1> r;

    for (bool perf (true);; perf = false)
    {
      for (auto it (ip.first); it != ip.second; ++it)
      {
        const function_overload& f (it->second);

        // Argument count match.
        //
        if (count < f.arg_min || count > f.arg_max)
          continue;

        // Argument types match.
        //
        {
          size_t i (0), n (min (count, f.arg_types.size ()));
          for (; i != n; ++i)
          {
            if (!f.arg_types[i]) // Anytyped.
              continue;

            const value_type* at (args[i].type);
            const value_type* ft (*f.arg_types[i]);

            if (at == ft) // Types match perfectly.
              continue;

            if (!perf && at != nullptr && ft != nullptr)
            {
              while ((at = at->base_type) != nullptr && at != ft) ;

              if (at != nullptr) // Types match via derived-to-base.
                continue;
            }

            break;
          }

          if (i != n)
            continue;
        }

        r.push_back (&f); // Continue looking to detect ambiguities.
      }

      if (!r.empty () || !perf)
        break;
    }

    switch (r.size ())
    {
    case 1:
      {
        // Print the call location in case the function fails.
        //
        auto g (
          make_exception_guard (
            [fa, &loc, &print_call] ()
            {
              if (fa && verb != 0)
              {
                diag_record dr (info (loc));
                dr << "while calling "; print_call (dr.os);
              }
            }));

        auto f (r.back ());
        return make_pair (f->impl (base, move (args), *f), true);
      }
    case 0:
      {
        if (!fa)
          return make_pair (value (nullptr), false);

        // No match.
        //
        diag_record dr;

        dr << fail (loc) << "unmatched call to "; print_call (dr.os);

        for (auto i (ip.first); i != ip.second; ++i)
          dr << info << "candidate: " << i->second;

        // If this is an unqualified name, then also print qualified
        // functions that end with this name. But skip functions that we
        // have already printed in the previous loop.
        //
        if (name.find ('.') == string::npos)
        {
          size_t n (name.size ());

          for (auto i (functions.begin ()); i != functions.end (); ++i)
          {
            const string& q (i->first);
            const function_overload& f (i->second);

            if ((f.alt_name == nullptr || f.alt_name != name) &&
                q.size () > n)
            {
              size_t p (q.size () - n);
              if (q[p - 1] == '.' && q.compare (p, n, name) == 0)
                dr << info << "candidate: " << i->second;
            }
          }
        }

        dr << endf;
      }
    default:
      {
        // Ambigous match.
        //
        diag_record dr;
        dr << fail (loc) << "ambiguous call to "; print_call (dr.os);

        for (auto f: r)
          dr << info << "candidate: " << *f;

        dr << endf;
      }
    }
  }

  value function_family::
  default_thunk (const scope* base,
                 vector_view<value> args,
                 const function_overload& f)
  try
  {
    // Call the cast thunk.
    //
    struct cast_data // Prefix of function_cast::data.
    {
      value (*const thunk) (const scope*, vector_view<value>, const void*);
    };

    auto d (reinterpret_cast<const cast_data*> (&f.data));
    return d->thunk (base, move (args), d);
  }
  catch (const invalid_argument& e)
  {
    diag_record dr (fail);
    dr << "invalid argument";

    if (*e.what () != '\0')
      dr << ": " << e;

    dr << endf;
  }

#if !defined(_MSC_VER) || _MSC_VER > 1910
  constexpr const optional<const value_type*>* function_args<>::types;
#else
  const optional<const value_type*>* const function_args<>::types = nullptr;
#endif

  void function_family::entry::
  insert (string n, function_overload f) const
  {
    // Figure out qualification.
    //
    string qn;
    size_t p (n.find ('.'));

    if (p == string::npos)
    {
      if (!qual.empty ())
      {
        qn = qual;
        qn += '.';
        qn += n;
      }
    }
    else if (p == 0)
    {
      assert (!qual.empty ());
      n.insert (0, qual);
    }

    auto i (qn.empty () ? functions.end () : functions.insert (move (qn), f));
    auto j (functions.insert (move (n), move (f)));

    // If we have both, then set alternative names.
    //
    if (i != functions.end ())
    {
      i->second.alt_name = j->first.c_str ();
      j->second.alt_name = i->first.c_str ();
    }
  }

  // Static-initialize the function map and populate with builtin functions.
  //
  function_map functions;

  void builtin_functions ();        // functions-builtin.cxx
  void filesystem_functions ();     // functions-filesystem.cxx
  void path_functions ();           // functions-path.cxx
  void process_path_functions ();   // functions-process-path.cxx
  void regex_functions ();          // functions-regex.cxx
  void string_functions ();         // functions-string.cxx
  void target_triplet_functions (); // functions-target-triplet.cxx

  struct functions_init
  {
    functions_init ()
    {
      builtin_functions ();
      filesystem_functions ();
      path_functions ();
      process_path_functions ();
      regex_functions ();
      string_functions ();
      target_triplet_functions ();
    }
  };

  static const functions_init init_;
}