scan.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include <stdio.h>
  2. /* This file contains the scanner for mylex(), the following functions and
  3. * variables are exported :
  4. *
  5. * int yylineno; - The current line number.
  6. *
  7. * char scanc(); - Return next character.
  8. *
  9. * backc( c); - Push back one character.
  10. * char c;
  11. *
  12. * FILE *switch_input( new); - Scanner will from now on read from
  13. * FILE *new; - 'new', old input-file is returned.
  14. *
  15. * The scanner must perform a lookahead of more than one character, so it uses
  16. * it's own internal buffer.
  17. */
  18. int yylineno = 1;
  19. /********* Internal variables + functions ***********************/
  20. #define BUF_SIZE 16
  21. static char buf[BUF_SIZE], /* Bufer to save backc()-characters */
  22. *bufptr = buf; /* Pointer to space for backc()-character */
  23. static FILE *infile = NULL;
  24. static char nextc()
  25. {
  26. FILE* fp = infile ? infile : stdin;
  27. if ( bufptr > buf)
  28. return( *--bufptr);
  29. else
  30. return( getc( fp));
  31. }
  32. /***************************************************************/
  33. char scanc()
  34. /* Get next character, but delete al C-comments and count lines */
  35. {
  36. char c, nextc();
  37. c = nextc();
  38. while ( c == '/') {
  39. c = nextc();
  40. if ( c == '*') { /* start of comment */
  41. while ( nextc() != '*' || nextc() != '/')
  42. ;
  43. c = nextc();
  44. }
  45. else {
  46. backc( c);
  47. return( '/');
  48. }
  49. }
  50. if ( c == '\n')
  51. yylineno++;
  52. return( c);
  53. }
  54. backc( c)
  55. char c;
  56. {
  57. if ( bufptr >= buf + BUF_SIZE)
  58. error( "backc(), no space in buffer left!");
  59. else {
  60. if ( c == '\n')
  61. yylineno--;
  62. *bufptr++ = c;
  63. }
  64. }
  65. FILE *switch_input( new)
  66. FILE *new;
  67. /* Switch to a new input file, try to save the lookahead-characters in buf[]
  68. * by calling ungetc(). If they can't be saved return NULL.
  69. */
  70. {
  71. FILE* fp = infile ? infile : stdin;
  72. char *ptr; FILE *old;
  73. /* Clean buf[] */
  74. for ( ptr = buf; ptr < bufptr; ptr++)
  75. if ( ungetc( *ptr, fp) == EOF && *ptr != EOF)
  76. return( NULL);
  77. bufptr = buf;
  78. old = infile;
  79. infile = new;
  80. return( old);
  81. }