stb_c_lexer.h 34 KB

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