lex.l 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. %{
  2. #include <stdio.h>
  3. #include "yacc.tab.h"
  4. #include "symtable.h"
  5. int linenum = 1;
  6. // include
  7. #define MAX_INCLUDE_DEPTH 10
  8. YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
  9. int include_stack_ptr = 0;
  10. %}
  11. symbol [-=+<>*/&|a-zA-Z][-=+<>*/&|a-zA-Z0-9_]*
  12. number [0-9]+
  13. %option noyywrap
  14. %x incl
  15. %%
  16. /* when including other files, parse them first */
  17. \(include BEGIN(incl);
  18. <incl>[ \t"]* /* ignore whitespace */
  19. <incl>[^ \t\n]+[ \t]*\"[ \t]*\) { /* the filename of the included file */
  20. // get the filename removing the trailing `\")` from the syntax
  21. char *end = yytext;
  22. while (end[0] != '"') { end++; }
  23. end[0] = '\0';
  24. // make sure there aren't too many includes
  25. if ( include_stack_ptr >= MAX_INCLUDE_DEPTH ) {
  26. fprintf( stderr, "Includes nested too deeply\n" );
  27. exit(1);
  28. }
  29. // save current buffer and advance pointer
  30. include_stack[include_stack_ptr++] =
  31. YY_CURRENT_BUFFER;
  32. // open new file
  33. yyin = fopen( yytext, "r" );
  34. if (!yyin) {
  35. fprintf( stderr, "failed to open included file: %s: %s\n", yytext, strerror(errno) );
  36. exit(1);
  37. }
  38. // switch buffer to new file
  39. yy_switch_to_buffer( yy_create_buffer( yyin, YY_BUF_SIZE ) );
  40. // normal parse
  41. BEGIN(INITIAL);
  42. }
  43. <<EOF>> {
  44. // ending initial file
  45. if ( --include_stack_ptr < 0 ) {
  46. yyterminate();
  47. }
  48. // ending included file, resume previous file
  49. else {
  50. yy_delete_buffer( YY_CURRENT_BUFFER );
  51. yy_switch_to_buffer( include_stack[include_stack_ptr] );
  52. }
  53. }
  54. /* ignore comments */
  55. #.* ;
  56. /* constants and variables */
  57. {symbol} { yylval = symtable_insert(yytext, DD_ZERO); return DD_CONSTANT_SYMBOL; }
  58. {number} { yylval = atoi(yytext); return DD_CONSTANT_NUMBER; }
  59. \"[^"]*\" {
  60. /* chop of the quotes from strings
  61. * add it to symbol table
  62. */
  63. char *temp = yytext +1;
  64. yytext[strlen(yytext) -1] = '\0';
  65. yylval = symtable_insert(temp, DD_CONSTANT_STRING);
  66. return DD_CONSTANT_STRING;
  67. }
  68. /* ignore whitespace */
  69. [ \t] ;
  70. /* count lines */
  71. \n linenum++;
  72. /* pass-through symbols */
  73. . return (int) yytext[0];
  74. %%