stb_c_lexer.h
This file
Path
stb_c_lexer.h
941 lines · 33.9 KiB · C
Last changed by
Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d
History of this fileTake it
1// stb_c_lexer.h - v0.12 - public domain Sean Barrett 20132// lexer for making little C-like languages with recursive-descent parsers3//4// This file provides both the interface and the implementation.5// To instantiate the implementation,6// #define STB_C_LEXER_IMPLEMENTATION7// in *ONE* source file, before #including this file.8//9// The default configuration is fairly close to a C lexer, although10// 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 inclusion14// 0.11 fix clang static analysis warning15// 0.10 fix warnings16// 0.09 hex floats, no-stdlib fixes17// 0.08 fix bad pointer comparison18// 0.07 fix mishandling of hexadecimal constants parsed by strtol19// 0.06 fix missing next character after ending quote mark (Andreas Fredriksson)20// 0.05 refixed get_location because github version had lost the fix21// 0.04 fix octal parsing bug22// 0.03 added STB_C_LEX_DISCARD_PREPROCESSOR option23// refactor API to simplify (only one struct instead of two)24// change literal enum names to have 'lit' at the end25// 0.02 first public release26//27// Status:28// - haven't tested compiling as C++29// - haven't tested the float parsing path30// - haven't tested the non-default-config paths (e.g. non-stdlib)31// - only tested default-config paths by eyeballing output of self-parse32//33// - haven't implemented multiline strings34// - haven't implemented octal/hex character constants35// - haven't implemented support for unicode CLEX_char36// - 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// github:mundusnine (bugfix)42//43// LICENSE44//45// See end of file for license information.4647#ifdef STB_C_LEXER_IMPLEMENTATION48#ifndef STB_C_LEXER_DEFINITIONS49// to change the default parsing rules, copy the following lines50// into your C/C++ file *before* including this, and then replace51// the Y's with N's for the ones you don't want. This needs to be52// set to the same values for every place in your program where53// stb_c_lexer.h is included.54// --BEGIN--5556#if defined(Y) || defined(N)57#error "Can only use stb_c_lexer in contexts where the preprocessor symbols 'Y' and 'N' are not defined"58#endif5960#define STB_C_LEX_C_DECIMAL_INTS Y // "0|[1-9][0-9]*" CLEX_intlit61#define STB_C_LEX_C_HEX_INTS Y // "0x[0-9a-fA-F]+" CLEX_intlit62#define STB_C_LEX_C_OCTAL_INTS Y // "[0-7]+" CLEX_intlit63#define STB_C_LEX_C_DECIMAL_FLOATS Y // "[0-9]*(.[0-9]*([eE][-+]?[0-9]+)?) CLEX_floatlit64#define STB_C_LEX_C99_HEX_FLOATS N // "0x{hex}+(.{hex}*)?[pP][-+]?{hex}+ CLEX_floatlit65#define STB_C_LEX_C_IDENTIFIERS Y // "[_a-zA-Z][_a-zA-Z0-9]*" CLEX_id66#define STB_C_LEX_C_DQ_STRINGS Y // double-quote-delimited strings with escapes CLEX_dqstring67#define STB_C_LEX_C_SQ_STRINGS N // single-quote-delimited strings with escapes CLEX_ssstring68#define STB_C_LEX_C_CHARS Y // single-quote-delimited character with escape CLEX_charlits69#define STB_C_LEX_C_COMMENTS Y // "/* comment */"70#define STB_C_LEX_CPP_COMMENTS Y // "// comment to end of line\n"71#define STB_C_LEX_C_COMPARISONS Y // "==" CLEX_eq "!=" CLEX_noteq "<=" CLEX_lesseq ">=" CLEX_greatereq72#define STB_C_LEX_C_LOGICAL Y // "&&" CLEX_andand "||" CLEX_oror73#define STB_C_LEX_C_SHIFTS Y // "<<" CLEX_shl ">>" CLEX_shr74#define STB_C_LEX_C_INCREMENTS Y // "++" CLEX_plusplus "--" CLEX_minusminus75#define STB_C_LEX_C_ARROW Y // "->" CLEX_arrow76#define STB_C_LEX_EQUAL_ARROW N // "=>" CLEX_eqarrow77#define STB_C_LEX_C_BITWISEEQ Y // "&=" CLEX_andeq "|=" CLEX_oreq "^=" CLEX_xoreq78#define STB_C_LEX_C_ARITHEQ Y // "+=" CLEX_pluseq "-=" CLEX_minuseq79 // "*=" CLEX_muleq "/=" CLEX_diveq "%=" CLEX_modeq80 // if both STB_C_LEX_SHIFTS & STB_C_LEX_ARITHEQ:81 // "<<=" CLEX_shleq ">>=" CLEX_shreq8283#define STB_C_LEX_PARSE_SUFFIXES N // letters after numbers are parsed as part of those numbers, and must be in suffix list below84#define STB_C_LEX_DECIMAL_SUFFIXES "" // decimal integer suffixes e.g. "uUlL" -- these are returned as-is in string storage85#define STB_C_LEX_HEX_SUFFIXES "" // e.g. "uUlL"86#define STB_C_LEX_OCTAL_SUFFIXES "" // e.g. "uUlL"87#define STB_C_LEX_FLOAT_SUFFIXES "" //8889#define STB_C_LEX_0_IS_EOF N // if Y, ends parsing at '\0'; if N, returns '\0' as token90#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==N91#define STB_C_LEX_MULTILINE_DSTRINGS N // allow newlines in double-quoted strings92#define STB_C_LEX_MULTILINE_SSTRINGS N // allow newlines in single-quoted strings93#define STB_C_LEX_USE_STDLIB Y // use strtod,strtol for parsing #s; otherwise inaccurate hack94#define STB_C_LEX_DOLLAR_IDENTIFIER Y // allow $ as an identifier character95#define STB_C_LEX_FLOAT_NO_DECIMAL Y // allow floats that have no decimal point if they have an exponent9697#define STB_C_LEX_DEFINE_ALL_TOKEN_NAMES N // if Y, all CLEX_ token names are defined, even if never returned98 // leaving it as N should help you catch config bugs99100#define STB_C_LEX_DISCARD_PREPROCESSOR Y // discard C-preprocessor directives (e.g. after prepocess101 // still have #line, #pragma, etc)102103//#define STB_C_LEX_ISWHITE(str) ... // return length in bytes of whitespace characters if first char is whitespace104105#define STB_C_LEXER_DEFINITIONS // This line prevents the header file from replacing your definitions106// --END--107#endif108#endif109110#ifndef INCLUDE_STB_C_LEXER_H111#define INCLUDE_STB_C_LEXER_H112113typedef struct114{115 // lexer variables116 char *input_stream;117 char *eof;118 char *parse_point;119 char *string_storage;120 int string_storage_len;121122 // lexer parse location for error messages123 char *where_firstchar;124 char *where_lastchar;125126 // lexer token variables127 long token;128 double real_number;129 long int_number;130 char *string;131 int string_len;132} stb_lexer;133134typedef struct135{136 int line_number;137 int line_offset;138} stb_lex_location;139140#ifdef __cplusplus141extern "C" {142#endif143144extern void stb_c_lexer_init(stb_lexer *lexer, const char *input_stream, const char *input_stream_end, char *string_store, int store_length);145// this function initialize the 'lexer' structure146// Input:147// - input_stream points to the file to parse, loaded into memory148// - input_stream_end points to the end of the file, or NULL if you use 0-for-EOF149// - string_store is storage the lexer can use for storing parsed strings and identifiers150// - store_length is the length of that storage151152extern int stb_c_lexer_get_token(stb_lexer *lexer);153// this function returns non-zero if a token is parsed, or 0 if at EOF154// Output:155// - lexer->token is the token ID, which is unicode code point for a single-char token, < 0 for a multichar or eof or error156// - lexer->real_number is a double constant value for CLEX_floatlit, or CLEX_intlit if STB_C_LEX_INTEGERS_AS_DOUBLES157// - lexer->int_number is an integer constant for CLEX_intlit if !STB_C_LEX_INTEGERS_AS_DOUBLES, or character for CLEX_charlit158// - lexer->string is a 0-terminated string for CLEX_dqstring or CLEX_sqstring or CLEX_identifier159// - lexer->string_len is the byte length of lexer->string160161extern void stb_c_lexer_get_location(const stb_lexer *lexer, const char *where, stb_lex_location *loc);162// this inefficient function returns the line number and character offset of a163// given location in the file as returned by stb_lex_token. Because it's inefficient,164// you should only call it for errors, not for every token.165// For error messages of invalid tokens, you typically want the location of the start166// of the token (which caused the token to be invalid). For bugs involving legit167// tokens, you can report the first or the range.168// Output:169// - loc->line_number is the line number in the file, counting from 1, of the location170// - loc->line_offset is the char-offset in the line, counting from 0, of the location171172173#ifdef __cplusplus174}175#endif176177enum178{179 CLEX_eof = 256,180 CLEX_parse_error,181 CLEX_intlit ,182 CLEX_floatlit ,183 CLEX_id ,184 CLEX_dqstring ,185 CLEX_sqstring ,186 CLEX_charlit ,187 CLEX_eq ,188 CLEX_noteq ,189 CLEX_lesseq ,190 CLEX_greatereq ,191 CLEX_andand ,192 CLEX_oror ,193 CLEX_shl ,194 CLEX_shr ,195 CLEX_plusplus ,196 CLEX_minusminus ,197 CLEX_pluseq ,198 CLEX_minuseq ,199 CLEX_muleq ,200 CLEX_diveq ,201 CLEX_modeq ,202 CLEX_andeq ,203 CLEX_oreq ,204 CLEX_xoreq ,205 CLEX_arrow ,206 CLEX_eqarrow ,207 CLEX_shleq, CLEX_shreq,208209 CLEX_first_unused_token210211};212#endif // INCLUDE_STB_C_LEXER_H213214#ifdef STB_C_LEXER_IMPLEMENTATION215216// Hacky definitions so we can easily #if on them217#define Y(x) 1218#define N(x) 0219220#if STB_C_LEX_INTEGERS_AS_DOUBLES(x)221typedef double stb__clex_int;222#define intfield real_number223#define STB__clex_int_as_double224#else225typedef long stb__clex_int;226#define intfield int_number227#endif228229// Convert these config options to simple conditional #defines so we can more230// easily test them once we've change the meaning of Y/N231232#if STB_C_LEX_PARSE_SUFFIXES(x)233#define STB__clex_parse_suffixes234#endif235236#if STB_C_LEX_C99_HEX_FLOATS(x)237#define STB__clex_hex_floats238#endif239240#if STB_C_LEX_C_HEX_INTS(x)241#define STB__clex_hex_ints242#endif243244#if STB_C_LEX_C_DECIMAL_INTS(x)245#define STB__clex_decimal_ints246#endif247248#if STB_C_LEX_C_OCTAL_INTS(x)249#define STB__clex_octal_ints250#endif251252#if STB_C_LEX_C_DECIMAL_FLOATS(x)253#define STB__clex_decimal_floats254#endif255256#if STB_C_LEX_DISCARD_PREPROCESSOR(x)257#define STB__clex_discard_preprocessor258#endif259260#if STB_C_LEX_USE_STDLIB(x) && (!defined(STB__clex_hex_floats) || __STDC_VERSION__ >= 199901L)261#define STB__CLEX_use_stdlib262#include <stdlib.h>263#endif264265// Now for the rest of the file we'll use the basic definition where266// where Y expands to its contents and N expands to nothing267#undef Y268#define Y(a) a269#undef N270#define N(a)271272// API function273void stb_c_lexer_init(stb_lexer *lexer, const char *input_stream, const char *input_stream_end, char *string_store, int store_length)274{275 lexer->input_stream = (char *) input_stream;276 lexer->eof = (char *) input_stream_end;277 lexer->parse_point = (char *) input_stream;278 lexer->string_storage = string_store;279 lexer->string_storage_len = store_length;280}281282// API function283void stb_c_lexer_get_location(const stb_lexer *lexer, const char *where, stb_lex_location *loc)284{285 char *p = lexer->input_stream;286 int line_number = 1;287 int char_offset = 0;288 while (*p && p < where) {289 if (*p == '\n' || *p == '\r') {290 p += (p[0]+p[1] == '\r'+'\n' ? 2 : 1); // skip newline291 line_number += 1;292 char_offset = 0;293 } else {294 ++p;295 ++char_offset;296 }297 }298 loc->line_number = line_number;299 loc->line_offset = char_offset;300}301302// main helper function for returning a parsed token303static int stb__clex_token(stb_lexer *lexer, int token, char *start, char *end)304{305 lexer->token = token;306 lexer->where_firstchar = start;307 lexer->where_lastchar = end;308 lexer->parse_point = end+1;309 return 1;310}311312// helper function for returning eof313static int stb__clex_eof(stb_lexer *lexer)314{315 lexer->token = CLEX_eof;316 return 0;317}318319static int stb__clex_iswhite(int x)320{321 return x == ' ' || x == '\t' || x == '\r' || x == '\n' || x == '\f';322}323324static const char *stb__strchr(const char *str, int ch)325{326 for (; *str; ++str)327 if (*str == ch)328 return str;329 return 0;330}331332// parse suffixes at the end of a number333static int stb__clex_parse_suffixes(stb_lexer *lexer, long tokenid, char *start, char *cur, const char *suffixes)334{335 #ifdef STB__clex_parse_suffixes336 lexer->string = lexer->string_storage;337 lexer->string_len = 0;338339 while ((*cur >= 'a' && *cur <= 'z') || (*cur >= 'A' && *cur <= 'Z')) {340 if (stb__strchr(suffixes, *cur) == 0)341 return stb__clex_token(lexer, CLEX_parse_error, start, cur);342 if (lexer->string_len+1 >= lexer->string_storage_len)343 return stb__clex_token(lexer, CLEX_parse_error, start, cur);344 lexer->string[lexer->string_len++] = *cur++;345 }346 #else347 suffixes = suffixes; // attempt to suppress warnings348 #endif349 return stb__clex_token(lexer, tokenid, start, cur-1);350}351352#ifndef STB__CLEX_use_stdlib353static double stb__clex_pow(double base, unsigned int exponent)354{355 double value=1;356 for ( ; exponent; exponent >>= 1) {357 if (exponent & 1)358 value *= base;359 base *= base;360 }361 return value;362}363364static double stb__clex_parse_float(char *p, char **q)365{366 char *s = p;367 double value=0;368 int base=10;369 int exponent=0;370371#ifdef STB__clex_hex_floats372 if (*p == '0') {373 if (p[1] == 'x' || p[1] == 'X') {374 base=16;375 p += 2;376 }377 }378#endif379380 for (;;) {381 if (*p >= '0' && *p <= '9')382 value = value*base + (*p++ - '0');383#ifdef STB__clex_hex_floats384 else if (base == 16 && *p >= 'a' && *p <= 'f')385 value = value*base + 10 + (*p++ - 'a');386 else if (base == 16 && *p >= 'A' && *p <= 'F')387 value = value*base + 10 + (*p++ - 'A');388#endif389 else390 break;391 }392393 if (*p == '.') {394 double pow, addend = 0;395 ++p;396 for (pow=1; ; pow*=base) {397 if (*p >= '0' && *p <= '9')398 addend = addend*base + (*p++ - '0');399#ifdef STB__clex_hex_floats400 else if (base == 16 && *p >= 'a' && *p <= 'f')401 addend = addend*base + 10 + (*p++ - 'a');402 else if (base == 16 && *p >= 'A' && *p <= 'F')403 addend = addend*base + 10 + (*p++ - 'A');404#endif405 else406 break;407 }408 value += addend / pow;409 }410#ifdef STB__clex_hex_floats411 if (base == 16) {412 // exponent required for hex float literal413 if (*p != 'p' && *p != 'P') {414 *q = s;415 return 0;416 }417 exponent = 1;418 } else419#endif420 exponent = (*p == 'e' || *p == 'E');421422 if (exponent) {423 int sign = p[1] == '-';424 unsigned int exponent=0;425 double power=1;426 ++p;427 if (*p == '-' || *p == '+')428 ++p;429 while (*p >= '0' && *p <= '9')430 exponent = exponent*10 + (*p++ - '0');431432#ifdef STB__clex_hex_floats433 if (base == 16)434 power = stb__clex_pow(2, exponent);435 else436#endif437 power = stb__clex_pow(10, exponent);438 if (sign)439 value /= power;440 else441 value *= power;442 }443 *q = p;444 return value;445}446#endif447448static int stb__clex_parse_char(char *p, char **q)449{450 if (*p == '\\') {451 *q = p+2; // tentatively guess we'll parse two characters452 switch(p[1]) {453 case '\\': return '\\';454 case '\'': return '\'';455 case '"': return '"';456 case 't': return '\t';457 case 'f': return '\f';458 case 'n': return '\n';459 case 'r': return '\r';460 case '0': return '\0'; // @TODO ocatal constants461 case 'x': case 'X': return -1; // @TODO hex constants462 case 'u': return -1; // @TODO unicode constants463 }464 }465 *q = p+1;466 return (unsigned char) *p;467}468469static int stb__clex_parse_string(stb_lexer *lexer, char *p, int type)470{471 char *start = p;472 char delim = *p++; // grab the " or ' for later matching473 char *out = lexer->string_storage;474 char *outend = lexer->string_storage + lexer->string_storage_len;475 while (*p != delim) {476 int n;477 if (*p == '\\') {478 char *q;479 n = stb__clex_parse_char(p, &q);480 if (n < 0)481 return stb__clex_token(lexer, CLEX_parse_error, start, q);482 p = q;483 } else {484 // @OPTIMIZE: could speed this up by looping-while-not-backslash485 n = (unsigned char) *p++;486 }487 if (out+1 > outend)488 return stb__clex_token(lexer, CLEX_parse_error, start, p);489 // @TODO expand unicode escapes to UTF8490 *out++ = (char) n;491 }492 *out = 0;493 lexer->string = lexer->string_storage;494 lexer->string_len = (int) (out - lexer->string_storage);495 return stb__clex_token(lexer, type, start, p);496}497498int stb_c_lexer_get_token(stb_lexer *lexer)499{500 char *p = lexer->parse_point;501502 // skip whitespace and comments503 for (;;) {504 #ifdef STB_C_LEX_ISWHITE505 while (p != lexer->stream_end) {506 int n;507 n = STB_C_LEX_ISWHITE(p);508 if (n == 0) break;509 if (lexer->eof && lexer->eof - lexer->parse_point < n)510 return stb__clex_token(tok, CLEX_parse_error, p,lexer->eof-1);511 p += n;512 }513 #else514 while (p != lexer->eof && stb__clex_iswhite(*p))515 ++p;516 #endif517518 STB_C_LEX_CPP_COMMENTS(519 if (p != lexer->eof && p[0] == '/' && p[1] == '/') {520 while (p != lexer->eof && *p != '\r' && *p != '\n')521 ++p;522 continue;523 }524 )525526 STB_C_LEX_C_COMMENTS(527 if (p != lexer->eof && p[0] == '/' && p[1] == '*') {528 char *start = p;529 p += 2;530 while (p != lexer->eof && (p[0] != '*' || p[1] != '/'))531 ++p;532 if (p == lexer->eof)533 return stb__clex_token(lexer, CLEX_parse_error, start, p-1);534 p += 2;535 continue;536 }537 )538539 #ifdef STB__clex_discard_preprocessor540 // @TODO this discards everything after a '#', regardless541 // of where in the line the # is, rather than requiring it542 // be at the start. (because this parser doesn't otherwise543 // check for line breaks!)544 if (p != lexer->eof && p[0] == '#') {545 while (p != lexer->eof && *p != '\r' && *p != '\n')546 ++p;547 continue;548 }549 #endif550551 break;552 }553554 if (p == lexer->eof)555 return stb__clex_eof(lexer);556557 switch (*p) {558 default:559 if ( (*p >= 'a' && *p <= 'z')560 || (*p >= 'A' && *p <= 'Z')561 || *p == '_' || (unsigned char) *p >= 128 // >= 128 is UTF8 char562 STB_C_LEX_DOLLAR_IDENTIFIER( || *p == '$' ) )563 {564 int n = 0;565 lexer->string = lexer->string_storage;566 do {567 if (n+1 >= lexer->string_storage_len)568 return stb__clex_token(lexer, CLEX_parse_error, p, p+n);569 lexer->string[n] = p[n];570 ++n;571 } while (572 (p[n] >= 'a' && p[n] <= 'z')573 || (p[n] >= 'A' && p[n] <= 'Z')574 || (p[n] >= '0' && p[n] <= '9') // allow digits in middle of identifier575 || p[n] == '_' || (unsigned char) p[n] >= 128576 STB_C_LEX_DOLLAR_IDENTIFIER( || p[n] == '$' )577 );578 lexer->string[n] = 0;579 lexer->string_len = n;580 return stb__clex_token(lexer, CLEX_id, p, p+n-1);581 }582583 // check for EOF584 STB_C_LEX_0_IS_EOF(585 if (*p == 0)586 return stb__clex_eof(lexer);587 )588589 single_char:590 // not an identifier, return the character as itself591 return stb__clex_token(lexer, *p, p, p);592593 case '+':594 if (p+1 != lexer->eof) {595 STB_C_LEX_C_INCREMENTS(if (p[1] == '+') return stb__clex_token(lexer, CLEX_plusplus, p,p+1);)596 STB_C_LEX_C_ARITHEQ( if (p[1] == '=') return stb__clex_token(lexer, CLEX_pluseq , p,p+1);)597 }598 goto single_char;599 case '-':600 if (p+1 != lexer->eof) {601 STB_C_LEX_C_INCREMENTS(if (p[1] == '-') return stb__clex_token(lexer, CLEX_minusminus, p,p+1);)602 STB_C_LEX_C_ARITHEQ( if (p[1] == '=') return stb__clex_token(lexer, CLEX_minuseq , p,p+1);)603 STB_C_LEX_C_ARROW( if (p[1] == '>') return stb__clex_token(lexer, CLEX_arrow , p,p+1);)604 }605 goto single_char;606 case '&':607 if (p+1 != lexer->eof) {608 STB_C_LEX_C_LOGICAL( if (p[1] == '&') return stb__clex_token(lexer, CLEX_andand, p,p+1);)609 STB_C_LEX_C_BITWISEEQ(if (p[1] == '=') return stb__clex_token(lexer, CLEX_andeq , p,p+1);)610 }611 goto single_char;612 case '|':613 if (p+1 != lexer->eof) {614 STB_C_LEX_C_LOGICAL( if (p[1] == '|') return stb__clex_token(lexer, CLEX_oror, p,p+1);)615 STB_C_LEX_C_BITWISEEQ(if (p[1] == '=') return stb__clex_token(lexer, CLEX_oreq, p,p+1);)616 }617 goto single_char;618 case '=':619 if (p+1 != lexer->eof) {620 STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_eq, p,p+1);)621 STB_C_LEX_EQUAL_ARROW( if (p[1] == '>') return stb__clex_token(lexer, CLEX_eqarrow, p,p+1);)622 }623 goto single_char;624 case '!':625 STB_C_LEX_C_COMPARISONS(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_noteq, p,p+1);)626 goto single_char;627 case '^':628 STB_C_LEX_C_BITWISEEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_xoreq, p,p+1));629 goto single_char;630 case '%':631 STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_modeq, p,p+1));632 goto single_char;633 case '*':634 STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_muleq, p,p+1));635 goto single_char;636 case '/':637 STB_C_LEX_C_ARITHEQ(if (p+1 != lexer->eof && p[1] == '=') return stb__clex_token(lexer, CLEX_diveq, p,p+1));638 goto single_char;639 case '<':640 if (p+1 != lexer->eof) {641 STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_lesseq, p,p+1);)642 STB_C_LEX_C_SHIFTS( if (p[1] == '<') {643 STB_C_LEX_C_ARITHEQ(if (p+2 != lexer->eof && p[2] == '=')644 return stb__clex_token(lexer, CLEX_shleq, p,p+2);)645 return stb__clex_token(lexer, CLEX_shl, p,p+1);646 }647 )648 }649 goto single_char;650 case '>':651 if (p+1 != lexer->eof) {652 STB_C_LEX_C_COMPARISONS(if (p[1] == '=') return stb__clex_token(lexer, CLEX_greatereq, p,p+1);)653 STB_C_LEX_C_SHIFTS( if (p[1] == '>') {654 STB_C_LEX_C_ARITHEQ(if (p+2 != lexer->eof && p[2] == '=')655 return stb__clex_token(lexer, CLEX_shreq, p,p+2);)656 return stb__clex_token(lexer, CLEX_shr, p,p+1);657 }658 )659 }660 goto single_char;661662 case '"':663 STB_C_LEX_C_DQ_STRINGS(return stb__clex_parse_string(lexer, p, CLEX_dqstring);)664 goto single_char;665 case '\'':666 STB_C_LEX_C_SQ_STRINGS(return stb__clex_parse_string(lexer, p, CLEX_sqstring);)667 STB_C_LEX_C_CHARS(668 {669 char *start = p;670 lexer->int_number = stb__clex_parse_char(p+1, &p);671 if (lexer->int_number < 0)672 return stb__clex_token(lexer, CLEX_parse_error, start,start);673 if (p == lexer->eof || *p != '\'')674 return stb__clex_token(lexer, CLEX_parse_error, start,p);675 return stb__clex_token(lexer, CLEX_charlit, start, p+1);676 })677 goto single_char;678679 case '0':680 #if defined(STB__clex_hex_ints) || defined(STB__clex_hex_floats)681 if (p+1 != lexer->eof) {682 if (p[1] == 'x' || p[1] == 'X') {683 char *q;684685 #ifdef STB__clex_hex_floats686 for (q=p+2;687 q != lexer->eof && ((*q >= '0' && *q <= '9') || (*q >= 'a' && *q <= 'f') || (*q >= 'A' && *q <= 'F'));688 ++q);689 if (q != lexer->eof) {690 if (*q == '.' STB_C_LEX_FLOAT_NO_DECIMAL(|| *q == 'p' || *q == 'P')) {691 #ifdef STB__CLEX_use_stdlib692 lexer->real_number = strtod((char *) p, (char**) &q);693 #else694 lexer->real_number = stb__clex_parse_float(p, &q);695 #endif696697 if (p == q)698 return stb__clex_token(lexer, CLEX_parse_error, p,q);699 return stb__clex_parse_suffixes(lexer, CLEX_floatlit, p,q, STB_C_LEX_FLOAT_SUFFIXES);700701 }702 }703 #endif // STB__CLEX_hex_floats704705 #ifdef STB__clex_hex_ints706 #ifdef STB__CLEX_use_stdlib707 lexer->int_number = strtol((char *) p, (char **) &q, 16);708 #else709 {710 stb__clex_int n=0;711 for (q=p+2; q != lexer->eof; ++q) {712 if (*q >= '0' && *q <= '9')713 n = n*16 + (*q - '0');714 else if (*q >= 'a' && *q <= 'f')715 n = n*16 + (*q - 'a') + 10;716 else if (*q >= 'A' && *q <= 'F')717 n = n*16 + (*q - 'A') + 10;718 else719 break;720 }721 lexer->int_number = n;722 }723 #endif724 if (q == p+2)725 return stb__clex_token(lexer, CLEX_parse_error, p-2,p-1);726 return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_HEX_SUFFIXES);727 #endif728 }729 }730 #endif // defined(STB__clex_hex_ints) || defined(STB__clex_hex_floats)731 // can't test for octal because we might parse '0.0' as float or as '0' '.' '0',732 // so have to do float first733734 /* FALL THROUGH */735 case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':736737 #ifdef STB__clex_decimal_floats738 {739 char *q = p;740 while (q != lexer->eof && (*q >= '0' && *q <= '9'))741 ++q;742 if (q != lexer->eof) {743 if (*q == '.' STB_C_LEX_FLOAT_NO_DECIMAL(|| *q == 'e' || *q == 'E')) {744 #ifdef STB__CLEX_use_stdlib745 lexer->real_number = strtod((char *) p, (char**) &q);746 #else747 lexer->real_number = stb__clex_parse_float(p, &q);748 #endif749750 return stb__clex_parse_suffixes(lexer, CLEX_floatlit, p,q, STB_C_LEX_FLOAT_SUFFIXES);751752 }753 }754 }755 #endif // STB__clex_decimal_floats756757 #ifdef STB__clex_octal_ints758 if (p[0] == '0') {759 char *q = p;760 #ifdef STB__CLEX_use_stdlib761 lexer->int_number = strtol((char *) p, (char **) &q, 8);762 #else763 stb__clex_int n=0;764 while (q != lexer->eof) {765 if (*q >= '0' && *q <= '7')766 n = n*8 + (*q - '0');767 else768 break;769 ++q;770 }771 if (q != lexer->eof && (*q == '8' || *q=='9'))772 return stb__clex_token(lexer, CLEX_parse_error, p, q);773 lexer->int_number = n;774 #endif775 return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_OCTAL_SUFFIXES);776 }777 #endif // STB__clex_octal_ints778779 #ifdef STB__clex_decimal_ints780 {781 char *q = p;782 #ifdef STB__CLEX_use_stdlib783 lexer->int_number = strtol((char *) p, (char **) &q, 10);784 #else785 stb__clex_int n=0;786 while (q != lexer->eof) {787 if (*q >= '0' && *q <= '9')788 n = n*10 + (*q - '0');789 else790 break;791 ++q;792 }793 lexer->int_number = n;794 #endif795 return stb__clex_parse_suffixes(lexer, CLEX_intlit, p,q, STB_C_LEX_OCTAL_SUFFIXES);796 }797 #endif // STB__clex_decimal_ints798 goto single_char;799 }800}801#endif // STB_C_LEXER_IMPLEMENTATION802803#ifdef STB_C_LEXER_SELF_TEST804#define _CRT_SECURE_NO_WARNINGS805#include <stdio.h>806#include <stdlib.h>807808static void print_token(stb_lexer *lexer)809{810 switch (lexer->token) {811 case CLEX_id : printf("_%s", lexer->string); break;812 case CLEX_eq : printf("=="); break;813 case CLEX_noteq : printf("!="); break;814 case CLEX_lesseq : printf("<="); break;815 case CLEX_greatereq : printf(">="); break;816 case CLEX_andand : printf("&&"); break;817 case CLEX_oror : printf("||"); break;818 case CLEX_shl : printf("<<"); break;819 case CLEX_shr : printf(">>"); break;820 case CLEX_plusplus : printf("++"); break;821 case CLEX_minusminus: printf("--"); break;822 case CLEX_arrow : printf("->"); break;823 case CLEX_andeq : printf("&="); break;824 case CLEX_oreq : printf("|="); break;825 case CLEX_xoreq : printf("^="); break;826 case CLEX_pluseq : printf("+="); break;827 case CLEX_minuseq : printf("-="); break;828 case CLEX_muleq : printf("*="); break;829 case CLEX_diveq : printf("/="); break;830 case CLEX_modeq : printf("%%="); break;831 case CLEX_shleq : printf("<<="); break;832 case CLEX_shreq : printf(">>="); break;833 case CLEX_eqarrow : printf("=>"); break;834 case CLEX_dqstring : printf("\"%s\"", lexer->string); break;835 case CLEX_sqstring : printf("'\"%s\"'", lexer->string); break;836 case CLEX_charlit : printf("'%s'", lexer->string); break;837 #if defined(STB__clex_int_as_double) && !defined(STB__CLEX_use_stdlib)838 case CLEX_intlit : printf("#%g", lexer->real_number); break;839 #else840 case CLEX_intlit : printf("#%ld", lexer->int_number); break;841 #endif842 case CLEX_floatlit : printf("%g", lexer->real_number); break;843 default:844 if (lexer->token >= 0 && lexer->token < 256)845 printf("%c", (int) lexer->token);846 else {847 printf("<<<UNKNOWN TOKEN %ld >>>\n", lexer->token);848 }849 break;850 }851}852853/* Force a test854of parsing855multiline comments */856857/*/ comment /*/858/**/ extern /**/859860void dummy(void)861{862 double some_floats[] = {863 1.0501, -10.4e12, 5E+10,864#if 0 // not supported in C++ or C-pre-99, so don't try to compile it, but let our parser test it865 0x1.0p+24, 0xff.FP-8, 0x1p-23,866#endif867 4.868 };869 (void) sizeof(some_floats);870 (void) some_floats[1];871872 printf("test %d",1); // https://github.com/nothings/stb/issues/13873}874875int main(int argc, char **argv)876{877 FILE *f = fopen("stb_c_lexer.h","rb");878 char *text = (char *) malloc(1 << 20);879 int len = f ? (int) fread(text, 1, 1<<20, f) : -1;880 stb_lexer lex;881 if (len < 0) {882 fprintf(stderr, "Error opening file\n");883 free(text);884 fclose(f);885 return 1;886 }887 fclose(f);888889 stb_c_lexer_init(&lex, text, text+len, (char *) malloc(0x10000), 0x10000);890 while (stb_c_lexer_get_token(&lex)) {891 if (lex.token == CLEX_parse_error) {892 printf("\n<<<PARSE ERROR>>>\n");893 break;894 }895 print_token(&lex);896 printf(" ");897 }898 return 0;899}900#endif901/*902------------------------------------------------------------------------------903This software is available under 2 licenses -- choose whichever you prefer.904------------------------------------------------------------------------------905ALTERNATIVE A - MIT License906Copyright (c) 2017 Sean Barrett907Permission is hereby granted, free of charge, to any person obtaining a copy of908this software and associated documentation files (the "Software"), to deal in909the Software without restriction, including without limitation the rights to910use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies911of the Software, and to permit persons to whom the Software is furnished to do912so, subject to the following conditions:913The above copyright notice and this permission notice shall be included in all914copies or substantial portions of the Software.915THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR916IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,917FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE918AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER919LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,920OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE921SOFTWARE.922------------------------------------------------------------------------------923ALTERNATIVE B - Public Domain (www.unlicense.org)924This is free and unencumbered software released into the public domain.925Anyone is free to copy, modify, publish, use, compile, sell, or distribute this926software, either in source code form or as a compiled binary, for any purpose,927commercial or non-commercial, and by any means.928In jurisdictions that recognize copyright laws, the author or authors of this929software dedicate any and all copyright interest in the software to the public930domain. We make this dedication for the benefit of the public at large and to931the detriment of our heirs and successors. We intend this dedication to be an932overt act of relinquishment in perpetuity of all present and future rights to933this software under copyright law.934THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR935IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,936FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE937AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN938ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION939WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.940------------------------------------------------------------------------------941*/