remove_constants.pl 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env perl
  2. # This script is a hack. It identifies things which it believes to be
  3. # constant, then replaces them throughout the code.
  4. #
  5. # Constants are identified as properties declared in object notation
  6. # with values consisting only of capital letters and underscores. If
  7. # the first character is an underscore, the constant is private, and
  8. # can be removed entirely.
  9. #
  10. # The script dies if any two constants have the same property name but
  11. # different values.
  12. my $script = join '', <>;
  13. # remove comments
  14. $script =~ s=/\*([^\*]|\*+[^\/])*\*/==g;
  15. $script =~ s=//.*==g;
  16. sub preserve {
  17. my $stuff = shift;
  18. $stuff =~ s/,//;
  19. return $stuff;
  20. }
  21. my %constants = ();
  22. sub add_constant {
  23. my ($name, $value) = @_;
  24. if (defined $constants{$name} && $constants{$name} ne $value) {
  25. print STDERR "variant constant $name = $value";
  26. die;
  27. } else {
  28. $constants{$name} = $value;
  29. #print STDERR "constant: $name = $value\n";
  30. }
  31. }
  32. # find private constants
  33. while ($script =~
  34. s/([,\{]) \s* # indicator that this is part of an object
  35. (_[A-Z0-9_]+) \s* : \s* # all-caps variable name beginning with _
  36. (\d+|0x[0-9A-Fa-f]+) \s* # numeric value
  37. ([,\}]) # next part of object
  38. /preserve "$1$4"/ex) {
  39. add_constant $2, $3;
  40. }
  41. my $script2 = '';
  42. # find public constants
  43. while ($script =~
  44. s/^(.*?) # beginning of script
  45. ([,\{]) \s* # indicator that this is part of an object
  46. ([A-Z0-9_]+) \s* : \s* # all-caps variable name
  47. (\d+|0x[0-9A-Fa-f]+) \s* # numeric value
  48. ([,\}]) # next part of object([,\{]) \s*
  49. /$5/esx) {
  50. $script2 .= "$1$2$3:$4";
  51. add_constant $3, $4;
  52. }
  53. $script = "$script2$script";
  54. foreach (keys %constants) {
  55. my $value = $constants{$_};
  56. $script =~ s/(?:[a-zA-Z0-9_]+\.)+$_(?=[^a-zA-Z0-9_])/$value/g;
  57. }
  58. print $script;