scan.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 = stdin;
  24. static char nextc()
  25. {
  26. if ( bufptr > buf)
  27. return( *--bufptr);
  28. else
  29. return( getc( infile));
  30. }
  31. /***************************************************************/
  32. char scanc()
  33. /* Get next character, but delete al C-comments and count lines */
  34. {
  35. char c, nextc();
  36. c = nextc();
  37. while ( c == '/') {
  38. c = nextc();
  39. if ( c == '*') { /* start of comment */
  40. while ( nextc() != '*' || nextc() != '/')
  41. ;
  42. c = nextc();
  43. }
  44. else {
  45. backc( c);
  46. return( '/');
  47. }
  48. }
  49. if ( c == '\n')
  50. yylineno++;
  51. return( c);
  52. }
  53. backc( c)
  54. char c;
  55. {
  56. if ( bufptr >= buf + BUF_SIZE)
  57. error( "backc(), no space in buffer left!");
  58. else {
  59. if ( c == '\n')
  60. yylineno--;
  61. *bufptr++ = c;
  62. }
  63. }
  64. FILE *switch_input( new)
  65. FILE *new;
  66. /* Switch to a new input file, try to save the lookahead-characters in buf[]
  67. * by calling ungetc(). If they can't be saved return NULL.
  68. */
  69. {
  70. char *ptr; FILE *old;
  71. /* Clean buf[] */
  72. for ( ptr = buf; ptr < bufptr; ptr++)
  73. if ( ungetc( *ptr, infile) == EOF && *ptr != EOF)
  74. return( NULL);
  75. bufptr = buf;
  76. old = infile;
  77. infile = new;
  78. return( old);
  79. }