inheritance-ordering.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env node
  2. const path = require('path');
  3. const graphlib = require('graphlib');
  4. const { findAll } = require('solidity-ast/utils');
  5. const { _: artifacts } = require('yargs').argv;
  6. for (const artifact of artifacts) {
  7. const { output: solcOutput } = require(path.resolve(__dirname, '../..', artifact));
  8. const graph = new graphlib.Graph({ directed: true });
  9. const names = {};
  10. const linearized = [];
  11. for (const source in solcOutput.contracts) {
  12. if (['contracts-exposed/', 'contracts/mocks/'].some(pattern => source.startsWith(pattern))) {
  13. continue;
  14. }
  15. for (const contractDef of findAll('ContractDefinition', solcOutput.sources[source].ast)) {
  16. names[contractDef.id] = contractDef.name;
  17. linearized.push(contractDef.linearizedBaseContracts);
  18. contractDef.linearizedBaseContracts.forEach((c1, i, contracts) =>
  19. contracts.slice(i + 1).forEach(c2 => {
  20. graph.setEdge(c1, c2);
  21. }),
  22. );
  23. }
  24. }
  25. /// graphlib.alg.findCycles will not find minimal cycles.
  26. /// We are only interested int cycles of lengths 2 (needs proof)
  27. graph.nodes().forEach((x, i, nodes) =>
  28. nodes
  29. .slice(i + 1)
  30. .filter(y => graph.hasEdge(x, y) && graph.hasEdge(y, x))
  31. .forEach(y => {
  32. console.log(`Conflict between ${names[x]} and ${names[y]} detected in the following dependency chains:`);
  33. linearized
  34. .filter(chain => chain.includes(parseInt(x)) && chain.includes(parseInt(y)))
  35. .forEach(chain => {
  36. const comp = chain.indexOf(parseInt(x)) < chain.indexOf(parseInt(y)) ? '>' : '<';
  37. console.log(`- ${names[x]} ${comp} ${names[y]} in ${names[chain.find(Boolean)]}`);
  38. // console.log(`- ${names[x]} ${comp} ${names[y]}: ${chain.reverse().map(id => names[id]).join(', ')}`);
  39. });
  40. process.exitCode = 1;
  41. }),
  42. );
  43. }
  44. if (!process.exitCode) {
  45. console.log('Contract ordering is consistent.');
  46. }