Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

962 lines
35 KiB

  1. // stb_c_lexer.h - v0.09 - public domain Sean Barrett 2013
  2. // lexer for making little C-like languages with recursive-descent parsers
  3. //
  4. // This file provides both the interface and the implementation.
  5. // To instantiate the implementation,
  6. // #define STB_C_LEXER_IMPLEMENTATION
  7. // in *ONE* source file, before #including this file.
  8. //
  9. // The default configuration is fairly close to a C lexer, although
  10. // suffixes on integer constants are not handled (you can override this).
  11. //
  12. // History:
  13. // 0.09 hex floats, no-stdlib fixes
  14. // 0.08 fix bad pointer comparison
  15. // 0.07 fix mishandling of hexadecimal constants parsed by strtol
  16. // 0.06 fix missing next character after ending quote mark (Andreas Fredriksson)
  17. // 0.05 refixed get_location because github version had lost the fix
  18. // 0.04 fix octal parsing bug
  19. // 0.03 added STB_C_LEX_DISCARD_PREPROCESSOR option
  20. // refactor API to simplify (only one struct instead of two)
  21. // change literal enum names to have 'lit' at the end
  22. // 0.02 first public release
  23. //
  24. // Status:
  25. // - haven't tested compiling as C++
  26. // - haven't tested the float parsing path
  27. // - haven't tested the non-default-config paths (e.g. non-stdlib)
  28. // - only tested default-config paths by eyeballing output of self-parse
  29. //
  30. // - haven't implemented multiline strings
  31. // - haven't implemented octal/hex character constants
  32. // - haven't implemented support for unicode CLEX_char
  33. // - need to expand error reporting so you don't just get "CLEX_parse_error"
  34. //
  35. // Contributors:
  36. // Arpad Goretity (bugfix)
  37. // Alan Hickman (hex floats)
  38. //
  39. // LICENSE
  40. //
  41. // See end of file for license information.
  42. #ifndef STB_C_LEXER_DEFINITIONS
  43. // to change the default parsing rules, copy the following lines
  44. // into your C/C++ file *before* including this, and then replace
  45. // the Y's with N's for the ones you don't want.
  46. // --BEGIN--
  47. #define STB_C_LEX_C_DECIMAL_INTS Y // "0|[1-9][0-9]*" CLEX_intlit
  48. #define STB_C_LEX_C_HEX_INTS Y // "0x[0-9a-fA-F]+" CLEX_intlit
  49. #define STB_C_LEX_C_OCTAL_INTS Y // "[0-7]+" CLEX_intlit
  50. #define STB_C_LEX_C_DECIMAL_FLOATS Y // "[0-9]*(.[0-9]*([eE][-+]?[0-9]+)?) CLEX_floatlit
  51. #define STB_C_LEX_C99_HEX_FLOATS N // "0x{hex}+(.{hex}*)?[pP][-+]?{hex}+ CLEX_floatlit
  52. #define STB_C_LEX_C_IDENTIFIERS Y // "[_a-zA-Z][_a-zA-Z0-9]*" CLEX_id
  53. #define STB_C_LEX_C_DQ_STRINGS Y // double-quote-delimited strings with escapes CLEX_dqstring
  54. #define STB_C_LEX_C_SQ_STRINGS N // single-quote-delimited strings with escapes CLEX_ssstring
  55. #define STB_C_LEX_C_CHARS Y // single-quote-delimited character with escape CLEX_charlits
  56. #define STB_C_LEX_C_COMMENTS Y // "/* comment */"
  57. #define STB_C_LEX_CPP_COMMENTS Y // "// comment to end of line\n"
  58. #define STB_C_LEX_C_COMPARISONS Y // "==" CLEX_eq "!=" CLEX_noteq "<=" CLEX_lesseq ">=" CLEX_greatereq
  59. #define STB_C_LEX_C_LOGICAL Y // "&&" CLEX_andand "||" CLEX_oror
  60. #define STB_C_LEX_C_SHIFTS Y // "<<" CLEX_shl ">>" CLEX_shr
  61. #define STB_C_LEX_C_INCREMENTS Y // "++" CLEX_plusplus "--" CLEX_minusminus
  62. #define STB_C_LEX_C_ARROW Y // "->" CLEX_arrow
  63. #define STB_C_LEX_EQUAL_ARROW N // "=>" CLEX_eqarrow
  64. #define STB_C_LEX_C_BITWISEEQ Y // "&=" CLEX_andeq "|=" CLEX_oreq "^=" CLEX_xoreq
  65. #define STB_C_LEX_C_ARITHEQ Y // "+=" CLEX_pluseq "-=" CLEX_minuseq
  66. // "*=" CLEX_muleq "/=" CLEX_diveq "%=" CLEX_modeq
  67. // if both STB_C_LEX_SHIFTS & STB_C_LEX_ARITHEQ:
  68. // "<<=" CLEX_shleq ">>=" CLEX_shreq
  69. #define STB_C_LEX_PARSE_SUFFIXES N // letters after numbers are parsed as part of those numbers, and must be in suffix list below
  70. #define STB_C_LEX_DECIMAL_SUFFIXES "" // decimal integer suffixes e.g. "uUlL" -- these are returned as-is in string storage
  71. #define STB_C_LEX_HEX_SUFFIXES "" // e.g. "uUlL"
  72. #define STB_C_LEX_OCTAL_SUFFIXES "" // e.g. "uUlL"
  73. #define STB_C_LEX_FLOAT_SUFFIXES "" //
  74. #define STB_C_LEX_0_IS_EOF N // if Y, ends parsing at '\0'; if N, returns '\0' as token
  75. #define STB_C_LEX_INTEGERS_AS_DOUBLES N // parses integers as doubles so they can be larger than 'int', but only if STB_C_LEX_STDLIB==N
  76. #define STB_C_LEX_MULTILINE_DSTRINGS N // allow newlines in double-quoted strings
  77. #define STB_C_LEX_MULTILINE_SSTRINGS N // allow newlines in single-quoted strings
  78. #define STB_C_LEX_USE_STDLIB Y // use strtod,strtol for parsing #s; otherwise inaccurate hack
  79. #define STB_C_LEX_DOLLAR_IDENTIFIER Y // allow $ as an identifier character
  80. #define STB_C_LEX_FLOAT_NO_DECIMAL Y // allow floats that have no decimal point if they have an exponent
  81. #define STB_C_LEX_DEFINE_ALL_TOKEN_NAMES N // if Y, all CLEX_ token names are defined, even if never returned
  82. // leaving it as N should help you catch config bugs
  83. #define STB_C_LEX_DISCARD_PREPROCESSOR Y // discard C-preprocessor directives (e.g. after prepocess
  84. // still have #line, #pragma, etc)
  85. //#define STB_C_LEX_ISWHITE(str) ... // return length in bytes of whitespace characters if first char is whitespace
  86. #define STB_C_LEXER_DEFINITIONS // This line prevents the header file from replacing your definitions
  87. // --END--
  88. #endif
  89. #ifndef INCLUDE_STB_C_LEXER_H
  90. #define INCLUDE_STB_C_LEXER_H
  91. typedef struct
  92. {
  93. // lexer variables
  94. char *input_stream;
  95. char *eof;
  96. char *parse_point;
  97. char *string_storage;
  98. int string_storage_len;
  99. // lexer parse location for error messages
  100. char *where_firstchar;
  101. char *where_lastchar;
  102. // lexer token variables
  103. long token;
  104. double real_number;
  105. long int_number;
  106. char *string;
  107. int string_len;
  108. } stb_lexer;
  109. typedef struct
  110. {
  111. int line_number;
  112. int line_offset;
  113. } stb_lex_location;
  114. #ifdef __cplusplus
  115. extern "C" {
  116. #endif
  117. extern void stb_c_lexer_init(stb_lexer *lexer, const char *input_stream, const char *input_stream_end, char *string_store, int store_length);
  118. // this function initialize the 'lexer' structure
  119. // Input:
  120. // - input_stream points to the file to parse, loaded into memory
  121. // - input_stream_end points to the end of the file, or NULL if you use 0-for-EOF
  122. // - string_store is storage the lexer can use for storing parsed strings and identifiers
  123. // - store_length is the length of that storage
  124. extern int stb_c_lexer_get_token(stb_lexer *lexer);
  125. // this function returns non-zero if a token is parsed, or 0 if at EOF
  126. // Output:
  127. // - lexer->token is the token ID, which is unicode code point for a single-char token, < 0 for a multichar or eof or error
  128. // - lexer->real_number is a double constant value for CLEX_floatlit, or CLEX_intlit if STB_C_LEX_INTEGERS_AS_DOUBLES
  129. // - lexer->int_number is an integer constant for CLEX_intlit if !STB_C_LEX_INTEGERS_AS_DOUBLES, or character for CLEX_charlit
  130. // - lexer->string is a 0-terminated string for CLEX_dqstring or CLEX_sqstring or CLEX_identifier
  131. // - lexer->string_len is the byte length of lexer->string
  132. extern void stb_c_lexer_get_location(const stb_lexer *lexer, const char *where, stb_lex_location *loc);
  133. // this inefficient function returns the line number and character offset of a
  134. // given location in the file as returned by stb_lex_token. Because it's inefficient,
  135. // you should only call it for errors, not for every token.
  136. // For error messages of invalid tokens, you typically want the location of the start
  137. // of the token (which caused the token to be invalid). For bugs involving legit
  138. // tokens, you can report the first or the range.
  139. // Output:
  140. // - loc->line_number is the line number in the file, counting from 1, of the location
  141. // - loc->line_offset is the char-offset in the line, counting from 0, of the location
  142. #ifdef __cplusplus
  143. }
  144. #endif
  145. #endif // INCLUDE_STB_C_LEXER_H
  146. #ifdef STB_C_LEXER_IMPLEMENTATION
  147. #if defined(Y) || defined(N)
  148. #error "Can only use stb_c_lexer in contexts where the preprocessor symbols 'Y' and 'N' are not defined"
  149. #endif
  150. // Hacky definitions so we can easily #if on them
  151. #define Y(x) 1
  152. #define N(x) 0
  153. #if STB_C_LEX_INTEGERS_AS_DOUBLES(x)
  154. typedef double stb__clex_int;
  155. #define intfield real_number
  156. #define STB__clex_int_as_double
  157. #else
  158. typedef long stb__clex_int;
  159. #define intfield int_number
  160. #endif
  161. // Convert these config options to simple conditional #defines so we can more
  162. // easily test them once we've change the meaning of Y/N
  163. #if STB_C_LEX_PARSE_SUFFIXES(x)
  164. #define STB__clex_parse_suffixes
  165. #endif
  166. #if STB_C_LEX_C_DECIMAL_INTS(x) || STB_C_LEX_C_HEX_INTS(x) || STB_C_LEX_DEFINE_ALL_TOKEN_NAMES(x)
  167. #define STB__clex_define_int
  168. #endif
  169. #if (STB_C_LEX_C_ARITHEQ(x) && STB_C_LEX_C_SHIFTS(x)) || STB_C_LEX_DEFINE_ALL_TOKEN_NAMES(x)
  170. #define STB__clex_define_shifts
  171. #endif
  172. #if STB_C_LEX_C99_HEX_FLOATS(x)
  173. #define STB__clex_hex_floats
  174. #endif
  175. #if STB_C_LEX_C_HEX_INTS(x)
  176. #define STB__clex_hex_ints
  177. #endif
  178. #if STB_C_LEX_C_DECIMAL_INTS(x)
  179. #define STB__clex_decimal_ints
  180. #endif
  181. #if STB_C_LEX_C_OCTAL_INTS(x)
  182. #define STB__clex_octal_ints
  183. #endif
  184. #if STB_C_LEX_C_DECIMAL_FLOATS(x)
  185. #define STB__clex_decimal_floats
  186. #endif
  187. #if STB_C_LEX_DISCARD_PREPROCESSOR(x)
  188. #define STB__clex_discard_preprocessor
  189. #endif
  190. #if STB_C_LEX_USE_STDLIB(x) && (!defined(STB__clex_hex_floats) || __STDC_VERSION__ >= 199901L)
  191. #define STB__CLEX_use_stdlib
  192. #include <stdlib.h>
  193. #endif
  194. // Now pick a definition of Y/N that's conducive to
  195. // defining the enum of token names.
  196. #if STB_C_LEX_DEFINE_ALL_TOKEN_NAMES(x) || defined(STB_C_LEXER_SELF_TEST)
  197. #undef N
  198. #define N(a) Y(a)
  199. #else
  200. #undef N
  201. #define N(a)
  202. #endif
  203. #undef Y
  204. #define Y(a) a,
  205. enum
  206. {
  207. CLEX_eof = 256,
  208. CLEX_parse_error,
  209. #ifdef STB__clex_define_int
  210. CLEX_intlit,
  211. #endif
  212. STB_C_LEX_C_DECIMAL_FLOATS( CLEX_floatlit )
  213. STB_C_LEX_C_IDENTIFIERS( CLEX_id )
  214. STB_C_LEX_C_DQ_STRINGS( CLEX_dqstring )
  215. STB_C_LEX_C_SQ_STRINGS( CLEX_sqstring )
  216. STB_C_LEX_C_CHARS( CLEX_charlit )
  217. STB_C_LEX_C_COMPARISONS( CLEX_eq )
  218. STB_C_LEX_C_COMPARISONS( CLEX_noteq )
  219. STB_C_LEX_C_COMPARISONS( CLEX_lesseq )
  220. STB_C_LEX_C_COMPARISONS( CLEX_greatereq )
  221. STB_C_LEX_C_LOGICAL( CLEX_andand )
  222. STB_C_LEX_C_LOGICAL( CLEX_oror )
  223. STB_C_LEX_C_SHIFTS( CLEX_shl )
  224. STB_C_LEX_C_SHIFTS( CLEX_shr )
  225. STB_C_LEX_C_INCREMENTS( CLEX_plusplus )
  226. STB_C_LEX_C_INCREMENTS( CLEX_minusminus )
  227. STB_C_LEX_C_ARITHEQ( CLEX_pluseq )
  228. STB_C_LEX_C_ARITHEQ( CLEX_minuseq )
  229. STB_C_LEX_C_ARITHEQ( CLEX_muleq )
  230. STB_C_LEX_C_ARITHEQ( CLEX_diveq )
  231. STB_C_LEX_C_ARITHEQ( CLEX_modeq )
  232. STB_C_LEX_C_BITWISEEQ( CLEX_andeq )
  233. STB_C_LEX_C_BITWISEEQ( CLEX_oreq )
  234. STB_C_LEX_C_BITWISEEQ( CLEX_xoreq )
  235. STB_C_LEX_C_ARROW( CLEX_arrow )
  236. STB_C_LEX_EQUAL_ARROW( CLEX_eqarrow )
  237. #ifdef STB__clex_define_shifts
  238. CLEX_shleq, CLEX_shreq,
  239. #endif
  240. CLEX_first_unused_token
  241. #undef Y
  242. #define Y(a) a
  243. };
  244. // Now for the rest of the file we'll use the basic definition where
  245. // where Y expands to its contents and N expands to nothing
  246. #undef N
  247. #define N(a)
  248. // API function
  249. void stb_c_lexer_init(stb_lexer *lexer, const char *input_stream, const char *input_stream_end, char *string_store, int store_length)
  250. {
  251. lexer->input_stream = (char *) input_stream;
  252. lexer->eof = (char *) input_stream_end;
  253. lexer->parse_point = (char *) input_stream;
  254. lexer->string_storage = string_store;
  255. lexer->string_storage_len = store_length;
  256. }
  257. // API function
  258. void stb_c_lexer_get_location(const stb_lexer *lexer, const char *where, stb_lex_location *loc)
  259. {
  260. char *p = lexer->input_stream;
  261. int line_number = 1;
  262. int char_offset = 0;
  263. while (*p && p < where) {
  264. if (*p == '\n' || *p == '\r') {
  265. p += (p[0]+p[1] == '\r'+'\n' ? 2 : 1); // skip newline
  266. line_number += 1;
  267. char_offset = 0;
  268. } else {
  269. ++p;
  270. ++char_offset;
  271. }
  272. }
  273. loc->line_number = line_number;
  274. loc->line_offset = char_offset;
  275. }
  276. // main helper function for returning a parsed token
  277. static int stb__clex_token(stb_lexer *lexer, int token, char *start, char *end)
  278. {
  279. lexer->token = token;
  280. lexer->where_firstchar = start;
  281. lexer->where_lastchar = end;
  282. lexer->parse_point = end+1;
  283. return 1;
  284. }
  285. // helper function for returning eof
  286. static int stb__clex_eof(stb_lexer *lexer)
  287. {
  288. lexer->token = CLEX_eof;
  289. return 0;
  290. }
  291. static int stb__clex_iswhite(int x)
  292. {
  293. return x == ' ' || x == '\t' || x == '\r' || x == '\n' || x == '\f';
  294. }
  295. static const char *stb__strchr(const char *str, int ch)
  296. {
  297. for (; *str; ++str)
  298. if (*str == ch)
  299. return str;
  300. return 0;
  301. }
  302. // parse suffixes at the end of a number
  303. static int stb__clex_parse_suffixes(stb_lexer *lexer, long tokenid, char *start, char *cur, const char *suffixes)
  304. {
  305. #ifdef STB__clex_parse_suffixes
  306. lexer->string = lexer->string_storage;
  307. lexer->string_len = 0;
  308. while ((*cur >= 'a' && *cur <= 'z') || (*cur >= 'A' && *cur <= 'Z')) {
  309. if (stb__strchr(suffixes, *cur) == 0)
  310. return stb__clex_token(lexer, CLEX_parse_error, start, cur);
  311. if (lexer->string_len+1 >= lexer->string_storage_len)
  312. return stb__clex_token(lexer, CLEX_parse_error, start, cur);
  313. lexer->string[lexer->string_len++] = *cur++;
  314. }
  315. #else
  316. suffixes = suffixes; // attempt to suppress warnings
  317. #endif
  318. return stb__clex_token(lexer, tokenid, start, cur-1);
  319. }
  320. #ifndef STB__CLEX_use_stdlib
  321. static double stb__clex_pow(double base, unsigned int exponent)
  322. {
  323. double value=1;
  324. for ( ; exponent; exponent >>= 1) {
  325. if (exponent & 1)
  326. value *= base;
  327. base *= base;
  328. }
  329. return value;
  330. }
  331. static double stb__clex_parse_float(char *p, char **q)
  332. {
  333. char *s = p;
  334. double value=0;
  335. int base=10;
  336. int exponent=0;
  337. #ifdef STB__clex_hex_floats
  338. if (*p == '0') {
  339. if (p[1] == 'x' || p[1] == 'X') {
  340. base=16;
  341. p += 2;
  342. }
  343. }
  344. #endif
  345. for (;;) {
  346. if (*p >= '0' && *p <= '9')
  347. value = value*base + (*p++ - '0');
  348. #ifdef STB__clex_hex_floats
  349. else if (base == 16 && *p >= 'a' && *p <= 'f')
  350. value = value*base + 10 + (*p++ - 'a');
  351. else if (base == 16 && *p >= 'A' && *p <= 'F')
  352. value = value*base + 10 + (*p++ - 'A');
  353. #endif
  354. else
  355. break;
  356. }
  357. if (*p == '.') {
  358. double pow, addend = 0;
  359. ++p;
  360. for (pow=1; ; pow*=base) {
  361. if (*p >= '0' && *p <= '9')
  362. addend = addend*base + (*p++ - '0');
  363. #ifdef STB__clex_hex_floats
  364. else if (base == 16 && *p >= 'a' && *p <= 'f')
  365. addend = addend*base + 10 + (*p++ - 'a');
  366. else if (base == 16 && *p >= 'A' && *p <= 'F')
  367. addend = addend*base + 10 + (*p++ - 'A');
  368. #endif
  369. else
  370. break;
  371. }
  372. value += addend / pow;
  373. }
  374. #ifdef STB__clex_hex_floats
  375. if (base == 16) {
  376. // exponent required for hex float literal
  377. if (*p != 'p' && *p != 'P') {
  378. *q = s;
  379. return 0;
  380. }
  381. exponent = 1;
  382. } else
  383. #endif
  384. exponent = (*p == 'e' || *p == 'E');
  385. if (exponent) {
  386. int sign = p[1] == '-';
  387. unsigned int exponent=0;
  388. double power=1;
  389. ++p;
  390. if (*p == '-' || *p == '+')
  391. ++p;
  392. while (*p >= '0' && *p <= '9')
  393. exponent = exponent*10 + (*p++ - '0');
  394. #ifdef STB__clex_hex_floats
  395. if (base == 16)
  396. power = stb__clex_pow(2, exponent);
  397. else
  398. #endif
  399. power = stb__clex_pow(10, exponent);
  400. if (sign)
  401. value /= power;
  402. else
  403. value *= power;
  404. }
  405. *q = p;
  406. return value;
  407. }
  408. #endif
  409. static int stb__clex_parse_char(char *p, char **q)
  410. {
  411. if (*p == '\\') {
  412. *q = p+2; // tentatively guess we'll parse two characters
  413. switch(p[1]) {
  414. case '\\': return '\\';
  415. case '\'': return '\'';
  416. case '"': return '"';
  417. case 't': return '\t';
  418. case 'f': return '\f';
  419. case 'n': return '\n';
  420. case 'r': return '\r';
  421. case '0': return '\0'; // @TODO ocatal constants
  422. case 'x': case 'X': return -1; // @TODO hex constants
  423. case 'u': return -1; // @TODO unicode constants
  424. }
  425. }
  426. *q = p+1;
  427. return (unsigned char) *p;
  428. }
  429. static int stb__clex_parse_string(stb_lexer *lexer, char *p, int type)
  430. {
  431. char *start = p;
  432. char delim = *p++; // grab the " or ' for later matching
  433. char *out = lexer->string_storage;
  434. char *outend = lexer->string_storage + lexer->string_storage_len;
  435. while (*p != delim) {
  436. int n;
  437. if (*p == '\\') {
  438. char *q;
  439. n = stb__clex_parse_char(p, &q);
  440. if (n < 0)
  441. return stb__clex_token(lexer, CLEX_parse_error, start, q);
  442. p = q;
  443. } else {
  444. // @OPTIMIZE: could speed this up by looping-while-not-backslash
  445. n = (unsigned char) *p++;
  446. }
  447. if (out+1 > outend)
  448. return stb__clex_token(lexer, CLEX_parse_error, start, p);
  449. // @TODO expand unicode escapes to UTF8
  450. *out++ = (char) n;
  451. }
  452. *out = 0;
  453. lexer->string = lexer->string_storage;
  454. lexer->string_len = out - lexer->string_storage;
  455. return stb__clex_token(lexer, type, start, p);
  456. }
  457. int stb_c_lexer_get_token(stb_lexer *lexer)
  458. {
  459. char *p = lexer->parse_point;
  460. // skip whitespace and comments
  461. for (;;) {
  462. #ifdef STB_C_LEX_ISWHITE
  463. while (p != lexer->stream_end) {
  464. int n;
  465. n = STB_C_LEX_ISWHITE(p);
  466. if (n == 0) break;
  467. if (lexer->eof && lexer->eof - lexer->parse_point < n)
  468. return stb__clex_token(tok, CLEX_parse_error, p,lexer->eof-1);
  469. p += n;
  470. }
  471. #else
  472. while (p != lexer->eof && stb__clex_iswhite(*p))
  473. ++p;
  474. #endif
  475. STB_C_LEX_CPP_COMMENTS(
  476. if (p != lexer->eof && p[0] == '/' && p[1] == '/') {
  477. while (p != lexer->eof && *p != '\r' && *p != '\n')
  478. ++p;
  479. continue;
  480. }
  481. )
  482. STB_C_LEX_C_COMMENTS(
  483. if (p != lexer->eof && p[0] == '/' && p[1] == '*') {
  484. char *start = p;
  485. p += 2;
  486. while (p != lexer->eof && (p[0] != '*' || p[1] != '/'))
  487. ++p;
  488. if (p == lexer->eof)
  489. return stb__clex_token(lexer, CLEX_parse_error, start, p-1);
  490. p += 2;
  491. continue;
  492. }
  493. )
  494. #ifdef STB__clex_discard_preprocessor
  495. // @TODO this discards everything after a '#', regardless
  496. // of where in the line the # is, rather than requiring it
  497. // be at the start. (because this parser doesn't otherwise
  498. // check for line breaks!)
  499. if (p != lexer->eof && p[0] == '#') {
  500. while (p != lexer->eof && *p != '\r' && *p != '\n')
  501. ++p;
  502. continue;
  503. }
  504. #endif
  505. break;
  506. }
  507. if (p == lexer->eof)
  508. return stb__clex_eof(lexer);
  509. switch (*p) {
  510. default:
  511. if ( (*p >= 'a' && *p <= 'z')
  512. || (*p >= 'A' && *p <= 'Z')
  513. || *p == '_' || (unsigned char) *p >= 128 // >= 128 is UTF8 char
  514. STB_C_LEX_DOLLAR_IDENTIFIER( || *p == '$' ) )
  515. {
  516. int n = 0;
  517. lexer->string = lexer->string_storage;
  518. lexer->string_len = n;
  519. do {
  520. if (n+1 >= lexer->string_storage_len)
  521. return stb__clex_token(lexer, CLEX_parse_error, p, p+n);
  522. lexer->string[n] = p[n];
  523. ++n;
  524. } while (
  525. (p[n] >= 'a' && p[n] <= 'z')
  526. || (p[n] >= 'A' && p[n] <= 'Z')
  527. || (p[n] >= '0' && p[n] <= '9') // allow digits in middle of identifier
  528. || p[n] == '_' || (unsigned char) p[n] >= 128
  529. STB_C_LEX_DOLLAR_IDENTIFIER( || p[n] == '$' )
  530. );
  531. lexer->string[n] = 0;
  532. return stb__clex_token(lexer, CLEX_id, p, p+n-1);
  533. }
  534. // check for EOF
  535. STB_C_LEX_0_IS_EOF(
  536. if (*p == 0)
  537. return stb__clex_eof(tok);
  538. )
  539. single_char:
  540. // not an identifier, return the character as itself
  541. return stb__clex_token(lexer, *p, p, p);
  542. case '+':
  543. if (p+1 != lexer->eof) {
  544. STB_C_LEX_C_INCREMENTS(if (p[1] == '+') return stb__clex_token(lexer, CLEX_plusplus, p,p+1);)
  545. STB_C_LEX_C_ARITHEQ( if (p[1] == '=') return stb__clex_token(lexer, CLEX_pluseq , p,p+1);)
  546. }
  547. goto single_char;
  548. case '-':
  549. if (p+1 != lexer->eof) {
  550. STB_C_LEX_C_INCREMENTS(if (p[1] == '-') return stb__clex_token(lexer, CLEX_minusminus, p,p+1);)
  551. STB_C_LEX_C_ARITHEQ( if (p[1] == '=') return stb__clex_token(lexer, CLEX_minuseq , p,p+1);)
  552. STB_C_LEX_C_ARROW( if (p[1] == '>') return stb__clex_token(lexer, CLEX_arrow , p,p+1);)
  553. }
  554. goto single_char;
  555. case '&':
  556. if (p+1 != lexer->eof) {
  557. STB_C_LEX_C_LOGICAL( if (p[1] == '&') return stb__clex_token(lexer, CLEX_andand, p,p+1);)
  558. STB_C_LEX_C_BITWISEEQ(if (p[1] == '=') return stb__clex_token(lexer, CLEX_andeq , p,p+1);)
  559. }
  560. goto single_char;
  561. case '|':
  562. if (p+1 != lexer->eof) {
  563. STB_C_LEX_C_LOGICAL( if (p[1] == '|') return stb__clex_token(lexer, CLEX_oror, p,p+1);)
  564. STB_C_LEX_C_BITWISEEQ(if (p[1] == '=') return stb__clex_token(lexer, CLEX_oreq, p,p+1);)
  565. }
  566. goto single_char;
  567. case '=':
  568. if (p+1 != lexer->eof) {
  569. STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_eq, p,p+1);)
  570. STB_C_LEX_EQUAL_ARROW( if (p[1] == '>') return stb__clex_token(lexer, CLEX_eqarrow, p,p+1);)
  571. }
  572. goto single_char;
  573. case '!':
  574. STB_C_LEX_C_COMPARISONS(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_noteq, p,p+1);)
  575. goto single_char;
  576. case '^':
  577. STB_C_LEX_C_BITWISEEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_xoreq, p,p+1));
  578. goto single_char;
  579. case '%':
  580. STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_modeq, p,p+1));
  581. goto single_char;
  582. case '*':
  583. STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_muleq, p,p+1));
  584. goto single_char;
  585. case '/':
  586. STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_diveq, p,p+1));
  587. goto single_char;
  588. case '<':
  589. if (p+1 != lexer->eof) {
  590. STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_lesseq, p,p+1);)
  591. STB_C_LEX_C_SHIFTS( if (p[1] == '<') {
  592. STB_C_LEX_C_ARITHEQ(if (p+2 != lexer->eof && p[2] == '=')
  593. return stb__clex_token(lexer, CLEX_shleq, p,p+2);)
  594. return stb__clex_token(lexer, CLEX_shl, p,p+1);
  595. }
  596. )
  597. }
  598. goto single_char;
  599. case '>':
  600. if (p+1 != lexer->eof) {
  601. STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_greatereq, p,p+1);)
  602. STB_C_LEX_C_SHIFTS( if (p[1] == '>') {
  603. STB_C_LEX_C_ARITHEQ(if (p+2 != lexer->eof && p[2] == '=')
  604. return stb__clex_token(lexer, CLEX_shreq, p,p+2);)
  605. return stb__clex_token(lexer, CLEX_shr, p,p+1);
  606. }
  607. )
  608. }
  609. goto single_char;
  610. case '"':
  611. STB_C_LEX_C_DQ_STRINGS(return stb__clex_parse_string(lexer, p, CLEX_dqstring);)
  612. goto single_char;
  613. case '\'':
  614. STB_C_LEX_C_SQ_STRINGS(return stb__clex_parse_string(lexer, p, CLEX_sqstring);)
  615. STB_C_LEX_C_CHARS(
  616. {
  617. char *start = p;
  618. lexer->int_number = stb__clex_parse_char(p+1, &p);
  619. if (lexer->int_number < 0)
  620. return stb__clex_token(lexer, CLEX_parse_error, start,start);
  621. if (p == lexer->eof || *p != '\'')
  622. return stb__clex_token(lexer, CLEX_parse_error, start,p);
  623. return stb__clex_token(lexer, CLEX_charlit, start, p+1);
  624. })
  625. goto single_char;
  626. case '0':
  627. #if defined(STB__clex_hex_ints) || defined(STB__clex_hex_floats)
  628. if (p+1 != lexer->eof) {
  629. if (p[1] == 'x' || p[1] == 'X') {
  630. char *q;
  631. #ifdef STB__clex_hex_floats
  632. for (q=p+2;
  633. q != lexer->eof && ((*q >= '0' && *q <= '9') || (*q >= 'a' && *q <= 'f') || (*q >= 'A' && *q <= 'F'));
  634. ++q);
  635. if (q != lexer->eof) {
  636. if (*q == '.' STB_C_LEX_FLOAT_NO_DECIMAL(|| *q == 'p' || *q == 'P')) {
  637. #ifdef STB__CLEX_use_stdlib
  638. lexer->real_number = strtod((char *) p, (char**) &q);
  639. #else
  640. lexer->real_number = stb__clex_parse_float(p, &q);
  641. #endif
  642. if (p == q)
  643. return stb__clex_token(lexer, CLEX_parse_error, p,q);
  644. return stb__clex_parse_suffixes(lexer, CLEX_floatlit, p,q, STB_C_LEX_FLOAT_SUFFIXES);
  645. }
  646. }
  647. #endif // STB__CLEX_hex_floats
  648. #ifdef STB__clex_hex_ints
  649. #ifdef STB__CLEX_use_stdlib
  650. lexer->int_number = strtol((char *) p, (char **) &q, 16);
  651. #else
  652. {
  653. stb__clex_int n=0;
  654. for (q=p+2; q != lexer->eof; ++q) {
  655. if (*q >= '0' && *q <= '9')
  656. n = n*16 + (*q - '0');
  657. else if (*q >= 'a' && *q <= 'f')
  658. n = n*16 + (*q - 'a') + 10;
  659. else if (*q >= 'A' && *q <= 'F')
  660. n = n*16 + (*q - 'A') + 10;
  661. else
  662. break;
  663. }
  664. lexer->int_number = n;
  665. }
  666. #endif
  667. if (q == p+2)
  668. return stb__clex_token(lexer, CLEX_parse_error, p-2,p-1);
  669. return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_HEX_SUFFIXES);
  670. #endif
  671. }
  672. }
  673. #endif // defined(STB__clex_hex_ints) || defined(STB__clex_hex_floats)
  674. // can't test for octal because we might parse '0.0' as float or as '0' '.' '0',
  675. // so have to do float first
  676. /* FALL THROUGH */
  677. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  678. #ifdef STB__clex_decimal_floats
  679. {
  680. char *q = p;
  681. while (q != lexer->eof && (*q >= '0' && *q <= '9'))
  682. ++q;
  683. if (q != lexer->eof) {
  684. if (*q == '.' STB_C_LEX_FLOAT_NO_DECIMAL(|| *q == 'e' || *q == 'E')) {
  685. #ifdef STB__CLEX_use_stdlib
  686. lexer->real_number = strtod((char *) p, (char**) &q);
  687. #else
  688. lexer->real_number = stb__clex_parse_float(p, &q);
  689. #endif
  690. return stb__clex_parse_suffixes(lexer, CLEX_floatlit, p,q, STB_C_LEX_FLOAT_SUFFIXES);
  691. }
  692. }
  693. }
  694. #endif // STB__clex_decimal_floats
  695. #ifdef STB__clex_octal_ints
  696. if (p[0] == '0') {
  697. char *q = p;
  698. #ifdef STB__CLEX_use_stdlib
  699. lexer->int_number = strtol((char *) p, (char **) &q, 8);
  700. #else
  701. stb__clex_int n=0;
  702. while (q != lexer->eof) {
  703. if (*q >= '0' && *q <= '7')
  704. n = n*8 + (*q - '0');
  705. else
  706. break;
  707. ++q;
  708. }
  709. if (q != lexer->eof && (*q == '8' || *q=='9'))
  710. return stb__clex_token(lexer, CLEX_parse_error, p, q);
  711. lexer->int_number = n;
  712. #endif
  713. return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_OCTAL_SUFFIXES);
  714. }
  715. #endif // STB__clex_octal_ints
  716. #ifdef STB__clex_decimal_ints
  717. {
  718. char *q = p;
  719. #ifdef STB__CLEX_use_stdlib
  720. lexer->int_number = strtol((char *) p, (char **) &q, 10);
  721. #else
  722. stb__clex_int n=0;
  723. while (q != lexer->eof) {
  724. if (*q >= '0' && *q <= '9')
  725. n = n*10 + (*q - '0');
  726. else
  727. break;
  728. ++q;
  729. }
  730. lexer->int_number = n;
  731. #endif
  732. return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_OCTAL_SUFFIXES);
  733. }
  734. #endif // STB__clex_decimal_ints
  735. goto single_char;
  736. }
  737. }
  738. #endif // STB_C_LEXER_IMPLEMENTATION
  739. #ifdef STB_C_LEXER_SELF_TEST
  740. #include <stdio.h>
  741. #include <stdlib.h>
  742. static void print_token(stb_lexer *lexer)
  743. {
  744. switch (lexer->token) {
  745. case CLEX_id : printf("_%s", lexer->string); break;
  746. case CLEX_eq : printf("=="); break;
  747. case CLEX_noteq : printf("!="); break;
  748. case CLEX_lesseq : printf("<="); break;
  749. case CLEX_greatereq : printf(">="); break;
  750. case CLEX_andand : printf("&&"); break;
  751. case CLEX_oror : printf("||"); break;
  752. case CLEX_shl : printf("<<"); break;
  753. case CLEX_shr : printf(">>"); break;
  754. case CLEX_plusplus : printf("++"); break;
  755. case CLEX_minusminus: printf("--"); break;
  756. case CLEX_arrow : printf("->"); break;
  757. case CLEX_andeq : printf("&="); break;
  758. case CLEX_oreq : printf("|="); break;
  759. case CLEX_xoreq : printf("^="); break;
  760. case CLEX_pluseq : printf("+="); break;
  761. case CLEX_minuseq : printf("-="); break;
  762. case CLEX_muleq : printf("*="); break;
  763. case CLEX_diveq : printf("/="); break;
  764. case CLEX_modeq : printf("%%="); break;
  765. case CLEX_shleq : printf("<<="); break;
  766. case CLEX_shreq : printf(">>="); break;
  767. case CLEX_eqarrow : printf("=>"); break;
  768. case CLEX_dqstring : printf("\"%s\"", lexer->string); break;
  769. case CLEX_sqstring : printf("'\"%s\"'", lexer->string); break;
  770. case CLEX_charlit : printf("'%s'", lexer->string); break;
  771. #if defined(STB__clex_int_as_double) && !defined(STB__CLEX_use_stdlib)
  772. case CLEX_intlit : printf("#%g", lexer->real_number); break;
  773. #else
  774. case CLEX_intlit : printf("#%ld", lexer->int_number); break;
  775. #endif
  776. case CLEX_floatlit : printf("%g", lexer->real_number); break;
  777. default:
  778. if (lexer->token >= 0 && lexer->token < 256)
  779. printf("%c", (int) lexer->token);
  780. else {
  781. printf("<<<UNKNOWN TOKEN %ld >>>\n", lexer->token);
  782. }
  783. break;
  784. }
  785. }
  786. /* Force a test
  787. of parsing
  788. multiline comments */
  789. /*/ comment /*/
  790. /**/ extern /**/
  791. void dummy(void)
  792. {
  793. double some_floats[] = {
  794. 1.0501, -10.4e12, 5E+10,
  795. #if 0 // not support in C++ or C-pre-99, so don't try to compile it
  796. 0x1.0p+24, 0xff.FP-8, 0x1p-23,
  797. #endif
  798. 4.
  799. };
  800. printf("test %d",1); // https://github.com/nothings/stb/issues/13
  801. }
  802. int main(int argc, char **argv)
  803. {
  804. FILE *f = fopen("stb_c_lexer.h","rb");
  805. char *text = (char *) malloc(1 << 20);
  806. int len = f ? fread(text, 1, 1<<20, f) : -1;
  807. stb_lexer lex;
  808. if (len < 0) {
  809. fprintf(stderr, "Error opening file\n");
  810. free(text);
  811. fclose(f);
  812. return 1;
  813. }
  814. fclose(f);
  815. stb_c_lexer_init(&lex, text, text+len, (char *) malloc(0x10000), 0x10000);
  816. while (stb_c_lexer_get_token(&lex)) {
  817. if (lex.token == CLEX_parse_error) {
  818. printf("\n<<<PARSE ERROR>>>\n");
  819. break;
  820. }
  821. print_token(&lex);
  822. printf(" ");
  823. }
  824. return 0;
  825. }
  826. #endif
  827. /*
  828. ------------------------------------------------------------------------------
  829. This software is available under 2 licenses -- choose whichever you prefer.
  830. ------------------------------------------------------------------------------
  831. ALTERNATIVE A - MIT License
  832. Copyright (c) 2017 Sean Barrett
  833. Permission is hereby granted, free of charge, to any person obtaining a copy of
  834. this software and associated documentation files (the "Software"), to deal in
  835. the Software without restriction, including without limitation the rights to
  836. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  837. of the Software, and to permit persons to whom the Software is furnished to do
  838. so, subject to the following conditions:
  839. The above copyright notice and this permission notice shall be included in all
  840. copies or substantial portions of the Software.
  841. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  842. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  843. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  844. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  845. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  846. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  847. SOFTWARE.
  848. ------------------------------------------------------------------------------
  849. ALTERNATIVE B - Public Domain (www.unlicense.org)
  850. This is free and unencumbered software released into the public domain.
  851. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  852. software, either in source code form or as a compiled binary, for any purpose,
  853. commercial or non-commercial, and by any means.
  854. In jurisdictions that recognize copyright laws, the author or authors of this
  855. software dedicate any and all copyright interest in the software to the public
  856. domain. We make this dedication for the benefit of the public at large and to
  857. the detriment of our heirs and successors. We intend this dedication to be an
  858. overt act of relinquishment in perpetuity of all present and future rights to
  859. this software under copyright law.
  860. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  861. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  862. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  863. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  864. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  865. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  866. ------------------------------------------------------------------------------
  867. */