Codebase list swi-prolog / upstream/8.1.30+dfsg src / pl-srcfile.c
upstream/8.1.30+dfsg

Tree @upstream/8.1.30+dfsg (Download .tar.gz)

pl-srcfile.c @upstream/8.1.30+dfsgraw · history · blame

   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
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
/*  Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        J.Wielemaker@vu.nl
    WWW:           http://www.swi-prolog.org
    Copyright (c)  2014-2020, VU University Amsterdam
			      CWI, Amsterdam
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the
       distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

/*#define O_DEBUG 1*/
#include "pl-incl.h"
#include "pl-dbref.h"
#include "pl-event.h"
#include "pl-tabling.h"

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Source administration. The core object is  SourceFile, which keeps track
of procedures that are defined by it.  Source files are identified by an
unsigned int, which is registered with clauses and procedures.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#undef LD
#define LD LOCAL_LD


static void
putSourceFileArray(size_t where, SourceFile sf)
{ int idx = MSB(where);

  if ( !GD->files.array.blocks[idx] )
  { PL_LOCK(L_MISC);
    if ( !GD->files.array.blocks[idx] )
    { size_t bs = (size_t)1<<idx;
      SourceFile *newblock;

      if ( !(newblock=PL_malloc_uncollectable(bs*sizeof(SourceFile))) )
	outOfCore();

      memset(newblock, 0, bs*sizeof(SourceFile));
      GD->files.array.blocks[idx] = newblock-bs;
    }
    PL_UNLOCK(L_MISC);
  }

  GD->files.array.blocks[idx][where] = sf;
}


static void
registerSourceFile(SourceFile sf)	/* locked by lookupSourceFile() */
{ size_t index;
  int i;
  int last = FALSE;

  if ( GD->files.no_hole_before == 0 )
    GD->files.no_hole_before = 1;

  for(index=GD->files.no_hole_before, i=MSB(index); !last; i++)
  { size_t upto = (size_t)2<<i;
    SourceFile *b = GD->files.array.blocks[i];

    if ( upto >= GD->files.highest )
    { upto = GD->files.highest;
      last = TRUE;
    }

    for(; index<upto; index++)
    { if ( b[index] == NULL )
      { sf->index = index;
	b[index] = sf;
	GD->files.no_hole_before = index+1;

	return;
      }
    }
  }

  GD->files.no_hole_before = index+1;
  sf->index = index;
  if ( (size_t)sf->index != index )
    fatalError("Too many (%d) source files", index);
  putSourceFileArray(index, sf);
  GD->files.highest = index+1;
}


size_t
highSourceFileIndex(void)
{ return GD->files.highest;
}


SourceFile
indexToSourceFile(int index)
{ if ( index > 0 && index < GD->files.highest )
  { int idx = MSB(index);

    return GD->files.array.blocks[idx][index];
  }

  return NULL;
}


static void
freeList(ListCell *lp)
{ ListCell c;

  if ( (c=*lp) )
  { ListCell n;

    *lp = NULL;
    for( ; c; c=n )
    { n = c->next;

      freeHeap(c, sizeof(*c));
    }
  }
}


static void
unallocSourceFile(SourceFile sf)
{ if ( sf->magic == SF_MAGIC_DESTROYING )
  { sf->magic = 0;
    freeList(&sf->procedures);
    freeList(&sf->modules);
#ifdef O_PLMT
    if ( sf->mutex )
      freeSimpleMutex(sf->mutex);
#endif
    freeHeap(sf, sizeof(*sf));
  }
}


static void
freeSymbolSourceFile(void *name, void *value)
{ SourceFile sf = value;

  if ( sf->magic == SF_MAGIC )
    sf->magic = SF_MAGIC_DESTROYING;
  unallocSourceFile(sf);
}


static void
cleanupSourceFileArray(void)
{ int i;
  SourceFile *ap0;

  for(i=0; (ap0=GD->files.array.blocks[i]); i++)
  { size_t bs = (size_t)1<<i;

    ap0 += bs;
    GD->files.array.blocks[i] = NULL;
    PL_free(ap0);
  }
}


void
cleanupSourceFiles(void)
{ Table t;

  if ( (t=GD->files.table) )
  { GD->files.table = NULL;

    destroyHTable(t);
  }

  cleanupSourceFileArray();
}


static bool
clearSourceAdmin(SourceFile sf)
{ GET_LD
  int rc = FALSE;

  if ( sf->magic == SF_MAGIC )
  { fid_t fid = PL_open_foreign_frame();
    term_t name = PL_new_term_ref();
    static predicate_t pred = NULL;

    if ( !pred )
      pred = PL_predicate("$clear_source_admin", 1, "system");

    PL_put_atom(name, sf->name);
    rc = PL_call_predicate(MODULE_system, PL_Q_NORMAL, pred, name);

    PL_discard_foreign_frame(fid);
  }

  return rc;
}


int
destroySourceFile(SourceFile sf)
{ DEBUG(MSG_SRCFILE,
	Sdprintf("Destroying source file %s\n", PL_atom_chars(sf->name)));

  clearSourceAdmin(sf);

  PL_LOCK(L_SRCFILE);
  if ( sf->magic == SF_MAGIC )
  { SourceFile f;

    sf->magic = SF_MAGIC_DESTROYING;
    f = deleteHTable(GD->files.table, (void*)sf->name);
    assert(f);
    PL_unregister_atom(sf->name);
    putSourceFileArray(sf->index, NULL);
    if ( GD->files.no_hole_before > sf->index )
      GD->files.no_hole_before = sf->index;
  }
  PL_UNLOCK(L_SRCFILE);

  unallocSourceFile(sf);

  return TRUE;
}


