aboutsummaryrefslogtreecommitdiff
path: root/odb/include.cxx
blob: d5675a11d7b986530c647d0eaaf39b1b1bd8daf0 (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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// file      : odb/include.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2009-2011 Code Synthesis Tools CC
// license   : GNU GPL v3; see accompanying LICENSE file

#include <odb/gcc.hxx>

#include <set>
#include <map>
#include <locale>
#include <cassert>
#include <fstream>
#include <sstream>

#include <odb/common.hxx>
#include <odb/context.hxx>
#include <odb/generate.hxx>

#include <iostream>

using namespace std;
using semantics::path;

namespace
{
  struct include_directive
  {
    enum type { quote, bracket };

    type type_;
    path path_;
  };

  typedef std::map<line_map const*, include_directive> includes;
  typedef std::map<path, includes> include_map;

  // Map of files to the lines which contain include directives
  // that we are interested in.
  //
  typedef std::map<size_t, include_directive*> include_lines;
  typedef std::map<string, include_lines> file_map;

  // Set of include directives sorted in the preference order.
  //
  struct include_comparator
  {
    bool
    operator() (include_directive const* x, include_directive const* y) const
    {
      // Prefer <> over "".
      //
      if (x->type_ != y->type_)
        return x->type_ < y->type_;

      // Otherwise, prefer longer (more qualified) paths over the
      // shorter ones.
      //
      return x->path_.string ().size () < y->path_.string ().size ();
    }
  };

  typedef
  std::multiset<include_directive const*, include_comparator>
  include_set;


  struct class_: traversal::class_, context
  {
    class_ (include_map& map)
        : map_ (map)
    {
    }

    virtual void
    traverse (type& c)
    {
      // We only generate things for objects and composite value types. In
      // particular, we don't care about views since they cannot be used in
      // definitions of other views, objects, or composite values.
      //
      if (!(object (c) || composite (c)))
        return;

      // Not interested in classes that we are generating.
      //
      // If this is a class template instantiation, then get the file
      // corresponding to the pragma, not the instantiation itself,
      // since that's where we are generation the code for this class.
      // While at it, also get the location.
      //
      using semantics::path;

      path f;
      location_t l;

      if (c.is_a<semantics::class_instantiation> ())
      {
        l = c.get<location_t> ("location");
        f = path (LOCATION_FILE (l));
      }
      else
      {
        f = c.file ();
        tree decl (TYPE_NAME (c.tree_node ()));
        l = DECL_SOURCE_LOCATION (decl);
      }

      if (f == unit.file ())
        return;

      // This is a persistent object or composite value type declared in
      // another header file. Include its -odb header.
      //
      if (l > BUILTINS_LOCATION)
      {
        line_map const* lm (linemap_lookup (line_table, l));

        if (lm != 0 && !MAIN_FILE_P (lm))
        {
          lm = INCLUDED_FROM (line_table, lm);

          path f (c.file ());
          f.complete ();
          f.normalize ();

          if (map_.find (f) == map_.end ())
            map_[f][lm] = include_directive ();
        }
      }
    }

  private:
    include_map& map_;
  };

  class include_parser
  {
  public:
    include_parser (options const& options)
        : loc_ ("C"), options_ (options)
    {
    }

    void
    parse_file (string const& file, include_lines& lines)
    {
      string f (file);
      size_t n (f.size ());

      // Check if we have a synthesized prologue/epilogue fragment.
      //
      if (n != 0 && f[0] == '<' && f[n - 1] == '>')
      {
        size_t p (f.rfind ('-'));

        if (p != string::npos)
        {
          string name (f, 1, p - 1);

          if (name == "odb-prologue" || name == "odb-epilogue")
          {
            // Extract the fragment number.
            //
            {
              istringstream istr (string (f, p + 1));
              istr >> n;
            }

            n--; // Prologues/epilogues are counted from 1.

            stringstream ss;
            f.clear ();

            // We don't need the #line part.
            //
            if (name == "odb-prologue")
            {
              size_t size (options_.odb_prologue ().size ());

              if (n < size)
                ss << options_.odb_prologue ()[n];
              else
                f = options_.odb_prologue_file ()[n - size];
            }
            else
            {
              size_t size (options_.odb_epilogue ().size ());

              if (n < size)
                ss << options_.odb_epilogue ()[n];
              else
                f = options_.odb_epilogue_file ()[n - size];
            }

            if (f.empty ())
            {
              parse_stream (ss, file, lines);
              return;
            }
            // Otherwise use the code below to parse the file.
          }
        }
      }

      ifstream is (f.c_str ());

      if (!is.is_open ())
      {
        cerr << "error: unable to open '" << f << "' in read mode" << endl;
        throw operation_failed ();
      }

      parse_stream (is, f, lines);
    }

    void
    parse_stream (istream& is, string const& name, include_lines& lines)
    {
      typedef char_traits<char>::int_type int_type;

      size_t lmax (lines.rbegin ()->first);

      string line;
      bool bslash (false);
      size_t lb (1), le (1);
      bool eof (false);

      for (int_type c (is.get ()); !eof; c = is.get ())
      {
        if (is.fail ())
        {
          if (is.eof ())
          {
            // If we are still in the range, treat this as the last newline.
            //
            c = '\n';
            eof = true;
          }
          else
            break; // Some other failure -- bail out.
        }

        if (c == '\n')
        {
          le++;

          if (!bslash)
          {
            //cerr << "line: " << lb << "-" << (le - 1) << " " << line << endl;

            // See if we are interested in this range of physical lines.
            //
            include_lines::iterator li (lines.lower_bound (lb));
            include_lines::iterator ui (lines.upper_bound (le - 1));

            // We should have at most one entry per logical line.
            //
            for (; li != ui; ++li)
            {
              if (li->first >= lb && li->first <= (le - 1))
              {
                if (!parse_line (line, *li->second))
                {
                  cerr << name << ":" << lb << ":1: error: "
                       << "unable to parse #include directive" << endl;
                  throw operation_failed ();
                }
              }
            }

            if (le > lmax)
              break;

            lb = le;
            line.clear ();
          }

          bslash = false;
          continue;
        }

        if (bslash)
        {
          line += '\\';
          bslash = false;
        }

        if (c == '\\')
          bslash = true;
        else
        {
          line += char (c);
        }
      }

      if (is.bad () || (is.fail () && !is.eof ()))
      {
        cerr << "error: input error while reading '" << name << "'" << endl;
        throw operation_failed ();
      }
    }

  private:
    bool
    parse_line (string const& l, include_directive& inc)
    {
      enum state
      {
        start_hash,
        start_keyword,
        parse_keyword,
        start_path,
        parse_path,
        parse_done
      };

      bool com (false);  // In C-style comment.
      string lex;
      char path_end ('\0');
      state s (start_hash);

      for (size_t i (0), n (l.size ()); i < n; ++i)
      {
        char c (l[i]);

        if (com)
        {
          if (c == '*' && (i + 1) < n && l[i + 1] == '/')
          {
            ++i;
            com = false;
            c = ' '; // Replace a comment with a single space.
          }
          else
            continue;
        }

        // We only ignore spaces in start states.
        //
        if (is_space (c))
        {
          switch (s)
          {
          case start_hash:
          case start_keyword:
          case start_path:
            {
              continue;
            }
          default:
            {
              break;
            }
          }
        }

        // C comment can be anywhere except in the path.
        //
        if (s != parse_path && c == '/' && (i + 1) < n && l[i + 1] == '*')
        {
          ++i;
          com = true;
          continue;
        }

        switch (s)
        {
        case start_hash:
          {
            if (c != '#')
              return false;

            s = start_keyword;
            break;
          }
        case start_keyword:
          {
            lex.clear ();
            s = parse_keyword;
            // Fall through.
          }
        case parse_keyword:
          {
            if (is_alpha (c))
            {
              lex += c;
              break;
            }

            if (lex != "include")
              return false;

            s = start_path;
            --i; // Re-parse the same character again.
            break;
          }
        case start_path:
          {
            if (c == '"')
            {
              path_end = '"';
              inc.type_ = include_directive::quote;
            }
            else if (c == '<')
            {
              path_end = '>';
              inc.type_ = include_directive::bracket;
            }
            else
              return false;

            lex.clear ();
            s = parse_path;
            break;
          }
        case parse_path:
          {
            if (c != path_end)
              lex += c;
            else
              s = parse_done;

            break;
          }
        default:
          {
            assert (false);
            break;
          }
        }

        if (s == parse_done)
          break;
      }

      if (s != parse_done)
        return false;

      inc.path_ = path (lex);
      return true;
    }

  private:
    bool
    is_alpha (char c) const
    {
      return isalpha (c, loc_);
    }

    bool
    is_space (char c) const
    {
      return isspace (c, loc_);
    }

  private:
    std::locale loc_;
    options const& options_;
  };
}

namespace include
{
  void
  generate ()
  {
    context ctx;
    include_map imap;

    traversal::unit unit;
    traversal::defines unit_defines;
    typedefs unit_typedefs (true);
    traversal::namespace_ ns;
    class_ c (imap);

    unit >> unit_defines >> ns;
    unit_defines >> c;
    unit >> unit_typedefs >> c;

    traversal::defines ns_defines;
    typedefs ns_typedefs (true);

    ns >> ns_defines >> ns;
    ns_defines >> c;
    ns >> ns_typedefs >> c;

    unit.dispatch (ctx.unit);

    // Add all the known include locations for each file in the map.
    //
    for (size_t i (0); i < line_table->used; ++i)
    {
      line_map const* m (line_table->maps + i);

      if (MAIN_FILE_P (m) || m->reason != LC_ENTER)
        continue;

      line_map const* i (INCLUDED_FROM (line_table, m));

      path f (m->to_file);
      f.complete ();
      f.normalize ();

      include_map::iterator it (imap.find (f));

      if (it != imap.end ())
        it->second[i] = include_directive ();
    }

    //
    //
    file_map fmap;

    for (include_map::iterator i (imap.begin ()), e (imap.end ()); i != e; ++i)
    {
      /*
      cerr << endl
           << i->first << " included from" << endl;

      for (includes::iterator j (i->second.begin ());
           j != i->second.end (); ++j)
      {
        line_map const* lm (j->first);
        cerr << '\t' << lm->to_file << ":" << LAST_SOURCE_LINE (lm) << endl;
      }
      */

      // First see if there is an include from the main file. If so, then
      // it is preferred over all others. Use the first one if there are
      // several.
      //
      line_map const* main_lm (0);
      include_directive* main_inc (0);

      for (includes::iterator j (i->second.begin ());
           j != i->second.end (); ++j)
      {
        line_map const* lm (j->first);

        if (MAIN_FILE_P (lm))
        {
          if (main_lm == 0 ||
              LAST_SOURCE_LINE (main_lm) > LAST_SOURCE_LINE (lm))
          {
            main_lm = lm;
            main_inc = &j->second;
          }
        }
      }

      if (main_lm != 0)
      {
        string f (main_lm->to_file);
        size_t n (f.size ());

        // Check if this is a synthesized fragment.
        //
        if (!(n != 0 && f[0] == '<' && f[n - 1] == '>'))
        {
          path p (f);
          p.complete ();
          p.normalize ();
          f = p.string ();
        }

        fmap[f][LAST_SOURCE_LINE (main_lm)] = main_inc;
        continue;
      }

      // Otherwise, add all entries.
      //
      for (includes::iterator j (i->second.begin ());
           j != i->second.end (); ++j)
      {
        line_map const* lm (j->first);

        string f (lm->to_file);
        size_t n (f.size ());

        // Check if this is a synthesized fragment.
        //
        if (!(n != 0 && f[0] == '<' && f[n - 1] == '>'))
        {
          path p (f);
          p.complete ();
          p.normalize ();
          f = p.string ();
        }

        fmap[f][LAST_SOURCE_LINE (lm)] = &j->second;
      }
    }

    //
    //
    include_parser ip (ctx.options);

    for (file_map::iterator i (fmap.begin ()), e (fmap.end ()); i != e; ++i)
    {
      ip.parse_file (i->first, i->second);
    }

    // Finally, output the include directives.
    //
    for (include_map::const_iterator i (imap.begin ()), e (imap.end ());
         i != e; ++i)
    {
      includes const& is (i->second);
      include_directive const* inc (0);

      if (is.size () == 1)
      {
        inc = &is.begin ()->second;
      }
      else
      {
        include_set set;

        for (includes::const_iterator j (i->second.begin ());
             j != i->second.end (); ++j)
        {
          if (!j->second.path_.empty ())
            set.insert (&j->second);
        }

        assert (set.size () > 0);
        inc = *set.rbegin ();
      }

      path f (inc->path_.base ());
      f += ctx.options.odb_file_suffix ();
      f += ctx.options.hxx_suffix ();

      char o (inc->type_ == include_directive::quote ? '"' : '<');
      ctx.os << "#include " << ctx.process_include_path (
        f.string (), false, o) << endl
             << endl;
    }
  }
}