aboutsummaryrefslogtreecommitdiff
path: root/libbuild2/target.cxx
blob: 92db7e92970be761406f3cc24d34a7890a7f872f (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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
// file      : libbuild2/target.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <libbuild2/target.hxx>

#include <cstring> // strcmp()

#include <libbuild2/file.hxx>
#include <libbuild2/scope.hxx>
#include <libbuild2/search.hxx>
#include <libbuild2/algorithm.hxx>
#include <libbuild2/filesystem.hxx>
#include <libbuild2/diagnostics.hxx>

using namespace std;
using namespace butl;

namespace build2
{
  // target_type
  //
  bool target_type::
  is_a (const char* n) const
  {
    for (const target_type* b (this); b != nullptr; b = b->base)
      if (strcmp (b->name, n) == 0)
        return true;

    return false;
  }

  // target_key
  //
  void target_key::
  as_name (names& r) const
  {
    string v;
    if (!name->empty ())
    {
      v = *name;
      target::combine_name (v, ext, false /* @@ TODO: what to do? */);
    }
    else
      assert (!ext || ext->empty ()); // Unspecified or none.

    r.emplace_back (*dir, type->name, move (v));

    if (!out->empty ())
    {
      r.back ().pair = '@';
      r.emplace_back (*out);
    }
  }

  // target_state
  //
  static const char* const target_state_[] =
  {
    "<invalid>", // Absent/invalid (see target_state for details).
    "unknown",
    "unchanged",
    "postponed",
    "busy",
    "changed",
    "failed",
    "group"
  };

  string
  to_string (target_state ts)
  {
    return target_state_[static_cast<uint8_t> (ts)];
  }

  // target
  //
  const target::prerequisites_type target::empty_prerequisites_;

  target::
  ~target ()
  {
    clear_data ();
  }

  const string& target::
  ext (string v)
  {
    ulock l (ctx.targets.mutex_);

    // Once the extension is set, it is immutable. However, it is possible
    // that someone has already "branded" this target with a different
    // extension.
    //
    optional<string>& e (*ext_);

    if (!e)
      e = move (v);
    else if (*e != v)
    {
      string o (*e);
      l.unlock ();

      fail << "conflicting extensions '" << o << "' and '" << v << "' "
           << "for target " << *this;
    }

    return *e;
  }

  group_view target::
  group_members (action) const
  {
    assert (false); // Not a group or doesn't expose its members.
    return group_view {nullptr, 0};
  }

  const scope& target::
  base_scope () const
  {
    // If this target is from the src tree, use its out directory to find
    // the scope.
    //
    return ctx.scopes.find_out (out_dir ());
  }

  const scope& target::
  root_scope () const
  {
    // This is tricky to cache so we do the lookup for now.
    //
    const scope* r (base_scope ().root_scope ());
    assert (r != nullptr);
    return *r;
  }

  pair<lookup, size_t> target::
  lookup_original (const variable& var,
                   bool target_only,
                   const scope* bs) const
  {
    pair<lookup_type, size_t> r (lookup_type (), 0);

    ++r.second;
    {
      auto p (vars.lookup (var));
      if (p.first != nullptr)
        r.first = lookup_type (*p.first, p.second, vars);
    }

    const target* g1 (nullptr);
    const target* g2 (nullptr);

    if (!r.first)
    {
      ++r.second;

      // In case of an ad hoc group, we may have to look in two groups.
      //
      if ((g1 = group) != nullptr)
      {
        auto p (g1->vars.lookup (var));
        if (p.first != nullptr)
          r.first = lookup_type (*p.first, p.second, g1->vars);
        else
        {
          if ((g2 = g1->group) != nullptr)
          {
            auto p (g2->vars.lookup (var));
            if (p.first != nullptr)
              r.first = lookup_type (*p.first, p.second, g2->vars);
          }
        }
      }
    }

    // Delegate to scope's lookup_original().
    //
    if (!r.first)
    {
      if (!target_only)
      {
        target_key tk (key ());
        target_key g1k (g1 != nullptr ? g1->key () : target_key {});
        target_key g2k (g2 != nullptr ? g2->key () : target_key {});

        if (bs == nullptr)
          bs = &base_scope ();

        auto p (bs->lookup_original (var,
                                     &tk,
                                     g1 != nullptr ? &g1k : nullptr,
                                     g2 != nullptr ? &g2k : nullptr));

        r.first = move (p.first);
        r.second = r.first ? r.second + p.second : p.second;
      }
      else
        r.second = size_t (~0);
    }

    return r;
  }

  value& target::
  append (const variable& var)
  {
    // Note: see also prerequisite::append() if changing anything here.

    // Note that here we want the original value without any overrides
    // applied.
    //
    auto l (lookup_original (var).first);

    if (l.defined () && l.belongs (*this)) // Existing var in this target.
      return vars.modify (l); // Ok since this is original.

    value& r (assign (var)); // NULL.

    if (l.defined ())
      r = *l; // Copy value (and type) from the outer scope.

    return r;
  }

  pair<lookup, size_t> target::opstate::
  lookup_original (const variable& var, bool target_only) const
  {
    pair<lookup_type, size_t> r (lookup_type (), 0);

    ++r.second;
    {
      auto p (vars.lookup (var));
      if (p.first != nullptr)
        r.first = lookup_type (*p.first, p.second, vars);
    }

    // Delegate to target's lookup_original().
    //
    if (!r.first)
    {
      auto p (target_->lookup_original (var, target_only));

      r.first = move (p.first);
      r.second = r.first ? r.second + p.second : p.second;
    }

    return r;
  }

  optional<string> target::
  split_name (string& v, const location& loc)
  {
    assert (!v.empty ());

    // Normally, we treat the rightmost dot as an extension separator (but see
    // find_extension() for the exact semantics) and if none exists, then we
    // assume the extension is not specified. There are, however, special
    // cases that override this rule:
    //
    // - We treat triple dots as the "chosen extension separator" (used to
    //   resolve ambiguity as to which dot is the separator, for example,
    //   libfoo...u.a). If they are trailing triple dots, then this signifies
    //   the "unspecified (default) extension" (used when the extension in the
    //   name is not "ours", for example, cxx{foo.test...} for foo.test.cxx)
    //   Having multiple triple dots is illegal.
    //
    // - Otherwise, we treat a single trailing dot as the "specified no
    // - extension".
    //
    // - Finally, double dots are used as an escape sequence to make sure the
    //   dot is not treated as an extension separator (or as special by any of
    //   the above rules, for example, libfoo.u..a). In case of trailing
    //   double dots, we naturally assume there is no default extension.
    //
    // An odd number of dots other than one or three is illegal. This means,
    // in particular, that it's impossible to specify a base/extension pair
    // where either the base ends with a dot or the extension begins with one
    // (or both). We are ok with that.
    //
    // Dot-only sequences are illegal. Note though, that dir{.} and dir{..}
    // are handled ad hoc outside this function and are valid.

    // Note that we cannot unescape dots in-place before we validate the name
    // since it can be required for diagnostics. Thus, the plan is as follows:
    //
    // - Iterate right to left, searching for the extension dot, validating
    //   the name, and checking if any dots are escaped.
    //
    // - Split the name.
    //
    // - Unescape the dots in the name and/or extension, if required.

    // Search for an extension dot, validate the name, and check for escape
    // sequences.
    //
    optional<size_t> edp; // Extension dot position.
    size_t edn (0);       // Extension dot representation lenght (1 or 3).

    bool escaped (false);
    bool dot_only (true);
    size_t n (v.size ());

    // Iterate right to left until the beginning of the string or a directory
    // separator is encountered.
    //
    // At the end of the loop p will point to the beginning of the leaf.
    //
    size_t p (n - 1);

    for (;; --p)
    {
      char c (v[p]);

      if (c == '.')
      {
        // Find the first dot in the sequence.
        //
        size_t i (p);
        for (; i != 0 && v[i - 1] == '.'; --i) ;

        size_t sn (p - i + 1); // Sequence length.

        if (sn == 3)          // Triple dots?
        {
          if (edp && edn == 3)
            fail (loc) << "multiple triple dots in target name '" << v << "'";

          edp = i;
          edn = 3;
        }
        else if (sn == 1)     // Single dot?
        {
          if (!edp)
          {
            edp = i;
            edn = 1;
          }
        }
        else if (sn % 2 == 0) // Escape sequence?
          escaped = true;
        else
          fail (loc) << "invalid dot sequence in target name '" << v << "'";

        p = i; // Position to the first dot in the sequence.
      }
      else if (path::traits_type::is_separator (c))
      {
        // Position to the beginning of the leaf and bail out.
        //
        ++p;
        break;
      }
      else
        dot_only = false;

      if (p == 0)
        break;
    }

    if (dot_only)
      fail (loc) << "invalid target name '" << v << "'";

    // The leading dot cannot be an extension dot. Thus, the leading triple
    // dots are invalid and the leading single dot is not considered as such.
    //
    if (edp && *edp == p)
    {
      if (edn == 3)
        fail (loc) << "leading triple dots in target name '" << v << "'";

      edp = nullopt;
    }

    // Split the name.
    //
    optional<string> r;

    if (edp)
    {
      if (*edp != n - edn)          // Non-trailing dot?
        r = string (v, *edp + edn);
      else if (edn == 1)            // Trailing single dot?
        r = string ();
      //else if (edn == 3)          // Trailing triple dots?
      //  r = nullopt;

      v.resize (*edp);
    }
    else if (v.back () == '.')      // Trailing escaped dot?
      r = string ();

    if (!escaped)
      return r;

    // Unescape the dots.
    //
    auto unescape = [] (string& s, size_t b = 0)
    {
      size_t n (s.size ());
      for (size_t i (b); i != n; ++i)
      {
        if (s[i] == '.')
        {
          // Find the end of the dot sequence.
          //
          size_t j (i + 1);
          for (; j != n && s[j] == '.'; ++j) ;

          size_t sn (j - i); // Sequence length.

          // Multiple dots can only represent an escape sequence now.
          //
          if (sn != 1)
          {
            assert (sn % 2 == 0);

            size_t dn (sn / 2);   // Number of dots to remove.
            s.erase (i + dn, dn);

            i += dn - 1; // Position to the last dot in the sequence.
            n -= dn;     // Adjust string size counter.
          }
        }
      }
    };

    unescape (v, p);

    if (r)
      unescape (*r);

    return r;
  }

  // Escape the name according to the rules described in split_name(). The
  // idea is that we should be able to roundtrip things.
  //
  // Note though, that multiple representations can end up with the same
  // name, for example libfoo.u..a and libfoo...u.a. We will always resolve
  // ambiguity with the triple dot and only escape those dots that otherwise
  // can be misinterpreted (dot sequences, etc).
  //
  void target::
  combine_name (string& v, const optional<string>& e, bool de)
  {
    // Escape all dot sequences since they can be misinterpreted as escape
    // sequences and return true if the result contains an unescaped dot that
    // can potentially be considered an extension dot.
    //
    // In the name mode only consider the basename, escape the trailing dot
    // (since it can be misinterpreted as the 'no extension' case), and don't
    // treat the basename leading dot as the potential extension dot.
    //
    auto escape = [] (string& s, bool name) -> bool
    {
      if (s.empty ())
        return false;

      bool r (false);
      size_t n (s.size ());

      // Iterate right to left until the beginning of the string or a
      // directory separator is encountered.
      //
      for (size_t p (n - 1);; --p)
      {
        char c (s[p]);

        if (c == '.')
        {
          // Find the first dot in the sequence.
          //
          size_t i (p);
          for (; i != 0 && s[i - 1] == '.'; --i) ;

          size_t sn (p - i + 1); // Sequence length.

          bool esc (sn != 1); // Escape the sequence.
          bool ext (sn == 1); // An extension dot, potentially.

          if (name)
          {
            if (i == n - 1)
              esc = true;

            if (ext && (i == 0 || path::traits_type::is_separator (s[i - 1])))
              ext = false;
          }

          if (esc)
            s.insert (p + 1, sn, '.'); // Double them.

          if (ext)
            r = true;

          p = i; // Position to the first dot in the sequence.
        }
        else if (path::traits_type::is_separator (c))
        {
          assert (name);
          break;
        }

        if (p == 0)
          break;
      }

      return r;
    };

    bool ed (escape (v, true /* name */));

    if (v.back () == '.') // Name had (before escaping) trailing dot.
    {
      assert (e && e->empty ());
    }
    else if (e)
    {
      // Separate the name and extension with the triple dots if the extension
      // contains potential extension dots.
      //
      string ext (*e);
      v += escape (ext, false /* name */) ?  "..." : ".";
      v += ext; // Empty or not.
    }
    else if (de && ed)
      v += "...";
  }

  // include()
  //
  // See var_include documentation for details on what's going on here.
  //
  include_type
  include_impl (action a,
                const target& t,
                const prerequisite& p,
                const target* m,
                lookup* rl)
  {
    context& ctx (t.ctx);

    include_type r (include_type::normal);

    if (const string* v = cast_null<string> (p.vars[ctx.var_include]))
    {
      if      (*v == "false") r = include_type::excluded;
      else if (*v == "adhoc") r = include_type::adhoc;
      else if (*v == "true")  r = include_type::normal;
      else
        fail << "invalid " << *ctx.var_include << " variable value "
             << "'" << *v << "' specified for prerequisite " << p;
    }

    // Handle operation-specific override (see var_include documentation
    // for details).
    //
    lookup l;
    optional<bool> r1; // Absent means something other than true|false.

    names storage;
    names_view ns;
    const variable* current_ovar (nullptr);

    if (r != include_type::excluded)
    {
      current_ovar = a.outer ()
        ? ctx.current_outer_ovar
        : ctx.current_inner_ovar;

      if (current_ovar != nullptr && (l = p.vars[*current_ovar]))
      {
        // Maybe we should optimize this for the common cases (bool, path,
        // name)? But then again we don't expect many such overrides. Plus
        // will complicate the diagnostics below.
        //
        ns = reverse (*l, storage);

        if (ns.size () == 1)
        {
          const name& n (ns[0]);

          if (n.simple ())
          {
            const string& v (n.value);

            if (v == "false")
              r1 = false;
            else if (v == "true")
              r1 = true;
          }
        }

        if (r1 && !*r1)
          r = include_type::excluded;
      }
    }

    // Call the meta-operation override, if any (currently used by dist).
    //
    if (r != include_type::normal || l)
    {
      if (auto f = ctx.current_mif->include)
        r = f (a, t, prerequisite_member {p, m}, r, l);
    }

    if (l)
    {
      if (rl != nullptr)
        *rl = l;
      else if (!r1)
      {
        // Note: we have to delay this until the meta-operation callback above
        // had a chance to override it.
        //
        fail << "unrecognized " << *current_ovar << " variable value "
             << "'" << ns << "' specified for prerequisite " << p;
      }
    }

    return r;
  }

  // target_set
  //
  const target* target_set::
  find (const target_key& k, tracer& trace) const
  {
    slock sl (mutex_);
    map_type::const_iterator i (map_.find (k));

    if (i == map_.end ())
      return nullptr;

    const target& t (*i->second);
    optional<string>& ext (i->first.ext);

    if (ext != k.ext)
    {
      ulock ul; // Keep locked for trace.

      if (k.ext)
      {
        // To update the extension we have to re-lock for exclusive access.
        // Between us releasing the shared lock and acquiring unique the
        // extension could change and possibly a new target that matches the
        // key could be inserted. In this case we simply re-run find ().
        //
        sl.unlock ();
        ul = ulock (mutex_);

        if (ext) // Someone set the extension.
        {
          ul.unlock ();
          return find (k, trace);
        }
      }

      l5 ([&]{
          diag_record r (trace);
          r << "assuming target ";
          to_stream (r.os,
                     target_key {&t.type (), &t.dir, &t.out, &t.name, ext},
                     stream_verb_max); // Always print the extension.
          r << " is the same as the one with ";

          if (!k.ext)
            r << "unspecified extension";
          else if (k.ext->empty ())
            r << "no extension";
          else
            r << "extension " << *k.ext;
        });

      if (k.ext)
        ext = k.ext;
    }

    return &t;
  }

  pair<target&, ulock> target_set::
  insert_locked (const target_type& tt,
                 dir_path dir,
                 dir_path out,
                 string name,
                 optional<string> ext,
                 target_decl decl,
                 tracer& trace)
  {
    target_key tk {&tt, &dir, &out, &name, move (ext)};
    target* t (const_cast<target*> (find (tk, trace)));

    if (t == nullptr)
    {
      // We sometimes call insert() even if we expect to find an existing
      // target in order to keep the same code (see cc/search_library()).
      //
      assert (ctx.phase != run_phase::execute);

      optional<string> e (
        tt.fixed_extension != nullptr
        ? string (tt.fixed_extension (tk, nullptr /* root scope */))
        : move (tk.ext));

      t = tt.factory (ctx, tt, move (dir), move (out), move (name));

      // Re-lock for exclusive access. In the meantime, someone could have
      // inserted this target so emplace() below could return false, in which
      // case we proceed pretty much like find() except already under the
      // exclusive lock.
      //
      ulock ul (mutex_);

      auto p (map_.emplace (target_key {&tt, &t->dir, &t->out, &t->name, e},
                            unique_ptr<target> (t)));

      map_type::iterator i (p.first);

      if (p.second)
      {
        t->ext_ = &i->first.ext;
        t->decl = decl;
        t->state.inner.target_ = t;
        t->state.outer.target_ = t;
        return pair<target&, ulock> (*t, move (ul));
      }

      // The "tail" of find().
      //
      t = i->second.get ();
      optional<string>& ext (i->first.ext);

      if (ext != e)
      {
        l5 ([&]{
            diag_record r (trace);
            r << "assuming target ";
            to_stream (
              r.os,
              target_key {&t->type (), &t->dir, &t->out, &t->name, ext},
              stream_verb_max); // Always print the extension.
            r << " is the same as the one with ";

            if (!e)
              r << "unspecified extension";
            else if (e->empty ())
              r << "no extension";
            else
              r << "extension " << *e;
          });

        if (e)
          ext = e;
      }

      // Fall through (continue as if the first find() returned this target).
    }

    // Without resorting to something like atomic we can only upgrade the
    // declaration to real (which is expected to only happen during the load
    // phase).
    //
    if (decl == target_decl::real)
    {
      assert (ctx.phase == run_phase::load);

      if (t->decl != target_decl::real)
        t->decl = decl;
    }

    return pair<target&, ulock> (*t, ulock ());
  }

  static const optional<string> unknown_ext ("?");

  ostream&
  to_stream (ostream& os, const target_key& k, optional<stream_verbosity> osv)
  {
    stream_verbosity sv (osv ? *osv : stream_verb (os));
    uint16_t dv (sv.path);
    uint16_t ev (sv.extension);

    // If the name is empty, then we want to print the last component of the
    // directory inside {}, e.g., dir{bar/}, not bar/dir{}.
    //
    bool n (!k.name->empty ());

    // Note: relative() returns empty for './'.
    //
    const dir_path& rd (dv < 1 ? relative (*k.dir) : *k.dir); // Relative.
    const dir_path& pd (n ? rd : rd.directory ());            // Parent.

    if (!pd.empty ())
    {
      if (dv < 1)
        os << diag_relative (pd);
      else
        to_stream (os, pd, true /* representation */);
    }

    const target_type& tt (*k.type);

    os << tt.name << '{';

    if (n)
    {
      const optional<string>* ext (nullptr); // NULL or present.

      // If the extension derivation functions are NULL, then it means this
      // target type doesn't use extensions.
      //
      if (tt.fixed_extension != nullptr || tt.default_extension != nullptr)
      {
        // For verbosity level 0 we don't print the extension. For 1 we print
        // it if there is one. For 2 we print 'foo.?' if it hasn't yet been
        // assigned and 'foo.' if it is assigned as "no extension" (empty).
        //
        if (ev > 0 && (ev > 1 || (k.ext && !k.ext->empty ())))
        {
          ext = k.ext ? &k.ext : &unknown_ext;
        }
      }
      else
        assert (!k.ext || k.ext->empty ()); // Unspecified or none.

      // Escape dots in the name/extension to resolve potential ambiguity.
      //
      if (k.name->find ('.') == string::npos &&
          (ext == nullptr || (*ext)->find ('.') == string::npos))
      {
        os << *k.name;

        if (ext != nullptr)
          os << '.' << **ext;
      }
      else
      {
        string n (*k.name);
        target::combine_name (n,
                              ext != nullptr ? *ext : nullopt_string,
                              false /* default_extension */);
        os << n;
      }
    }
    else
      to_stream (os,
                 rd.empty () ? dir_path (".") : rd.leaf (),
                 true /* representation */);

    os << '}';

    // If this target is from src, print its out.
    //
    if (!k.out->empty ())
    {
      if (dv < 1)
      {
        // Don't print '@./'.
        //
        const string& o (diag_relative (*k.out, false));

        if (!o.empty ())
          os << '@' << o;
      }
      else
        os << '@' << *k.out;
    }

    return os;
  }

  ostream&
  operator<< (ostream& os, const target_key& k)
  {
    if (auto p = k.type->print)
      p (os, k);
    else
      to_stream (os, k, stream_verb (os));

    return os;
  }

  // mtime_target
  //
  timestamp mtime_target::
  mtime () const
  {
    // Figure out from which target we should get the value.
    //
    const mtime_target* t (this);

    switch (ctx.phase)
    {
    case run_phase::load: break;
    case run_phase::match:
      {
        // Similar logic to matched_state_impl().
        //
        const opstate& s (state[action () /* inner */]);

        // Note: already synchronized.
        size_t o (s.task_count.load (memory_order_relaxed) - ctx.count_base ());

        if (o != offset_applied && o != offset_executed)
          break;
      }
      // Fall through.
    case run_phase::execute:
      {
        if (group_state (action () /* inner */))
          t = &group->as<mtime_target> ();

        break;
      }
    }

    return timestamp (duration (t->mtime_.load (memory_order_consume)));
  }

  // path_target
  //
  const string* path_target::
  derive_extension (bool search, const char* de)
  {
    // See also search_existing_file() if updating anything here.

    // Should be no default extension if searching.
    //
    assert (!search || de == nullptr);

    // The target should use extensions and they should not be fixed.
    //
    assert (de == nullptr || type ().default_extension != nullptr);

    if (const string* p = ext ())
      // Note that returning by reference is now MT-safe since once the
      // extension is specified, it is immutable.
      //
      return p;
    else
    {
      optional<string> e;

      // If the target type has the default extension function then try that
      // first. The reason for preferring it over what's been provided by the
      // caller is that this function will often use the 'extension' variable
      // which the user can use to override extensions. But since we pass the
      // provided default extension, the target type can override this logic
      // (see the exe{} target type for a use case).
      //
      if (auto f = type ().default_extension)
        e = f (key (), base_scope (), de, search);

      if (!e)
      {
        if (de != nullptr)
          e = de;
        else
        {
          if (search)
            return nullptr;

          fail << "no default extension for target " << *this << endf;
        }
      }

      return &ext (move (*e));
    }
  }

  const path& path_target::
  derive_path (const char* de, const char* np, const char* ns, const char* ee)
  {
    return derive_path_with_extension (derive_extension (de), np, ns, ee);
  }

  const path& path_target::
  derive_path_with_extension (const string& e,
                              const char* np,
                              const char* ns,
                              const char* ee)
  {
    path_type p (dir);

    if (np == nullptr || np[0] == '\0')
      p /= name;
    else
    {
      p /= np;
      p += name;
    }

    if (ns != nullptr)
      p += ns;

    return derive_path_with_extension (move (p), e, ee);
  }

  const path& path_target::
  derive_path (path_type p, const char* de, const char* ee)
  {
    return derive_path_with_extension (move (p), derive_extension (de), ee);
  }

  const path& path_target::
  derive_path_with_extension (path_type p, const string& e, const char* ee)
  {
    if (!e.empty ())
    {
      p += '.';
      p += e;
    }

    if (ee != nullptr)
    {
      p += '.';
      p += ee;
    }

    return path (move (p));
  }

  // Search functions.
  //

  const target*
  target_search (const target& t, const prerequisite_key& pk)
  {
    // The default behavior is to look for an existing target in the
    // prerequisite's directory scope.
    //
    return search_existing_target (t.ctx, pk);
  }

  const target*
  file_search (const target& t, const prerequisite_key& pk)
  {
    // First see if there is an existing target.
    //
    if (const target* e = search_existing_target (t.ctx, pk))
      return e;

    // Then look for an existing file in the src tree.
    //
    return search_existing_file (t.ctx, pk);
  }

  extern const char target_extension_none_[] = "";

  const char*
  target_extension_none (const target_key& k, const scope* s)
  {
    return target_extension_fix<target_extension_none_> (k, s);
  }

  const char*
  target_extension_must (const target_key& tk, const scope*)
  {
    if (!tk.ext)
      fail << tk.type->name << " target " << tk << " must include extension";

    return tk.ext->c_str ();
  }

  void
  target_print_0_ext_verb (ostream& os, const target_key& k)
  {
    stream_verbosity sv (stream_verb (os));
    if (sv.extension == 1) sv.extension = 0; // Remap 1 to 0.
    to_stream (os, k, sv);
  }

  void
  target_print_1_ext_verb (ostream& os, const target_key& k)
  {
    stream_verbosity sv (stream_verb (os));
    if (sv.extension == 0) sv.extension = 1; // Remap 0 to 1.
    to_stream (os, k, sv);
  }

  // type info
  //

  const target_type target::static_type
  {
    "target",
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    &target_search,
    target_type::flag::none,
  };

  const target_type mtime_target::static_type
  {
    "mtime_target",
    &target::static_type,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    &target_search,
    target_type::flag::none
  };

  const target_type path_target::static_type
  {
    "path_target",
    &mtime_target::static_type,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    &target_search,
    target_type::flag::none
  };

  const target_type file::static_type
  {
    "file",
    &path_target::static_type,
    &target_factory<file>,
    &target_extension_none,
    nullptr, /* default_extension */
    nullptr, /* pattern */
    &target_print_1_ext_verb, // Print extension even at verbosity level 0.
    &file_search,
    target_type::flag::none
  };

  static const target*
  alias_search (const target& t, const prerequisite_key& pk)
  {
    // For an alias we don't want to silently create a target since it will do
    // nothing and it most likely not what the user intended.
    //
    const target* e (search_existing_target (t.ctx, pk));

    if (e == nullptr || e->decl != target_decl::real)
      fail << "no explicit target for " << pk;

    return e;
  }

  const target_type alias::static_type
  {
    "alias",
    &target::static_type,
    &target_factory<alias>,
    nullptr, // Extension not used.
    nullptr,
    nullptr,
    nullptr,
    &alias_search,
    target_type::flag::none
  };

  // dir
  //
  bool dir::
  check_implied (const scope& rs, const dir_path& d)
  {
    try
    {
      for (const dir_entry& e: dir_iterator (d, true /* ignore_dangling */))
      {
        switch (e.type ())
        {
        case entry_type::directory:
          {
            if (check_implied (rs, d / path_cast<dir_path> (e.path ())))
              return true;

            break;
          }
        case entry_type::regular:
          {
            if (e.path () == rs.root_extra->buildfile_file)
              return true;

            break;
          }
        default:
          break;
        }
      }
    }
    catch (const system_error& e)
    {
      fail << "unable to iterate over " << d << ": " << e << endf;
    }

    return false;
  }

  prerequisites dir::
  collect_implied (const scope& bs)
  {
    prerequisites_type r;
    const dir_path& d (bs.src_path ());

    try
    {
      for (const dir_entry& e: dir_iterator (d, true /* ignore_dangling */))
      {
        if (e.type () == entry_type::directory)
          r.push_back (
            prerequisite (nullopt,
                          dir::static_type,
                          dir_path (e.path ().representation ()), // Relative.
                          dir_path (), // In the out tree.
                          string (),
                          nullopt,
                          bs));
      }
    }
    catch (const system_error& e)
    {
      fail << "unable to iterate over " << d << ": " << e;
    }

    return r;
  }

  static const target*
  dir_search (const target& t, const prerequisite_key& pk)
  {
    tracer trace ("dir_search");

    // The first step is like in search_alias(): looks for an existing target.
    //
    const target* e (search_existing_target (t.ctx, pk));

    if (e != nullptr && e->decl == target_decl::real)
      return e;

    // If not found (or is implied), then try to load the corresponding
    // buildfile (which would normally define this target). Failed that, see
    // if we can assume an implied buildfile which would be equivalent to:
    //
    // ./: */
    //
    const scope& s (*pk.scope);
    const dir_path& d (*pk.tk.dir);

    // Note: this code is a custom version of parser::parse_include().

    // Calculate the new out_base. If the directory is absolute then we assume
    // it is already normalized.
    //
    dir_path out_base (d.relative ()
                       ? (s.out_path () / d).normalize ()
                       : d);

    // In our world modifications to the scope structure during search & match
    // should be "pure append" in the sense that they should not affect any
    // existing targets that have already been searched & matched.
    //
    // A straightforward way to enforce this is to not allow any existing
    // targets to be inside any newly created scopes (except, perhaps for the
    // directory target itself which we know hasn't been searched yet). This,
    // however, is not that straightforward to implement: we would need to
    // keep a directory prefix map for all the targets (e.g., in target_set).
    // Also, a buildfile could load from a directory that is not a
    // subdirectory of out_base. So for now we just assume that this is so.
    // And so it is.
    //
    bool retest (false);

    assert (t.ctx.phase == run_phase::match);
    {
      // Switch the phase to load.
      //
      phase_switch ps (t.ctx, run_phase::load);

      // This is subtle: while we were fussing around another thread may have
      // loaded the buildfile. So re-test now that we are in an exclusive
      // phase.
      //
      if (e == nullptr)
        e = search_existing_target (t.ctx, pk);

      if (e != nullptr && e->decl == target_decl::real)
        retest = true;
      else
      {
        // Ok, no luck, switch the scope.
        //
        // Note that we don't need to do anything for the project's
        // environment: source_once() will take care of it itself and
        // search_implied() is not affected.
        //
        pair<scope&, scope*> sp (
          switch_scope (*s.rw ().root_scope (), out_base));

        if (sp.second != nullptr) // Ignore scopes out of any project.
        {
          scope& base (sp.first);
          scope& root (*sp.second);

          const dir_path& src_base (base.src_path ());

          path bf (src_base / root.root_extra->buildfile_file);

          if (exists (bf))
          {
            l5 ([&]{trace << "loading buildfile " << bf << " for " << pk;});
            retest = source_once (root, base, bf);
          }
          else if (exists (src_base))
          {
            e = dir::search_implied (base, pk, trace);
            retest = (e != nullptr);
          }
        }
      }
    }

    assert (t.ctx.phase == run_phase::match);

    // If we loaded/implied the buildfile, examine the target again.
    //
    if (retest)
    {
      if (e == nullptr)
        e = search_existing_target (t.ctx, pk);

      if (e != nullptr && e->decl == target_decl::real)
        return e;
    }

    fail << "no explicit target for " << pk << endf;
  }

  static bool
  dir_pattern (const target_type&,
               const scope&,
               string& v,
               optional<string>&,
               const location&,
               bool r)
  {
    // Add/strip trailing directory separator unless already there.
    //
    bool d (path::traits_type::is_separator (v.back ()));

    if (r)
    {
      assert (d);
      v.resize (v.size () - 1);
    }
    else if (!d)
    {
      v += path::traits_type::directory_separator;
      return true;
    }

    return false;
  }

  const target_type dir::static_type
  {
    "dir",
    &alias::static_type,
    &target_factory<dir>,
    nullptr,              // Extension not used.
    nullptr,
    &dir_pattern,
    nullptr,
    &dir_search,
    target_type::flag::none
  };

  const target_type fsdir::static_type
  {
    "fsdir",
    &target::static_type,
    &target_factory<fsdir>,
    nullptr,              // Extension not used.
    nullptr,
    &dir_pattern,
    nullptr,
    &target_search,
    target_type::flag::none
  };

  static optional<string>
  exe_target_extension (const target_key&,
                        const scope&,
                        const char* e,
                        bool search)
  {
    // If we are searching for an executable that is not a target, then use
    // the host machine executable extension. Otherwise, if this is a target,
    // then we expect the rule to supply the target machine extension. But if
    // it doesn't, then fallback to no extension (e.g., a script).
    //
    return string (!search
                   ? (e != nullptr ? e : "")
                   :
#ifdef _WIN32
                   "exe"
#else
                   ""
#endif
    );
  }

#ifdef _WIN32
  static bool
  exe_target_pattern (const target_type&,
                      const scope&,
                      string& v,
                      optional<string>& e,
                      const location& l,
                      bool r)
  {
    if (r)
    {
      assert (e);
      e = nullopt;
    }
    else
    {
      e = target::split_name (v, l);

      if (!e)
      {
        e = "exe";
        return true;
      }
    }

    return false;
  }
#endif

  const target_type exe::static_type
  {
    "exe",
    &file::static_type,
    &target_factory<exe>,
    nullptr, /* fixed_extension */
    &exe_target_extension,
#ifdef _WIN32
    &exe_target_pattern,
#else
    nullptr,
#endif
    nullptr,
    &file_search,
    target_type::flag::none
  };

  static const char*
  buildfile_target_extension (const target_key& tk, const scope* root)
  {
    // If the name is the special 'buildfile', then there is no extension,
    // otherwise it is 'build' (or 'build2file' and 'build2' in the
    // alternative naming scheme).

    // Let's try hard not to need the root scope by trusting the extensions
    // we were given.
    //
    // BTW, one way to get rid of all this root scope complication is to
    // always require explicit extension specification for buildfiles. Since
    // they are hardly ever mentioned explicitly, this should probably be ok.
    //
    if (tk.ext)
      return tk.ext->c_str ();

    if (root == nullptr)
    {
      // The same login as in target::root_scope().
      //
      // Note: we are guaranteed the scope is never NULL for prerequisites
      // (where out/dir could be relative and none of this will work).
      //
      // @@ CTX TODO
#if 0
      root = scopes.find (tk.out->empty () ? *tk.dir : *tk.out).root_scope ();
#endif

      if (root == nullptr || root->root_extra == nullptr)
        fail << "unable to determine extension for buildfile target " << tk;
    }

    return *tk.name == root->root_extra->buildfile_file.string ()
      ? ""
      : root->root_extra->build_ext.c_str ();
  }

  static bool
  buildfile_target_pattern (const target_type&,
                            const scope& base,
                            string& v,
                            optional<string>& e,
                            const location& l,
                            bool r)
  {
    if (r)
    {
      assert (e);
      e = nullopt;
    }
    else
    {
      e = target::split_name (v, l);

      if (!e)
      {
        const scope* root (base.root_scope ());

        if (root == nullptr || root->root_extra == nullptr)
          fail (l) << "unable to determine extension for buildfile pattern";

        if (v != root->root_extra->buildfile_file.string ())
        {
          e = root->root_extra->build_ext;
          return true;
        }
      }
    }

    return false;
  }

  const target_type buildfile::static_type
  {
    "buildfile",
    &file::static_type,
    &target_factory<buildfile>,
    &buildfile_target_extension,
    nullptr, /* default_extension */
    &buildfile_target_pattern,
    nullptr,
    &file_search,
    target_type::flag::none
  };

  const target_type doc::static_type
  {
    "doc",
    &file::static_type,
    &target_factory<doc>,
    &target_extension_none,              // Same as file (no extension).
    nullptr, /* default_extension */
    nullptr, /* pattern */               // Same as file.
    &target_print_1_ext_verb,            // Same as file.
    &file_search,
    target_type::flag::none
  };

  const target_type legal::static_type
  {
    "legal",
    &doc::static_type,
    &target_factory<legal>,
    &target_extension_none,              // Same as file (no extension).
    nullptr, /* default_extension */
    nullptr, /* pattern */               // Same as file.
    &target_print_1_ext_verb,            // Same as file.
    &file_search,
    target_type::flag::none
  };

  const target_type man::static_type
  {
    "man",
    &doc::static_type,
    &target_factory<man>,
    &target_extension_must,   // Should be specified explicitly.
    nullptr, /* default_extension */
    nullptr,
    &target_print_1_ext_verb, // Print extension even at verbosity level 0.
    &file_search,
    target_type::flag::none
  };

  extern const char man1_ext[] = "1"; // VC14 rejects constexpr.

  const target_type man1::static_type
  {
    "man1",
    &man::static_type,
    &target_factory<man1>,
    &target_extension_fix<man1_ext>,
    nullptr,  /* default_extension */
    &target_pattern_fix<man1_ext>,
    &target_print_0_ext_verb, // Fixed extension, no use printing.
    &file_search,
    target_type::flag::none
  };

  static const char*
  manifest_target_extension (const target_key& tk, const scope*)
  {
    // If the name is special 'manifest', then there is no extension,
    // otherwise it is .manifest.
    //
    return *tk.name == "manifest" ? "" : "manifest";
  }

  static bool
  manifest_target_pattern (const target_type&,
                           const scope&,
                           string& v,
                           optional<string>& e,
                           const location& l,
                           bool r)
  {
    if (r)
    {
      assert (e);
      e = nullopt;
    }
    else
    {
      e = target::split_name (v, l);

      if (!e && v != "manifest")
      {
        e = "manifest";
        return true;
      }
    }

    return false;
  }

  const target_type manifest::static_type
  {
    "manifest",
    &doc::static_type,
    &target_factory<manifest>,
    &manifest_target_extension,
    nullptr, /* default_extension */
    &manifest_target_pattern,
    nullptr,
    &file_search,
    target_type::flag::none
  };
}