static SourceFile
lookupSourceFile_unlocked(atom_t name, int create)
{ GET_LD
  SourceFile file;

  if ( !GD->files.table )
  { GD->files.table = newHTable(32);
    GD->files.table->free_symbol = freeSymbolSourceFile;
    GD->files.no_hole_before = 1;
  }

  if ( !(file=lookupHTable(GD->files.table, (void*)name)) &&
       create )
  { file = allocHeapOrHalt(sizeof(*file));
    memset(file, 0, sizeof(*file));

    file->name       = name;
    file->system     = GD->bootsession;
    file->from_state = GD->bootsession;
    file->resource   = GD->bootsession;
#ifdef O_PLMT
    file->mutex    = allocSimpleMutex(PL_atom_chars(name));
#endif
    file->magic    = SF_MAGIC;
    PL_register_atom(file->name);
    registerSourceFile(file);

    addNewHTable(GD->files.table, (void*)name, file);
  }

  return file;
}


SourceFile
lookupSourceFile(atom_t name, int create)
{ SourceFile sf;

  PL_LOCK(L_SRCFILE);
  sf = lookupSourceFile_unlocked(name, create);
  PL_UNLOCK(L_SRCFILE);

  return sf;
}


int
hasProcedureSourceFile(SourceFile sf, Procedure proc)
{ ListCell cell;

  if ( true(proc->definition, FILE_ASSIGNED) )
  { for(cell=sf->procedures; cell; cell = cell->next)
    { if ( cell->value == proc )
	succeed;
    }
  }

  fail;
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
addProcedureSourceFile(SourceFile, Procedure) associates a  procedure to
a source file. Note that  a  procedure   may  be  associated to multiple
source files.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

void
addProcedureSourceFile(SourceFile sf, Procedure proc)
{ LOCKSRCFILE(sf);
  if ( !hasProcedureSourceFile(sf, proc) )
  { ListCell cell;

    cell = allocHeapOrHalt(sizeof(struct list_cell));
    cell->value = proc;
    cell->next = sf->procedures;
    sf->procedures = cell;
    set(proc->definition, FILE_ASSIGNED);
    if ( !proc->source_no )
      proc->source_no = sf->index;
    else
      set(proc, PROC_MULTISOURCE);
  }
  UNLOCKSRCFILE(sf);
}


/* Add a module to the source file.  Note that we must add additional
   modules at the end because '$already_loaded'/4 assumes that the first
   module is the primary module of the file.
*/

int
addModuleSourceFile(SourceFile sf, Module m)
{ ListCell *cp, c2;
  int rc = TRUE;

  LOCKSRCFILE(sf);
  for(cp=&sf->modules; *cp; cp = &(*cp)->next)
  { ListCell cell = *cp;

    if ( cell->value == m )
      goto out;
  }

  if ( !(c2 = allocHeap(sizeof(struct list_cell))) )
  { rc = FALSE;			/* no memory */
    goto out;
  }
  c2->value = m;
  c2->next = NULL;
  *cp = c2;

out:
  UNLOCKSRCFILE(sf);
  return rc;
}


static int
delModuleSourceFile(SourceFile sf, Module m)
{ ListCell *cp, c;
  int rc = FALSE;

  LOCKSRCFILE(sf);
  for(cp=&sf->modules; (c=*cp); cp=&c->next)
  { if ( c->value == m )
    { *cp = c->next;
      freeHeap(c, sizeof(*c));

      rc = TRUE;
      break;
    }
  }
  UNLOCKSRCFILE(sf);

  return rc;
}


static void					/* requires LOCKSRCFILE(sf) */
delAllModulesSourceFile__unlocked(SourceFile sf)
{ ListCell c = sf->modules, n;

  sf->modules = NULL;

  for(; c; c = n)
  { Module m = c->value;

    n = c->next;
    if ( m->file == sf )
    { PL_LOCK(L_MODULE);
      m->file = NULL;
      m->line_no = 0;
      clearHTable(m->public);
      PL_UNLOCK(L_MODULE);
    }

    freeHeap(c, sizeof(*c));
  }
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Remove all links from sf to  m  module.   If  sf  becomes empty, we also
delete the source file.

(*) Although the system:$init_goal/3 clauses belong   to the file, we'll
consider a file holding only initialization goals empty.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

void
unlinkSourceFileModule(SourceFile sf, Module m)
{ GET_LD
  ListCell cell, next, prev = NULL;

  LOCKSRCFILE(sf);

  DEBUG(MSG_DESTROY_MODULE,
	Sdprintf("Cleaning %s\n", PL_atom_chars(sf->name)));

  for(cell=sf->procedures; cell; cell=next)
  { Procedure proc;
    Definition def;

    next = cell->next;
    proc = cell->value;
    def  = proc->definition;

    if ( lookupHTable(m->procedures, (void*)def->functor->functor) ||
	 PROCEDURE_dinit_goal->definition == def )	/* see (*) */
    { if ( sf->current_procedure == proc )
	sf->current_procedure = NULL;

      if ( prev )
	prev->next = cell->next;
      else
	sf->procedures = cell->next;
      freeHeap(cell, sizeof(*cell));
    } else
    { DEBUG(MSG_DESTROY_MODULE,
	    Sdprintf("  Keeping %s\n", procedureName(proc)));
      prev = cell;
    }
  }

  UNLOCKSRCFILE(sf);

  if ( !sf->procedures && !sf->modules )
  { DEBUG(MSG_DESTROY_MODULE,
	  Sdprintf("Destroying empty source file %s\n",
		   PL_atom_chars(sf->name)));
    destroySourceFile(sf);
  }
}


/** '$source_file'(:Head, -File) is semidet.
*/

static
PRED_IMPL("$source_file", 2, source_file, PL_FA_TRANSPARENT)
{ PRED_LD
  Procedure proc;
  SourceFile sf;

  term_t descr = A1;
  term_t file  = A2;

  if ( get_procedure(descr, &proc, 0, GP_FINDHERE) )
  { if ( isDefinedProcedure(proc) &&
	 (sf = indexToSourceFile(proc->source_no)) &&
	 sf->count > 0 )
      return PL_unify_atom(file, sf->name);
  }

  return FALSE;
}

/** '$source_file_predicates'(+File, -Heads:list(callable)) is semidet.
*/

static
PRED_IMPL("$source_file_predicates", 2, source_file_predicates, 0)
{ PRED_LD
  atom_t name;
  int rc = TRUE;
  SourceFile sf;

  term_t file = A1;

  PL_LOCK(L_SRCFILE);
  if ( PL_get_atom_ex(file, &name) &&
       (sf = lookupSourceFile_unlocked(name, FALSE)) &&
       sf->count > 0 )
  { term_t tail = PL_copy_term_ref(A2);
    term_t head = PL_new_term_ref();
    ListCell cell;

    LOCKSRCFILE(sf);
    for(cell=sf->procedures; rc && cell; cell = cell->next )
    { Procedure proc = cell->value;
      Definition def = proc->definition;

      rc = ( PL_unify_list(tail, head, tail) &&
	     unify_definition(MODULE_user, head, def, 0, GP_QUALIFY)
	   );
    }
    rc = (rc && PL_unify_nil(tail));
    UNLOCKSRCFILE(sf);
  } else
    rc = FALSE;
  PL_UNLOCK(L_SRCFILE);

  return rc;
}


static
PRED_IMPL("$time_source_file", 3, time_source_file, PL_FA_NONDETERMINISTIC)
{ PRED_LD
  int index;
  int mx = highSourceFileIndex();
  term_t file = A1;
  term_t time = A2;
  term_t type = A3;			/* user or system */
  fid_t fid;

  switch( CTX_CNTRL )
  { case FRG_FIRST_CALL:
      index = 0;
      break;
    case FRG_REDO:
      index = (int)CTX_INT;
      break;
    case FRG_CUTTED:
    default:
      succeed;
  }

  fid = PL_open_foreign_frame();
  for(; index < mx; index++)
  { SourceFile f = indexToSourceFile(index);

    if ( f == NULL || f->count == 0 )
      continue;

    if ( PL_unify_atom(file, f->name) &&
	 PL_unify_float(time, f->mtime) &&
	 PL_unify_atom(type, f->system ? ATOM_system : ATOM_user) )
    { PL_close_foreign_frame(fid);
      ForeignRedoInt(index+1);
    }

    PL_rewind_foreign_frame(fid);
  }

  PL_close_foreign_frame(fid);
  fail;
}


/** '$source_file_property'(+SrcFile, +Property, -Value) is semidet.
*/

static
PRED_IMPL("$source_file_property", 3, source_file_property, 0)
{ PRED_LD
  atom_t filename, property;
  SourceFile sf;

  if ( !PL_get_atom_ex(A1, &filename) ||
       !PL_get_atom_ex(A2, &property) )
    return FALSE;

  sf = lookupSourceFile(filename, FALSE);

  if ( property == ATOM_load_count )
    return PL_unify_integer(A3, sf ? sf->count : 0);
  if ( property == ATOM_reloading )
    return PL_unify_bool(A3, sf ? sf->reload != NULL : 0);
  if ( property == ATOM_number_of_clauses )
    return PL_unify_integer(A3, sf ? sf->number_of_clauses : 0);
  if ( property == ATOM_resource )
    return PL_unify_bool(A3, sf ? sf->resource : FALSE);
  if ( property == ATOM_from_state )
    return PL_unify_bool(A3, sf ? sf->from_state : FALSE);

  return PL_domain_error("source_file_property", A2);
}

static
PRED_IMPL("$set_source_file", 3, set_source_file, 0)
{ PRED_LD
  atom_t filename, property;
  SourceFile sf;

  if ( !PL_get_atom_ex(A1, &filename) ||
       !PL_get_atom_ex(A2, &property) )
    return FALSE;

  if ( (sf = lookupSourceFile(filename, FALSE)) )
  { if ( property == ATOM_resource )
    { int v;

      if ( PL_get_bool_ex(A3, &v) )
      { sf->resource = v;
	return TRUE;
      }
      return FALSE;
    } else
      return PL_domain_error("source_file_property", A2);
  } else
    return PL_existence_error("source_file", A1);

}

static
PRED_IMPL("$set_source_files", 1, set_source_files, 0)
{ PRED_LD
  atom_t prop;

  if ( !PL_get_atom_ex(A1, &prop) )
    return FALSE;
  if ( prop == ATOM_system || prop == ATOM_from_state )
  { int i, n;

    PL_LOCK(L_SRCFILE);
    n = highSourceFileIndex();
    for(i=1; i<n; i++)
    { SourceFile f = indexToSourceFile(i);

      if ( f )
      { if ( prop == ATOM_system )
	  f->system = TRUE;
	f->from_state = TRUE;
      }
    }
    PL_UNLOCK(L_SRCFILE);

    return TRUE;
  } else
    return PL_domain_error("source_property", A1);
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
unloadFile(SourceFile sf)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static int
unloadFile(SourceFile sf)
{ ListCell cell, next;
  size_t deleted = 0;
  int rc;

  delayEvents();
  LOCKSRCFILE(sf);
				      /* remove the clauses */
  for(cell = sf->procedures; cell; cell = cell->next)
  { Procedure proc = cell->value;
    Definition def = proc->definition;

    if ( false(def, P_FOREIGN|P_THREAD_LOCAL) )
    { deleted += removeClausesPredicate(
		     def, true(def, P_MULTIFILE) ? sf->index : 0, TRUE);
    }

    DEBUG(MSG_UNLOAD,
	  if ( false(def, P_MULTIFILE) && def->impl.clauses.number_of_clauses )
	    Sdprintf("%s: %d clauses after unload\n",
		     predicateName(def), def->impl.clauses.number_of_clauses));

    if ( false(def, P_MULTIFILE) )
    { clear(def, FILE_ASSIGNED);
      clear_meta_declaration(def);
    }
  }
  DEBUG(MSG_UNLOAD, Sdprintf("Removed %ld clauses\n", (long)deleted));

				      /* cleanup the procedure list */
  for(cell = sf->procedures; cell; cell = next)
  { next = cell->next;
    freeHeap(cell, sizeof(struct list_cell));
  }
  sf->procedures = NULL;

  delAllModulesSourceFile__unlocked(sf);
  UNLOCKSRCFILE(sf);

  rc = sendDelayedEvents(TRUE) >= 0;
  pl_garbage_collect_clauses();

  return rc;
}


/** '$unload_file'(+Name) is det.

Remove all traces of a loaded file.
*/

static
PRED_IMPL("$unload_file", 1, unload_file, 0)
{ PRED_LD
  SourceFile sf;
  atom_t name;

  if ( !PL_get_atom_ex(A1, &name) )
    return FALSE;

  if ( (sf = lookupSourceFile(name, FALSE)) )
  { ListCell mc, mcn;

    if ( sf->system )
      return PL_error(NULL, 0, NULL, ERR_PERMISSION,
		      ATOM_unload, ATOM_file, A1);

    if ( !unloadFile(sf) )
      return FALSE;

    for(mc=sf->modules; mc; mc=mcn)
    { Module m = mc->value;

      mcn = mc->next;
      LOCKMODULE(m);
      m->file = NULL;
      m->line_no = 0;
      delModuleSourceFile(sf, m);
      clearHTable(m->public);
      setSuperModule(m, MODULE_user);
      UNLOCKMODULE(m);
    }

    destroySourceFile(sf);
  }

  return TRUE;
}


		 /*******************************
		 *	    RECONSULT		*
		 *******************************/

static void	fix_discontiguous(p_reload *r);
static void	fix_metapredicate(p_reload *r);

#ifdef O_PLMT
#define GEN_RELOAD (GEN_MAX-PL_thread_self())
#else
#define GEN_RELOAD (GEN_MAX-1)
#endif

static int
startReconsultFile(SourceFile sf)
{ GET_LD
  sf_reload *r;

  DEBUG(MSG_RECONSULT, Sdprintf("Reconsult %s ...\n", sourceFileName(sf)));

  if ( (r = allocHeap(sizeof(*sf->reload))) )
  { ListCell cell;

    memset(r, 0, sizeof(*r));
    r->procedures        = newHTable(16);
    r->reload_gen        = GEN_RELOAD;
    r->pred_access_count = popNPredicateAccess(0);
    sf->reload = r;

    LD->gen_reload = r->reload_gen;

    for(cell = sf->procedures; cell; cell = cell->next)
    { Procedure proc = cell->value;
      Definition def = proc->definition;
      ClauseRef c;

      if ( false(def, P_FOREIGN|P_THREAD_LOCAL) )
      { acquire_def(def);
	for(c = def->impl.clauses.first_clause; c; c = c->next)
	{ Clause cl = c->value.clause;

	  if ( !GLOBALLY_VISIBLE_CLAUSE(cl, global_generation()) ||
	       true(cl, CL_ERASED) )
	    continue;
	  if ( true(def, P_MULTIFILE) && cl->owner_no != sf->index )
	    continue;
	  if ( true(def, P_DYNAMIC) && cl->owner_no == 0 )
	    continue;

	  cl->generation.erased = r->reload_gen;
	}
	release_def(def);
      }
      if ( true(def, P_AUTOLOAD) )
      { clear(def, P_AUTOLOAD);			/* should be be more selective? */
      }
    }

    return TRUE;
  }

  return PL_no_memory();
}


static ClauseRef
find_clause(ClauseRef cref, gen_t generation)
{ for(; cref; cref = cref->next)
  { if ( GLOBALLY_VISIBLE_CLAUSE(cref->value.clause, generation) )
      break;
  }

  return cref;
}


static void
advance_clause(p_reload *r ARG_LD)
{ ClauseRef cref;

  if ( (cref = r->current_clause) )
  { acquire_def(r->predicate);
    for(cref = cref->next; cref; cref = cref->next)
    { if ( GLOBALLY_VISIBLE_CLAUSE(cref->value.clause, r->generation) )
	break;
    }
    release_def(r->predicate);
    r->current_clause = cref;
  }
}


static void
copy_clause_source(Clause dest, Clause src)
{ dest->source_no = src->source_no;
  dest->owner_no  = src->owner_no;
  dest->line_no   = src->line_no;
}


static ClauseRef
keep_clause(p_reload *r, Clause clause ARG_LD)
{ ClauseRef cref = r->current_clause;
  Clause keep = cref->value.clause;

  keep->generation.erased = GEN_MAX;
  copy_clause_source(keep, clause);
  freeClause(clause);
  advance_clause(r PASS_LD);

  return cref;
}


static int
equal_clause(Clause cl1, Clause cl2)
{ if ( cl1->code_size == cl2->code_size )
  { size_t bytes = (size_t)cl1->code_size * sizeof(code);

    return memcmp(cl1->codes, cl2->codes, bytes) == 0;
  }

  return FALSE;
}


int
reloadHasClauses(SourceFile sf, Procedure proc ARG_LD)
{ p_reload *reload;

  if ( sf->reload && (reload=lookupHTable(sf->reload->procedures, proc)) )
  { return reload->number_of_clauses > 0;
  }

  return FALSE;
}


int
isRedefinedProcedure(Procedure proc, gen_t gen)
{ GET_LD
  Definition def = proc->definition;
  ClauseRef c;
  int ret = FALSE;

  acquire_def(def);
  for(c = def->impl.clauses.first_clause; c; c = c->next)
  { Clause cl = c->value.clause;
    if ( GLOBALLY_VISIBLE_CLAUSE(cl, gen) )
    { ret = TRUE;
      break;
    }
  }
  release_def(def);

  return ret;
}


static p_reload *
reloadContext(SourceFile sf, Procedure proc ARG_LD)
{ p_reload *reload;

  if ( !(reload = lookupHTable(sf->reload->procedures, proc)) )
  { Definition def = proc->definition;

    if ( !(reload = allocHeap(sizeof(*reload))) )
    { PL_no_memory();
      return NULL;
    }
    memset(reload, 0, sizeof(*reload));
    reload->predicate = def;
    if ( true(def, P_THREAD_LOCAL|P_FOREIGN) )
    { set(reload, P_NO_CLAUSES);
    } else if ( isRedefinedProcedure(proc, global_generation()) )
    { reload->generation = pushPredicateAccess(def);
      acquire_def(def);
      reload->current_clause = find_clause(def->impl.clauses.first_clause,
					   reload->generation);
      release_def(def);
    } else
    { set(reload, P_NEW);
    }
    addNewHTable(sf->reload->procedures, proc, reload);
    DEBUG(MSG_RECONSULT_PRED,
	  Sdprintf("%s %s ...\n",
		   true(reload, P_NEW)        ? "New"   :
		   true(reload, P_NO_CLAUSES) ? "Alien" :
					        "Reload",
		   predicateName(def)));
  }

  return reload;
}


ClauseRef
assertProcedureSource(SourceFile sf, Procedure proc, Clause clause ARG_LD)
{ if ( sf && sf->reload )
  { p_reload *reload;
    Definition def = proc->definition;
    ClauseRef cref;

    assert(proc == sf->current_procedure);

    sf->reload->number_of_clauses++;

    if ( !(reload = reloadContext(sf, proc PASS_LD)) )
    { freeClause(clause);
      return NULL;
    }

    if ( reload->number_of_clauses++ == 0 )
      fix_discontiguous(reload);

    if ( true(reload, P_NEW|P_NO_CLAUSES) )
      return assertProcedure(proc, clause, CL_END PASS_LD);

    if ( (cref = reload->current_clause) )
    { ClauseRef cref2;

      if ( equal_clause(cref->value.clause, clause) )
      { DEBUG(MSG_RECONSULT_CLAUSE,
	      Sdprintf("  Keeping clause %d\n",
		       clauseNo(cref->value.clause, reload->generation)));
	return keep_clause(reload, clause PASS_LD);
      }

      set(reload, P_MODIFIED);

      acquire_def(def);
      for(cref2 = cref->next; cref2; cref2 = cref2->next)
      { Clause c2 = cref2->value.clause;

	if ( !GLOBALLY_VISIBLE_CLAUSE(c2, reload->generation) )
	  continue;
	if ( true(def, P_MULTIFILE) && c2->owner_no != sf->index )
	  continue;

	if ( equal_clause(c2, clause) )
	{ ClauseRef del;

	  for(del = cref; del != cref2; del = del->next)
	  { Clause c = del->value.clause;

	    if ( !GLOBALLY_VISIBLE_CLAUSE(c, reload->generation) ||
		 true(c, CL_ERASED) )
	      continue;
	    if ( true(def, P_MULTIFILE) && c->owner_no != sf->index )
	      continue;

	    DEBUG(MSG_RECONSULT_CLAUSE,
		  Sdprintf("  Deleted clause %d\n",
			   clauseNo(c, reload->generation)));
	  }
	  release_def(def);

	  reload->current_clause = cref2;
	  DEBUG(MSG_RECONSULT_CLAUSE,
		Sdprintf("  Keeping clause %d\n",
			 clauseNo(cref2->value.clause, reload->generation)));
	  return keep_clause(reload, clause PASS_LD);
	}
      }
      release_def(def);

      DEBUG(MSG_RECONSULT_CLAUSE,
	    Sdprintf("  Inserted before clause %d\n",
		     clauseNo(cref->value.clause, reload->generation)));
      if ( (cref2 = assertProcedure(proc, clause, cref PASS_LD)) )
	cref2->value.clause->generation.created = sf->reload->reload_gen;

      return cref2;
    } else
    { if ( (cref = assertProcedure(proc, clause, CL_END PASS_LD)) )
	cref->value.clause->generation.created = sf->reload->reload_gen;
      DEBUG(MSG_RECONSULT_CLAUSE, Sdprintf("  Added at the end\n"));

      set(reload, P_MODIFIED);

      return cref;
    }
  } else if ( sf )
  { sf->number_of_clauses++;
  }

  return assertProcedure(proc, clause, CL_END PASS_LD);
}


static void
associateSource(SourceFile sf, Procedure proc)
{ Definition def = proc->definition;

  if ( false(def, FILE_ASSIGNED) )
  { GET_LD

    DEBUG(2, Sdprintf("Associating %s to %s (%p)\n",
		      predicateName(def), PL_atom_chars(source_file_name),
		      def));
    addProcedureSourceFile(sf, proc);

    if ( SYSTEM_MODE )
    { set(def, P_LOCKED|HIDE_CHILDS);
    } else
    { if ( truePrologFlag(PLFLAG_DEBUGINFO) )
	clear(def, HIDE_CHILDS);
      else
	set(def, HIDE_CHILDS);
    }
  }
}


#define P_ATEND	(P_VOLATILE|P_PUBLIC|P_ISO|P_NOPROFILE|P_NON_TERMINAL)

int
setAttrProcedureSource(SourceFile sf, Procedure proc,
		       unsigned attr, int val ARG_LD)
{ if ( val && (attr&PROC_DEFINED) )
    associateSource(sf, proc);

  if ( sf->reload )
  { p_reload *reload;

    if ( !(reload = reloadContext(sf, proc PASS_LD)) )
      return FALSE;

    if ( val )
      set(reload, attr);
    else
      clear(reload, attr);

    if ( (attr&(P_ATEND|P_TRANSPARENT)) )
      return TRUE;
  }

  return setAttrDefinition(proc->definition, attr, val);
}


static void
fix_attributes(SourceFile sf, Definition def, p_reload *r ARG_LD)
{ if ( false(def, P_MULTIFILE) )
    def->flags = (def->flags & ~P_ATEND) | (r->flags & P_ATEND);
  else
    def->flags |= (r->flags&P_ATEND);

  fix_metapredicate(r);
}


static void
fix_discontiguous(p_reload *r)
{ Definition def = r->predicate;

  if ( true(def, P_DISCONTIGUOUS) && false(r, P_DISCONTIGUOUS) )
    clear(def, P_DISCONTIGUOUS);
}


int
setMetapredicateSource(SourceFile sf, Procedure proc,
		       arg_info *args ARG_LD)
{ associateSource(sf, proc);

  if ( sf->reload )
  { p_reload *reload;
    size_t i, arity = proc->definition->functor->arity;

    if ( !(reload = reloadContext(sf, proc PASS_LD)) )
      return FALSE;

    if ( !reload->args )
      reload->args = allocHeapOrHalt(sizeof(*reload->args)*arity);
    for(i=0; i<arity; i++)
      reload->args[i].meta = args[i].meta;

    if ( isTransparentMetamask(proc->definition, args) )
      set(reload, P_TRANSPARENT);
    else
      clear(reload, P_TRANSPARENT);
    set(reload, P_META);
  } else
  { setMetapredicateMask(proc->definition, args);
  }

  return TRUE;
}


static int
equal_meta(Definition def, const arg_info *args)
{ if ( def->impl.any.args && args )
  { size_t i, arity = def->functor->arity;

    for(i=0; i<arity; i++)
    { if ( def->impl.any.args[i].meta != args[i].meta )
	return FALSE;
    }

    return TRUE;
  }

  return FALSE;
}

static void
fix_metapredicate(p_reload *r)
{ Definition def = r->predicate;

  if ( false(def, P_MULTIFILE) )
  { int mfmask = (P_META|P_TRANSPARENT);

    if ( (def->flags&mfmask) != (r->flags&mfmask) ||
	 !equal_meta(def, r->args) )
    { if ( true(def, P_META) && false(r, P_META) )
	clear_meta_declaration(def);
      else if ( true(r, P_META) )
	setMetapredicateMask(def, r->args);
      clear(def, P_TRANSPARENT);
      set(def, r->flags&P_TRANSPARENT);

      freeCodesDefinition(def, FALSE);
    }
  } else if ( true(r, P_META) )
  { setMetapredicateMask(def, r->args);
    freeCodesDefinition(def, FALSE);
  } else if ( true(r, P_TRANSPARENT) )
  { set(def, P_TRANSPARENT);
  }
}


void
registerReloadModule(SourceFile sf, Module module)
{ GET_LD
  m_reload *r;

  if ( sf->reload )
  { Table mt;

    if ( !(mt=sf->reload->modules) )
      mt = sf->reload->modules = newHTable(8);

    if ( !(r=lookupHTable(mt, module)) )
    { r = allocHeapOrHalt(sizeof(*r));
      memset(r, 0, sizeof(*r));
      addNewHTable(mt, module, r);
    }
  }
}


int
exportProcedureSource(SourceFile sf, Module module, Procedure proc)
{ GET_LD
  m_reload *r;

  if ( sf->reload && sf->reload->modules &&
       (r = lookupHTable(sf->reload->modules, module)) )
  { if ( !r->public )
      r->public = newHTable(8);
    updateHTable(r->public,
		 (void *)proc->definition->functor->functor,
		 proc);
  }

  return exportProcedure(module, proc);
}


static void
fix_module(Module m, m_reload *r)
{ GET_LD

  LOCKMODULE(m);
  for_table(m->public, n, v,
	    { if ( !r->public ||
		   !lookupHTable(r->public, n) )
	      { DEBUG(MSG_RECONSULT_MODULE,
		      Sdprintf("Delete export %s\n",
			       procedureName(v)));
		deleteHTable(m->public, n);
	      }
	    });
  UNLOCKMODULE(m);
}


static void
delete_old_predicate(SourceFile sf, Procedure proc)
{ Definition def = proc->definition;
  size_t deleted;

  if ( def->functor->functor == FUNCTOR_dtabled2 )
  { GET_LD
    ClauseRef c;

    acquire_def(def);
    for(c = def->impl.clauses.first_clause; c; c = c->next)
    { Clause cl = c->value.clause;

      if ( false(cl, CL_ERASED) &&
	   GLOBALLY_VISIBLE_CLAUSE(cl, global_generation()) )
	untable_from_clause(cl);
    }
    release_def(def);
  }

  deleted = removeClausesPredicate(
		def,
		true(def, P_MULTIFILE) ? sf->index : 0,
		TRUE);

  if ( false(def, P_MULTIFILE) )
  { clear(def, FILE_ASSIGNED);
    clear_meta_declaration(def);
    freeCodesDefinition(def, TRUE);
  }

  DEBUG(MSG_RECONSULT_PRED,
	Sdprintf("Deleted %ld clauses from predicate %s\n",
		 (long)deleted, predicateName(def)));

  (void)deleted;
}


static void
delete_old_predicates(SourceFile sf)
{ GET_LD
  ListCell cell, prev = NULL, next;

  for(cell = sf->procedures; cell; cell = next)
  { Procedure proc = cell->value;

    next = cell->next;

    if ( false(proc->definition, P_FOREIGN) &&
	 !lookupHTable(sf->reload->procedures, proc) )
    { delete_old_predicate(sf, proc);

      if ( prev )
	prev->next = cell->next;
      else
	sf->procedures = cell->next;
    } else
    { prev = cell;
    }
  }
}


static void
delete_pending_clauses(SourceFile sf, Definition def, p_reload *r ARG_LD)
{ ClauseRef cref;
  sf_reload *rl = sf->reload;

  acquire_def(def);
  for(cref = r->current_clause; cref; cref = cref->next)
  { Clause c = cref->value.clause;

    if ( !GLOBALLY_VISIBLE_CLAUSE(c, r->generation) ||
	 true(c, CL_ERASED) )
      continue;
    if ( true(r->predicate, P_MULTIFILE|P_DYNAMIC) && c->owner_no != sf->index )
      continue;

    if ( def->functor->functor == FUNCTOR_dtabled2 )
      untable_from_clause(c);

    c->generation.erased = rl->reload_gen;
    set(r, P_MODIFIED);
    DEBUG(MSG_RECONSULT_CLAUSE,
	  Sdprintf("  %s: deleted clause %d\n",
		   predicateName(def),
		   clauseNo(c, r->generation)));
  }
  release_def(def);
}


static size_t
end_reconsult_proc(SourceFile sf, Procedure proc, p_reload *r ARG_LD)
{ size_t dropped_access = 0;

  DEBUG(MSG_RECONSULT_CLAUSE,
	Sdprintf("Fixup %s\n", predicateName(proc->definition)));

  if ( false(r, P_NEW|P_NO_CLAUSES) )
  { Definition def = proc->definition;

    delete_pending_clauses(sf, def, r PASS_LD);
    fix_attributes(sf, def, r PASS_LD);
    reconsultFinalizePredicate(sf->reload, def, r PASS_LD);
  } else
  { dropped_access++;
    if ( true(r, P_NO_CLAUSES) )
    { Definition def = proc->definition;
      fix_attributes(sf, def, r PASS_LD);
    }
  }
  if ( r->args )
    freeHeap(r->args, 0);
  freeHeap(r, sizeof(*r));

  return dropped_access;
}


static int
endReconsult(SourceFile sf)
{ GET_LD
  sf_reload *reload;

  if ( (reload=sf->reload) )
  { size_t accessed_preds = reload->procedures->size;

    delayEvents();
    delete_old_predicates(sf);

    for_table(reload->procedures, n, v,
	      { Procedure proc = n;
		p_reload *r = v;

		accessed_preds -= end_reconsult_proc(sf, proc, r PASS_LD);
	      });

    popNPredicateAccess(accessed_preds);
    assert(reload->pred_access_count == popNPredicateAccess(0));
    destroyHTable(reload->procedures);

    if ( reload->modules )
    { for_table(reload->modules, n, v,
		{ Module m = n;
		  m_reload *r = v;

		  fix_module(m, r);
		  if ( r->public )
		    destroyHTable(r->public);
		  freeHeap(r, sizeof(*r));
		});
      destroyHTable(reload->modules);
    }

    sf->number_of_clauses = sf->reload->number_of_clauses;
    sf->reload = NULL;
    freeHeap(reload, sizeof(*reload));

    LD->gen_reload = GEN_INVALID;

    pl_garbage_collect_clauses();
    if ( sendDelayedEvents(TRUE) < 0 )
      return FALSE;
  }

  return TRUE;
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Flush the definition of proc in the   context  of (reloading) the source
file sf.  This performs the following steps:

  - If we have not seen the predicate, remove all clauses we may have
    for it and add as P_NEW.
  - If we have seen the predicate, perform the generation sync we would
    normally do at the end of the file and mark the predicate reload
    context as P_NEW.

`proc` is a predicate indicator. If it  is not qualified, it is resolved
against M in prolog_load_context(module, M).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static int
flush_procedure(SourceFile sf, Procedure proc)
{ GET_LD
  sf_reload *reload;

  if ( (reload=sf->reload) )
  { p_reload *r;

    if ( (r=lookupHTable(sf->reload->procedures, proc)) )
    { if ( false(r, P_NEW|P_NO_CLAUSES) )
      { Definition def = proc->definition;

	delete_pending_clauses(sf, def, r PASS_LD);
	fix_attributes(sf, def, r PASS_LD);
	reconsultFinalizePredicate(reload, def, r PASS_LD);
      }
    } else
    { delete_old_predicate(sf, proc);
      (void)reloadContext(sf, proc PASS_LD);
    }
  }

  return TRUE;
}


		 /*******************************
		 *	      CONSULT		*
		 *******************************/

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
startConsult(SourceFile sf)

This function is called when starting the consult a file. Its task is to
remove all clauses that come from this   file  if this is a *reconsult*.
There are two options.

    * Immediately remove the clauses from any non-referenced predicate.
    This saves space, but if there are multiple threads it may cause
    other threads to trap an undefined predicate.

    * Delay until garbage_collect_clauses/0
    This way other threads can happily keep running.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

int
startConsult(SourceFile f)
{ if ( f->count++ > 0 )			/* This is a re-consult */
  { if ( !startReconsultFile(f) )
      return FALSE;
  }

  f->current_procedure = NULL;
  return TRUE;
}


/** '$start_consult'(+Id, +Modified) is det.
*/

static
PRED_IMPL("$start_consult", 2, start_consult, 0)
{ PRED_LD
  atom_t name;
  double time;

  term_t file = A1;
  term_t modified = A2;

  if ( PL_get_atom_ex(file, &name) &&
       PL_get_float_ex(modified, &time) )
  { SourceFile f = lookupSourceFile(name, TRUE);

    f->mtime = time;
    startConsult(f);

    return TRUE;
  }

  return FALSE;
}


int
endConsult(SourceFile f)
{ f->current_procedure = NULL;
  return endReconsult(f);
}


static
PRED_IMPL("$end_consult", 1, end_consult, 0)
{ PRED_LD
  atom_t name;

  if ( PL_get_atom_ex(A1, &name) )
  { SourceFile sf;

    if ( (sf=lookupSourceFile(name, FALSE)) )
    { return endConsult(sf);
    }

    return TRUE;
  }

  return FALSE;
}



/** '$clause_from_source'(+Owner, +File, +Line, -Clause) is semidet.

True when Clause is the clause that contains  Line in File. Owner is the
source file owning Clause. For normal  files,   Owner  and  File are the
same. This predicate can find a clause in an included file by specifying
the main file as Owner and the included file as File.
*/

static
PRED_IMPL("$clause_from_source", 4, clause_from_source, 0)
{ PRED_LD
  atom_t owner_name;
  atom_t file_name;
  SourceFile of, sf;		/* owner file, source file */
  unsigned int source_no;
  int ln;
  ListCell cell;
  Clause c = NULL;

  term_t owner = A1;
  term_t file = A2;
  term_t line = A3;
  term_t clause = A4;

  if ( !PL_get_atom_ex(owner, &owner_name) ||
       !PL_get_atom_ex(file, &file_name) ||
       !(of = lookupSourceFile(owner_name, FALSE)) ||
       !PL_get_integer_ex(line, &ln) )
    return FALSE;

  if ( file_name == owner_name ) {
    source_no = of->index;
  } else {
    if ( !(sf=lookupSourceFile(file_name, FALSE)) )
      return FALSE;
    source_no = sf->index;
  }

  LOCKSRCFILE(of);
  for(cell = of->procedures; cell; cell = cell->next)
  { Procedure proc = cell->value;
    Definition def = proc->definition;

    if ( def && false(def, P_FOREIGN) )
    { ClauseRef cref;

      acquire_def(def);
      for(cref = def->impl.clauses.first_clause; cref; cref = cref->next )
      { Clause cl = cref->value.clause;

	if ( cl->source_no == source_no )
	{ if ( ln >= (int)cl->line_no )
	  { if ( !c || c->line_no < cl->line_no )
	      c = cl;
	  }
	}
      }
      release_def(def);
    }
  }
  UNLOCKSRCFILE(of);

  if ( c )
    return PL_unify_clref(clause, c);

  fail;
}

/** '$flush_predicate'(+Predicate, +File) is det.
 *
 * Finalize the definition of Predicate wrt. File. After this,
 * subsequent changes to the predicate are _immediate_.
 */

static int
flush_predicate(term_t pred ARG_LD)
{ SourceFile sf;
  Procedure proc;
  Module m = LD->modules.source;
  functor_t fdef;

  if ( ReadingSource )
    sf = lookupSourceFile(source_file_name, TRUE);
  else
    return TRUE;			/* not reading source; nothing to flush */

  if ( !get_functor(pred, &fdef, &m, 0, GF_PROCEDURE) )
    return FALSE;
  if ( (proc=isCurrentProcedure(fdef,m)) )
    return flush_procedure(sf, proc);

  return TRUE;
}


static
PRED_IMPL("$flush_predicate", 1, flush_predicate, 0)
{ PRED_LD

  return flush_predicate(A1 PASS_LD);
}


/** '$flushed_predicate'(:Head) is semidet.
 *
 * True when the finalized definition of Goal is defined.
 */

static
PRED_IMPL("$flushed_predicate", 1, flushed_predicate, 0)
{ PRED_LD
  SourceFile sf;
  term_t head = PL_new_term_ref();
  Module m = LD->modules.source;
  functor_t fdef;
  Procedure proc;

  if ( !PL_strip_module(A1, &m, head) )
    return FALSE;
  if ( !PL_get_functor(head, &fdef) )
    return PL_type_error("callable", A1);
  if ( !(proc=isCurrentProcedure(fdef, m)) )
    return FALSE;

  if ( ReadingSource )
    sf = lookupSourceFile(source_file_name, TRUE);
  else
    return isDefinedProcedure(proc);

  flush_procedure(sf, proc);
  return isDefinedProcedure(proc);
}


		 /*******************************
		 *      PUBLISH PREDICATES	*
		 *******************************/

#define  PL_FA_NONDET PL_FA_NONDETERMINISTIC

BeginPredDefs(srcfile)
  PRED_DEF("$source_file",		2, source_file,		     0)
  PRED_DEF("$source_file_predicates",	2, source_file_predicates,   0)
  PRED_DEF("$time_source_file",		3, time_source_file,    PL_FA_NONDET)
  PRED_DEF("$source_file_property",	3, source_file_property,     0)
  PRED_DEF("$set_source_file",          3, set_source_file,          0)
  PRED_DEF("$clause_from_source",	4, clause_from_source,	     0)
  PRED_DEF("$unload_file",		1, unload_file,		     0)
  PRED_DEF("$start_consult",		2, start_consult,	     0)
  PRED_DEF("$end_consult",		1, end_consult,		     0)
  PRED_DEF("$set_source_files",	        1, set_source_files,	     0)
  PRED_DEF("$flush_predicate",		1, flush_predicate,          0)
  PRED_DEF("$flushed_predicate",	1, flushed_predicate,	     0)
EndPredDefs