srcpos.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright 2007 Jon Loeliger, Freescale Semiconductor, Inc.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 2 of the
  7. * License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  17. * USA
  18. */
  19. #include "dtc.h"
  20. #include "srcpos.h"
  21. /*
  22. * Record the complete unique set of opened file names.
  23. * Primarily used to cache source position file names.
  24. */
  25. #define MAX_N_FILE_NAMES (100)
  26. const char *file_names[MAX_N_FILE_NAMES];
  27. static int n_file_names = 0;
  28. /*
  29. * Like yylineno, this is the current open file pos.
  30. */
  31. int srcpos_filenum = -1;
  32. FILE *dtc_open_file(const char *fname)
  33. {
  34. FILE *f;
  35. if (lookup_file_name(fname, 1) < 0)
  36. die("Too many files opened\n");
  37. if (streq(fname, "-"))
  38. f = stdin;
  39. else
  40. f = fopen(fname, "r");
  41. if (! f)
  42. die("Couldn't open \"%s\": %s\n", fname, strerror(errno));
  43. return f;
  44. }
  45. /*
  46. * Locate and optionally add filename fname in the file_names[] array.
  47. *
  48. * If the filename is currently not in the array and the boolean
  49. * add_it is non-zero, an attempt to add the filename will be made.
  50. *
  51. * Returns;
  52. * Index [0..MAX_N_FILE_NAMES) where the filename is kept
  53. * -1 if the name can not be recorded
  54. */
  55. int lookup_file_name(const char *fname, int add_it)
  56. {
  57. int i;
  58. for (i = 0; i < n_file_names; i++) {
  59. if (strcmp(file_names[i], fname) == 0)
  60. return i;
  61. }
  62. if (add_it) {
  63. if (n_file_names < MAX_N_FILE_NAMES) {
  64. file_names[n_file_names] = strdup(fname);
  65. return n_file_names++;
  66. }
  67. }
  68. return -1;
  69. }
  70. const char *srcpos_filename_for_num(int filenum)
  71. {
  72. if (0 <= filenum && filenum < n_file_names) {
  73. return file_names[filenum];
  74. }
  75. return 0;
  76. }
  77. const char *srcpos_get_filename(void)
  78. {
  79. return srcpos_filename_for_num(srcpos_filenum);
  80. }