better code for numerical escapes

This commit is contained in:
Roberto Ierusalimschy 2011-07-15 09:30:41 -03:00
parent 7978a8d8b2
commit 067f761739
1 changed files with 19 additions and 28 deletions

47
llex.c
View File

@ -1,5 +1,5 @@
/* /*
** $Id: llex.c,v 2.52 2011/07/08 19:17:30 roberto Exp roberto $ ** $Id: llex.c,v 2.53 2011/07/08 20:01:38 roberto Exp roberto $
** Lexical Analyzer ** Lexical Analyzer
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@ -297,39 +297,30 @@ static void escerror (LexState *ls, int *c, int n, const char *msg) {
static int readhexaesc (LexState *ls) { static int readhexaesc (LexState *ls) {
int c[3]; /* keep input for error message */ int c[3], i; /* keep input for error message */
int i = 2; /* at least 'x?' will go to error message */ int r = 0; /* result accumulator */
c[0] = 'x'; c[0] = 'x'; /* for error message */
c[1] = next(ls); /* first hexa digit */ for (i = 1; i < 3; i++) { /* read two hexa digits */
if (lisxdigit(c[1])) { c[i] = next(ls);
c[i++] = next(ls); /* second hexa digit */ if (!lisxdigit(c[i]))
if (lisxdigit(c[2])) escerror(ls, c, i + 1, "hexadecimal digit expected");
return (luaO_hexavalue(c[1]) << 4) + luaO_hexavalue(c[2]); r = (r << 4) + luaO_hexavalue(c[i]);
/* else go through to error */
} }
escerror(ls, c, i, "hexadecimal digit expected"); return r;
return 0; /* to avoid warnings */
} }
static int readdecesc (LexState *ls) { static int readdecesc (LexState *ls) {
int c[3], r; int c[3], i;
int i = 2; /* at least two chars will be read */ int r = 0; /* result accumulator */
c[0] = ls->current; /* first char must be a digit */ for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
c[1] = next(ls); /* read second char */ c[i] = ls->current;
r = c[0] - '0'; /* partial result */ r = 10*r + c[i] - '0';
if (lisdigit(c[1])) { next(ls);
c[i++] = next(ls); /* read third char */
r = 10*r + c[1] - '0'; /* update result */
if (lisdigit(c[2])) {
r = 10*r + c[2] - '0'; /* update result */
if (r > UCHAR_MAX)
escerror(ls, c, i, "decimal escape too large");
return r;
}
} }
/* else, has read one character that was not a digit */ if (r > UCHAR_MAX)
zungetc(ls->z); /* return it to input stream */ escerror(ls, c, i, "decimal escape too large");
zungetc(ls->z);
return r; return r;
} }