PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/Rexample/rdev/src/library/tools/src/gramLatex.y

https://bitbucket.org/pengyuut/rexample
Happy | 925 lines | 778 code | 147 blank | 0 comment | 0 complexity | 9a45d3c60a56b96d868770dfc6f7ee4a MD5 | raw file
  1. %{
  2. /*
  3. * R : A Computer Langage for Statistical Data Analysis
  4. * Copyright (C) 1995, 1996, 1997 Robert Gentleman and Ross Ihaka
  5. * Copyright (C) 1997--2013 The R Core Team
  6. * Copyright (C) 2010 Duncan Murdoch
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, a copy is available at
  20. * http://www.r-project.org/Licenses/
  21. */
  22. #ifdef HAVE_CONFIG_H
  23. #include <config.h>
  24. #endif
  25. #include <Defn.h>
  26. #include <Parse.h>
  27. #define STRICT_R_HEADERS
  28. #include <R_ext/RS.h> /* for R_chk_* allocation */
  29. #include <ctype.h>
  30. #include <R_ext/Print.h>
  31. /* bison creates a non-static symbol yylloc in both gramLatex.o and gramRd.o,
  32. so remap */
  33. #define yylloc yyllocL
  34. #define DEBUGVALS 0 /* 1 causes detailed internal state output to R console */
  35. #define DEBUGMODE 0 /* 1 causes Bison output of parse state, to stdout or stderr */
  36. #define YYERROR_VERBOSE 1
  37. static void yyerror(const char *);
  38. static int yylex();
  39. static int yyparse(void);
  40. #define yyconst const
  41. typedef struct yyltype
  42. {
  43. int first_line;
  44. int first_column;
  45. int first_byte;
  46. int last_line;
  47. int last_column;
  48. int last_byte;
  49. } yyltype;
  50. # define YYLTYPE yyltype
  51. # define YYLLOC_DEFAULT(Current, Rhs, N) \
  52. do \
  53. if (YYID (N)) \
  54. { \
  55. (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
  56. (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
  57. (Current).first_byte = YYRHSLOC (Rhs, 1).first_byte; \
  58. (Current).last_line = YYRHSLOC (Rhs, N).last_line; \
  59. (Current).last_column = YYRHSLOC (Rhs, N).last_column; \
  60. (Current).last_byte = YYRHSLOC (Rhs, N).last_byte; \
  61. } \
  62. else \
  63. { \
  64. (Current).first_line = (Current).last_line = \
  65. YYRHSLOC (Rhs, 0).last_line; \
  66. (Current).first_column = (Current).last_column = \
  67. YYRHSLOC (Rhs, 0).last_column; \
  68. (Current).first_byte = (Current).last_byte = \
  69. YYRHSLOC (Rhs, 0).last_byte; \
  70. } \
  71. while (YYID (0))
  72. /* Useful defines so editors don't get confused ... */
  73. #define LBRACE '{'
  74. #define RBRACE '}'
  75. /* Functions used in the parsing process */
  76. static SEXP GrowList(SEXP, SEXP);
  77. static int KeywordLookup(const char *);
  78. static SEXP NewList(void);
  79. static SEXP makeSrcref(YYLTYPE *, SEXP);
  80. static int xxgetc();
  81. static int xxungetc(int);
  82. /* Internal lexer / parser state variables */
  83. static char const yyunknown[] = "unknown macro"; /* our message, not bison's */
  84. typedef struct ParseState ParseState;
  85. struct ParseState {
  86. int xxlineno, xxbyteno, xxcolno;
  87. int xxDebugTokens; /* non-zero causes debug output to R console */
  88. SEXP Value;
  89. int xxinitvalue;
  90. SEXP xxInVerbEnv; /* Are we currently in a verbatim environment? If
  91. so, this is the string to end it. If not,
  92. this is NULL */
  93. SEXP xxVerbatimList;/* A STRSXP containing all the verbatim environment names */
  94. SEXP SrcFile; /* parseLatex will *always* supply a srcfile */
  95. ParseState *prevState;
  96. };
  97. static Rboolean busy = FALSE;
  98. static ParseState parseState;
  99. /* Routines used to build the parse tree */
  100. static SEXP xxnewlist(SEXP);
  101. static SEXP xxlist(SEXP, SEXP);
  102. static void xxsavevalue(SEXP, YYLTYPE *);
  103. static SEXP xxtag(SEXP, int, YYLTYPE *);
  104. static SEXP xxenv(SEXP, SEXP, SEXP, YYLTYPE *);
  105. static SEXP xxmath(SEXP, YYLTYPE *);
  106. static SEXP xxblock(SEXP, YYLTYPE *);
  107. static void xxSetInVerbEnv(SEXP);
  108. static int mkMarkup(int);
  109. static int mkText(int);
  110. static int mkComment(int);
  111. static int mkVerb(int);
  112. static int mkVerbEnv();
  113. #define YYSTYPE SEXP
  114. %}
  115. %token END_OF_INPUT ERROR
  116. %token MACRO
  117. %token TEXT COMMENT
  118. %token BEGIN END VERB
  119. /* Recent bison has <> to represent all of the destructors below, but we don't assume it */
  120. /* I think we need to list everything here which occurs before the last item in a
  121. pattern, just in case the last item is unmatched and we need to back out. But
  122. it is safe to list more, so we do. */
  123. %destructor { UNPROTECT_PTR($$); } MACRO TEXT COMMENT BEGIN END
  124. %%
  125. Init: Items END_OF_INPUT { xxsavevalue($1, &@$); return 0; }
  126. | END_OF_INPUT { xxsavevalue(NULL, &@$); return 0; }
  127. | error { PROTECT(parseState.Value = R_NilValue); YYABORT; }
  128. ;
  129. Items: Item { $$ = xxnewlist($1); }
  130. | math { $$ = xxnewlist($1); }
  131. | Items Item { $$ = xxlist($1, $2); }
  132. | Items math { $$ = xxlist($1, $2); }
  133. nonMath: Item { $$ = xxnewlist($1); }
  134. | nonMath Item { $$ = xxlist($1, $2); }
  135. Item: TEXT { $$ = xxtag($1, TEXT, &@$); }
  136. | COMMENT { $$ = xxtag($1, COMMENT, &@$); }
  137. | MACRO { $$ = xxtag($1, MACRO, &@$); }
  138. | VERB { $$ = xxtag($1, VERB, &@$); }
  139. | environment { $$ = $1; }
  140. | block { $$ = $1; }
  141. environment: BEGIN '{' TEXT '}' { xxSetInVerbEnv($3); }
  142. Items END '{' TEXT '}' { $$ = xxenv($3, $6, $9, &@$);
  143. UNPROTECT_PTR($1); UNPROTECT_PTR($7); }
  144. math: '$' nonMath '$' { $$ = xxmath($2, &@$); }
  145. block: '{' Items '}' { $$ = xxblock($2, &@$); }
  146. | '{' '}' { $$ = xxblock(NULL, &@$); }
  147. %%
  148. static SEXP xxnewlist(SEXP item)
  149. {
  150. SEXP ans, tmp;
  151. #if DEBUGVALS
  152. Rprintf("xxnewlist(item=%p)", item);
  153. #endif
  154. PROTECT(tmp = NewList());
  155. if (item) {
  156. PROTECT(ans = GrowList(tmp, item));
  157. UNPROTECT_PTR(tmp);
  158. UNPROTECT_PTR(item);
  159. } else ans = tmp;
  160. #if DEBUGVALS
  161. Rprintf(" result: %p is length %d\n", ans, length(ans));
  162. #endif
  163. return ans;
  164. }
  165. static SEXP xxlist(SEXP oldlist, SEXP item)
  166. {
  167. SEXP ans;
  168. #if DEBUGVALS
  169. Rprintf("xxlist(oldlist=%p, item=%p)", oldlist, item);
  170. #endif
  171. PROTECT(ans = GrowList(oldlist, item));
  172. UNPROTECT_PTR(item);
  173. UNPROTECT_PTR(oldlist);
  174. #if DEBUGVALS
  175. Rprintf(" result: %p is length %d\n", ans, length(ans));
  176. #endif
  177. return ans;
  178. }
  179. static SEXP xxenv(SEXP begin, SEXP body, SEXP end, YYLTYPE *lloc)
  180. {
  181. SEXP ans;
  182. #if DEBUGVALS
  183. Rprintf("xxenv(begin=%p, body=%p, end=%p)", begin, body, end);
  184. #endif
  185. PROTECT(ans = allocVector(VECSXP, 2));
  186. SET_VECTOR_ELT(ans, 0, begin);
  187. UNPROTECT_PTR(begin);
  188. if (!isNull(body)) {
  189. SET_VECTOR_ELT(ans, 1, PairToVectorList(CDR(body)));
  190. UNPROTECT_PTR(body);
  191. }
  192. /* FIXME: check that begin and end match */
  193. setAttrib(ans, R_SrcrefSymbol, makeSrcref(lloc, parseState.SrcFile));
  194. setAttrib(ans, install("latex_tag"), mkString("ENVIRONMENT"));
  195. if (!isNull(end))
  196. UNPROTECT_PTR(end);
  197. #if DEBUGVALS
  198. Rprintf(" result: %p\n", ans);
  199. #endif
  200. return ans;
  201. }
  202. static SEXP xxmath(SEXP body, YYLTYPE *lloc)
  203. {
  204. SEXP ans;
  205. #if DEBUGVALS
  206. Rprintf("xxmath(body=%p)", body);
  207. #endif
  208. PROTECT(ans = PairToVectorList(CDR(body)));
  209. UNPROTECT_PTR(body);
  210. setAttrib(ans, R_SrcrefSymbol, makeSrcref(lloc, parseState.SrcFile));
  211. setAttrib(ans, install("latex_tag"), mkString("MATH"));
  212. #if DEBUGVALS
  213. Rprintf(" result: %p\n", ans);
  214. #endif
  215. return ans;
  216. }
  217. static SEXP xxblock(SEXP body, YYLTYPE *lloc)
  218. {
  219. SEXP ans;
  220. #if DEBUGVALS
  221. Rprintf("xxblock(body=%p)", body);
  222. #endif
  223. if (!body)
  224. PROTECT(ans = allocVector(VECSXP, 0));
  225. else {
  226. PROTECT(ans = PairToVectorList(CDR(body)));
  227. UNPROTECT_PTR(body);
  228. }
  229. setAttrib(ans, R_SrcrefSymbol, makeSrcref(lloc, parseState.SrcFile));
  230. setAttrib(ans, install("latex_tag"), mkString("BLOCK"));
  231. #if DEBUGVALS
  232. Rprintf(" result: %p\n", ans);
  233. #endif
  234. return ans;
  235. }
  236. static int VerbatimLookup(const char *s)
  237. {
  238. int i;
  239. for (i = 0; i < length(parseState.xxVerbatimList); i++) {
  240. if (strcmp(s, CHAR(STRING_ELT(parseState.xxVerbatimList, i))) == 0)
  241. return TRUE;
  242. }
  243. return FALSE;
  244. }
  245. static void xxSetInVerbEnv(SEXP envname)
  246. {
  247. char buffer[256];
  248. if (VerbatimLookup(CHAR(STRING_ELT(envname, 0)))) {
  249. snprintf(buffer, sizeof(buffer), "\\end{%s}", CHAR(STRING_ELT(envname, 0)));
  250. PROTECT(parseState.xxInVerbEnv = ScalarString(mkChar(buffer)));
  251. } else parseState.xxInVerbEnv = NULL;
  252. }
  253. static void xxsavevalue(SEXP items, YYLTYPE *lloc)
  254. {
  255. if (items) {
  256. PROTECT(parseState.Value = PairToVectorList(CDR(items)));
  257. UNPROTECT_PTR(items);
  258. } else {
  259. PROTECT(parseState.Value = allocVector(VECSXP, 1));
  260. SET_VECTOR_ELT(parseState.Value, 0, ScalarString(mkChar("")));
  261. setAttrib(VECTOR_ELT(parseState.Value, 0), install("latex_tag"), mkString("TEXT"));
  262. }
  263. if (!isNull(parseState.Value)) {
  264. setAttrib(parseState.Value, R_ClassSymbol, mkString("LaTeX"));
  265. setAttrib(parseState.Value, R_SrcrefSymbol, makeSrcref(lloc, parseState.SrcFile));
  266. }
  267. }
  268. static SEXP xxtag(SEXP item, int type, YYLTYPE *lloc)
  269. {
  270. setAttrib(item, install("latex_tag"), mkString(yytname[YYTRANSLATE(type)]));
  271. setAttrib(item, R_SrcrefSymbol, makeSrcref(lloc, parseState.SrcFile));
  272. return item;
  273. }
  274. /*----------------------------------------------------------------------------*/
  275. static int (*ptr_getc)(void);
  276. /* Private pushback, since file ungetc only guarantees one byte.
  277. We need up to one MBCS-worth */
  278. #define PUSHBACK_BUFSIZE 30
  279. static int pushback[PUSHBACK_BUFSIZE];
  280. static unsigned int npush = 0;
  281. static int prevpos = 0;
  282. static int prevlines[PUSHBACK_BUFSIZE];
  283. static int prevcols[PUSHBACK_BUFSIZE];
  284. static int prevbytes[PUSHBACK_BUFSIZE];
  285. static int xxgetc(void)
  286. {
  287. int c, oldpos;
  288. if(npush) c = pushback[--npush]; else c = ptr_getc();
  289. oldpos = prevpos;
  290. prevpos = (prevpos + 1) % PUSHBACK_BUFSIZE;
  291. prevbytes[prevpos] = parseState.xxbyteno;
  292. prevlines[prevpos] = parseState.xxlineno;
  293. /* We only advance the column for the 1st byte in UTF-8, so handle later bytes specially */
  294. if (0x80 <= (unsigned char)c && (unsigned char)c <= 0xBF) {
  295. parseState.xxcolno--;
  296. prevcols[prevpos] = prevcols[oldpos];
  297. } else
  298. prevcols[prevpos] = parseState.xxcolno;
  299. if (c == EOF) return R_EOF;
  300. R_ParseContextLast = (R_ParseContextLast + 1) % PARSE_CONTEXT_SIZE;
  301. R_ParseContext[R_ParseContextLast] = (char) c;
  302. if (c == '\n') {
  303. parseState.xxlineno += 1;
  304. parseState.xxcolno = 1;
  305. parseState.xxbyteno = 1;
  306. } else {
  307. parseState.xxcolno++;
  308. parseState.xxbyteno++;
  309. }
  310. if (c == '\t') parseState.xxcolno = ((parseState.xxcolno + 6) & ~7) + 1;
  311. R_ParseContextLine = parseState.xxlineno;
  312. return c;
  313. }
  314. static int xxungetc(int c)
  315. {
  316. /* this assumes that c was the result of xxgetc; if not, some edits will be needed */
  317. parseState.xxlineno = prevlines[prevpos];
  318. parseState.xxbyteno = prevbytes[prevpos];
  319. parseState.xxcolno = prevcols[prevpos];
  320. prevpos = (prevpos + PUSHBACK_BUFSIZE - 1) % PUSHBACK_BUFSIZE;
  321. R_ParseContextLine = parseState.xxlineno;
  322. R_ParseContext[R_ParseContextLast] = '\0';
  323. /* Mac OS X requires us to keep this non-negative */
  324. R_ParseContextLast = (R_ParseContextLast + PARSE_CONTEXT_SIZE - 1)
  325. % PARSE_CONTEXT_SIZE;
  326. if(npush >= PUSHBACK_BUFSIZE - 2) return R_EOF;
  327. pushback[npush++] = c;
  328. return c;
  329. }
  330. static SEXP makeSrcref(YYLTYPE *lloc, SEXP srcfile)
  331. {
  332. SEXP val;
  333. PROTECT(val = allocVector(INTSXP, 6));
  334. INTEGER(val)[0] = lloc->first_line;
  335. INTEGER(val)[1] = lloc->first_byte;
  336. INTEGER(val)[2] = lloc->last_line;
  337. INTEGER(val)[3] = lloc->last_byte;
  338. INTEGER(val)[4] = lloc->first_column;
  339. INTEGER(val)[5] = lloc->last_column;
  340. setAttrib(val, R_SrcfileSymbol, srcfile);
  341. setAttrib(val, R_ClassSymbol, mkString("srcref"));
  342. UNPROTECT(1);
  343. return val;
  344. }
  345. static SEXP mkString2(const char *s, size_t len)
  346. {
  347. SEXP t;
  348. cetype_t enc = CE_UTF8;
  349. PROTECT(t = allocVector(STRSXP, 1));
  350. SET_STRING_ELT(t, 0, mkCharLenCE(s, (int) len, enc));
  351. UNPROTECT(1);
  352. return t;
  353. }
  354. /* Stretchy List Structures : Lists are created and grown using a special */
  355. /* dotted pair. The CAR of the list points to the last cons-cell in the */
  356. /* list and the CDR points to the first. The list can be extracted from */
  357. /* the pair by taking its CDR, while the CAR gives fast access to the end */
  358. /* of the list. */
  359. /* Create a stretchy-list dotted pair */
  360. static SEXP NewList(void)
  361. {
  362. SEXP s = CONS(R_NilValue, R_NilValue);
  363. SETCAR(s, s);
  364. return s;
  365. }
  366. /* Add a new element at the end of a stretchy list */
  367. static SEXP GrowList(SEXP l, SEXP s)
  368. {
  369. SEXP tmp;
  370. PROTECT(s);
  371. tmp = CONS(s, R_NilValue);
  372. UNPROTECT(1);
  373. SETCDR(CAR(l), tmp);
  374. SETCAR(l, tmp);
  375. return l;
  376. }
  377. /*--------------------------------------------------------------------------*/
  378. static void PutState(ParseState *state) {
  379. state->xxlineno = parseState.xxlineno;
  380. state->xxbyteno = parseState.xxbyteno;
  381. state->xxcolno = parseState.xxcolno;
  382. state->xxDebugTokens = parseState.xxDebugTokens;
  383. state->Value = parseState.Value;
  384. state->xxinitvalue = parseState.xxinitvalue;
  385. state->xxInVerbEnv = parseState.xxInVerbEnv;
  386. state->xxVerbatimList = parseState.xxVerbatimList;
  387. state->SrcFile = parseState.SrcFile;
  388. state->prevState = parseState.prevState;
  389. }
  390. static void UseState(ParseState *state) {
  391. parseState.xxlineno = state->xxlineno;
  392. parseState.xxbyteno = state->xxbyteno;
  393. parseState.xxcolno = state->xxcolno;
  394. parseState.xxDebugTokens = state->xxDebugTokens;
  395. parseState.Value = state->Value;
  396. parseState.xxinitvalue = state->xxinitvalue;
  397. parseState.xxInVerbEnv = state->xxInVerbEnv;
  398. parseState.xxVerbatimList = state->xxVerbatimList;
  399. parseState.SrcFile = state->SrcFile;
  400. parseState.prevState = state->prevState;
  401. }
  402. static SEXP ParseLatex(ParseStatus *status, SEXP srcfile)
  403. {
  404. R_ParseContextLast = 0;
  405. R_ParseContext[0] = '\0';
  406. parseState.xxInVerbEnv = NULL;
  407. parseState.xxlineno = 1;
  408. parseState.xxcolno = 1;
  409. parseState.xxbyteno = 1;
  410. parseState.SrcFile = srcfile;
  411. npush = 0;
  412. parseState.Value = R_NilValue;
  413. if (yyparse()) *status = PARSE_ERROR;
  414. else *status = PARSE_OK;
  415. #if DEBUGVALS
  416. Rprintf("ParseRd result: %p\n", parseState.Value);
  417. #endif
  418. UNPROTECT_PTR(parseState.Value);
  419. return parseState.Value;
  420. }
  421. static const char * nextchar_parse;
  422. /* need to handle incomplete last line */
  423. static int char_getc(void)
  424. {
  425. int c;
  426. c = *nextchar_parse++;
  427. if (!c) {
  428. c = R_EOF;
  429. nextchar_parse--;
  430. }
  431. return (c);
  432. }
  433. static
  434. SEXP R_ParseLatex(SEXP text, ParseStatus *status, SEXP srcfile)
  435. {
  436. nextchar_parse = CHAR(STRING_ELT(text, 0));
  437. ptr_getc = char_getc;
  438. return ParseLatex(status, srcfile);
  439. }
  440. /*----------------------------------------------------------------------------
  441. *
  442. * The Lexical Analyzer:
  443. *
  444. * Basic lexical analysis is performed by the following
  445. * routines.
  446. *
  447. * The function yylex() scans the input, breaking it into
  448. * tokens which are then passed to the parser.
  449. *
  450. */
  451. /* Special Symbols */
  452. /* Section and R code headers */
  453. struct {
  454. char *name;
  455. int token;
  456. }
  457. static keywords[] = {
  458. /* These sections contain Latex-like text */
  459. { "\\begin", BEGIN },
  460. { "\\end", END },
  461. { "\\verb", VERB },
  462. { 0, 0 }
  463. /* All other markup macros are rejected. */
  464. };
  465. /* Record the longest # directive here */
  466. #define DIRECTIVE_LEN 7
  467. static int KeywordLookup(const char *s)
  468. {
  469. int i;
  470. for (i = 0; keywords[i].name; i++) {
  471. if (strcmp(keywords[i].name, s) == 0)
  472. return keywords[i].token;
  473. }
  474. return MACRO;
  475. }
  476. static void yyerror(const char *s)
  477. {
  478. static const char *const yytname_translations[] =
  479. {
  480. /* the left column are strings coming from bison, the right
  481. column are translations for users.
  482. The first YYENGLISH from the right column are English to be translated,
  483. the rest are to be copied literally. The #if 0 block below allows xgettext
  484. to see these.
  485. */
  486. #define YYENGLISH 3
  487. "$undefined", "input",
  488. "LATEXMACRO", "macro",
  489. "ESCAPE", "macro",
  490. 0, 0
  491. };
  492. static char const yyunexpected[] = "syntax error, unexpected ";
  493. static char const yyexpecting[] = ", expecting ";
  494. static char const yyshortunexpected[] = "unexpected %s";
  495. static char const yylongunexpected[] = "unexpected %s '%s'";
  496. char *expecting;
  497. char ParseErrorMsg[PARSE_ERROR_SIZE];
  498. SEXP filename;
  499. char ParseErrorFilename[PARSE_ERROR_SIZE];
  500. if (!strncmp(s, yyunexpected, sizeof yyunexpected -1)) {
  501. int i, translated = FALSE;
  502. /* Edit the error message */
  503. expecting = strstr(s + sizeof yyunexpected -1, yyexpecting);
  504. if (expecting) *expecting = '\0';
  505. for (i = 0; yytname_translations[i]; i += 2) {
  506. if (!strcmp(s + sizeof yyunexpected - 1, yytname_translations[i])) {
  507. if (yychar < 256)
  508. snprintf(ParseErrorMsg, PARSE_ERROR_SIZE,
  509. _(yyshortunexpected),
  510. i/2 < YYENGLISH ? _(yytname_translations[i+1])
  511. : yytname_translations[i+1]);
  512. else
  513. snprintf(ParseErrorMsg, PARSE_ERROR_SIZE,
  514. _(yylongunexpected),
  515. i/2 < YYENGLISH ? _(yytname_translations[i+1])
  516. : yytname_translations[i+1],
  517. CHAR(STRING_ELT(yylval, 0)));
  518. translated = TRUE;
  519. break;
  520. }
  521. }
  522. if (!translated) {
  523. if (yychar < 256)
  524. snprintf(ParseErrorMsg, PARSE_ERROR_SIZE,
  525. _(yyshortunexpected),
  526. s + sizeof yyunexpected - 1);
  527. else
  528. snprintf(ParseErrorMsg, PARSE_ERROR_SIZE,
  529. _(yylongunexpected),
  530. s + sizeof yyunexpected - 1, CHAR(STRING_ELT(yylval, 0)));
  531. }
  532. if (expecting) {
  533. translated = FALSE;
  534. for (i = 0; yytname_translations[i]; i += 2) {
  535. if (!strcmp(expecting + sizeof yyexpecting - 1, yytname_translations[i])) {
  536. strcat(ParseErrorMsg, _(yyexpecting));
  537. strcat(ParseErrorMsg, i/2 < YYENGLISH ? _(yytname_translations[i+1])
  538. : yytname_translations[i+1]);
  539. translated = TRUE;
  540. break;
  541. }
  542. }
  543. if (!translated) {
  544. strcat(ParseErrorMsg, _(yyexpecting));
  545. strcat(ParseErrorMsg, expecting + sizeof yyexpecting - 1);
  546. }
  547. }
  548. } else if (!strncmp(s, yyunknown, sizeof yyunknown-1)) {
  549. snprintf(ParseErrorMsg, PARSE_ERROR_SIZE,
  550. "%s '%s'", s, CHAR(STRING_ELT(yylval, 0)));
  551. } else {
  552. snprintf(ParseErrorMsg, PARSE_ERROR_SIZE,"%s", s);
  553. }
  554. filename = findVar(install("filename"), parseState.SrcFile);
  555. if (isString(filename) && length(filename))
  556. strncpy(ParseErrorFilename, CHAR(STRING_ELT(filename, 0)), PARSE_ERROR_SIZE - 1);
  557. else
  558. ParseErrorFilename[0] = '\0';
  559. if (yylloc.first_line != yylloc.last_line)
  560. warning("%s:%d-%d: %s",
  561. ParseErrorFilename, yylloc.first_line, yylloc.last_line, ParseErrorMsg);
  562. else
  563. warning("%s:%d: %s",
  564. ParseErrorFilename, yylloc.first_line, ParseErrorMsg);
  565. }
  566. #define TEXT_PUSH(c) do { \
  567. size_t nc = bp - stext; \
  568. if (nc >= nstext - 1) { \
  569. char *old = stext; \
  570. nstext *= 2; \
  571. stext = malloc(nstext); \
  572. if(!stext) error(_("unable to allocate buffer for long string at line %d"), parseState.xxlineno);\
  573. memmove(stext, old, nc); \
  574. if(old != st0) free(old); \
  575. bp = stext+nc; } \
  576. *bp++ = ((char)c); \
  577. } while(0)
  578. static void setfirstloc(void)
  579. {
  580. yylloc.first_line = parseState.xxlineno;
  581. yylloc.first_column = parseState.xxcolno;
  582. yylloc.first_byte = parseState.xxbyteno;
  583. }
  584. static void setlastloc(void)
  585. {
  586. yylloc.last_line = prevlines[prevpos];
  587. yylloc.last_column = prevcols[prevpos];
  588. yylloc.last_byte = prevbytes[prevpos];
  589. }
  590. /* Split the input stream into tokens. */
  591. /* This is the lowest of the parsing levels. */
  592. static int token(void)
  593. {
  594. int c;
  595. if (parseState.xxinitvalue) {
  596. yylloc.first_line = 0;
  597. yylloc.first_column = 0;
  598. yylloc.first_byte = 0;
  599. yylloc.last_line = 0;
  600. yylloc.last_column = 0;
  601. yylloc.last_byte = 0;
  602. PROTECT(yylval = mkString(""));
  603. c = parseState.xxinitvalue;
  604. parseState.xxinitvalue = 0;
  605. return(c);
  606. }
  607. setfirstloc();
  608. if (parseState.xxInVerbEnv)
  609. return mkVerbEnv();
  610. c = xxgetc();
  611. switch (c) {
  612. case '%': return mkComment(c);
  613. case '\\':return mkMarkup(c);
  614. case R_EOF:return END_OF_INPUT;
  615. case LBRACE:return c;
  616. case RBRACE:return c;
  617. case '$': return c;
  618. }
  619. return mkText(c);
  620. }
  621. #define INITBUFSIZE 128
  622. static int mkText(int c)
  623. {
  624. char st0[INITBUFSIZE];
  625. unsigned int nstext = INITBUFSIZE;
  626. char *stext = st0, *bp = st0;
  627. while(1) {
  628. switch (c) {
  629. case '\\':
  630. case '%':
  631. case LBRACE:
  632. case RBRACE:
  633. case '$':
  634. case R_EOF:
  635. goto stop;
  636. }
  637. TEXT_PUSH(c);
  638. c = xxgetc();
  639. };
  640. stop:
  641. xxungetc(c);
  642. PROTECT(yylval = mkString2(stext, bp - stext));
  643. if(stext != st0) free(stext);
  644. return TEXT;
  645. }
  646. static int mkComment(int c)
  647. {
  648. char st0[INITBUFSIZE];
  649. unsigned int nstext = INITBUFSIZE;
  650. char *stext = st0, *bp = st0;
  651. do TEXT_PUSH(c);
  652. while ((c = xxgetc()) != '\n' && c != R_EOF);
  653. if (c == R_EOF) xxungetc(c);
  654. else TEXT_PUSH(c);
  655. PROTECT(yylval = mkString2(stext, bp - stext));
  656. if(stext != st0) free(stext);
  657. return COMMENT;
  658. }
  659. static int mkMarkup(int c)
  660. {
  661. char st0[INITBUFSIZE];
  662. unsigned int nstext = INITBUFSIZE;
  663. char *stext = st0, *bp = st0;
  664. int retval = 0;
  665. TEXT_PUSH(c);
  666. while (isalpha((c = xxgetc()))) TEXT_PUSH(c);
  667. /* One non-alpha allowed */
  668. if (bp - stext == 1) {
  669. TEXT_PUSH(c);
  670. TEXT_PUSH('\0');
  671. retval = MACRO;
  672. } else {
  673. TEXT_PUSH('\0');
  674. retval = KeywordLookup(stext);
  675. if (retval == VERB)
  676. retval = mkVerb(c); /* This makes the yylval */
  677. else if (c != ' ') /* Eat a space, but keep other terminators */
  678. xxungetc(c);
  679. }
  680. if (retval != VERB) {
  681. PROTECT(yylval = mkString(stext));
  682. }
  683. if(stext != st0) free(stext);
  684. return retval;
  685. }
  686. static int mkVerb(int c)
  687. {
  688. char st0[INITBUFSIZE];
  689. unsigned int nstext = INITBUFSIZE;
  690. char *stext = st0, *bp = st0;
  691. int delim = c;
  692. TEXT_PUSH('\\'); TEXT_PUSH('v'); TEXT_PUSH('e'); TEXT_PUSH('r'); TEXT_PUSH('b');
  693. TEXT_PUSH(c);
  694. while ((c = xxgetc()) != delim) TEXT_PUSH(c);
  695. TEXT_PUSH(c);
  696. PROTECT(yylval = mkString2(stext, bp - stext));
  697. if(stext != st0) free(stext);
  698. return VERB;
  699. }
  700. static int mkVerbEnv()
  701. {
  702. char st0[INITBUFSIZE];
  703. unsigned int nstext = INITBUFSIZE;
  704. char *stext = st0, *bp = st0;
  705. int matched = 0, i;
  706. int c;
  707. while ((c = xxgetc()) != R_EOF && CHAR(STRING_ELT(parseState.xxInVerbEnv, 0))[matched]) {
  708. TEXT_PUSH(c);
  709. if (c == CHAR(STRING_ELT(parseState.xxInVerbEnv, 0))[matched])
  710. matched++;
  711. else
  712. matched = 0;
  713. }
  714. if ( !CHAR(STRING_ELT(parseState.xxInVerbEnv, 0))[matched] ) {
  715. for (i = matched-1; i >= 0; i--)
  716. xxungetc(*(--bp));
  717. UNPROTECT_PTR(parseState.xxInVerbEnv);
  718. parseState.xxInVerbEnv = NULL;
  719. }
  720. PROTECT(yylval = mkString2(stext, bp - stext));
  721. if (stext != st0) free(stext);
  722. return VERB;
  723. }
  724. static int yylex(void)
  725. {
  726. int tok = token();
  727. if (parseState.xxDebugTokens) {
  728. Rprintf("%d:%d: %s", yylloc.first_line, yylloc.first_column, yytname[YYTRANSLATE(tok)]);
  729. if (tok > 255 && tok != END_OF_INPUT)
  730. Rprintf(": %s", CHAR(STRING_ELT(yylval, 0)));
  731. Rprintf("\n");
  732. }
  733. setlastloc();
  734. return tok;
  735. }
  736. static void PushState() {
  737. if (busy) {
  738. ParseState *prev = malloc(sizeof(ParseState));
  739. PutState(prev);
  740. parseState.prevState = prev;
  741. } else
  742. parseState.prevState = NULL;
  743. busy = TRUE;
  744. }
  745. static void PopState() {
  746. if (parseState.prevState) {
  747. ParseState *prev = parseState.prevState;
  748. UseState(prev);
  749. free(prev);
  750. } else
  751. busy = FALSE;
  752. }
  753. /* "do_parseLatex"
  754. .External2(CC_parseLatex, file, srcfile, verbose, basename, warningCalls)
  755. If there is text then that is read and the other arguments are ignored.
  756. */
  757. SEXP C_parseLatex(SEXP call, SEXP op, SEXP args, SEXP env)
  758. {
  759. args = CDR(args);
  760. SEXP s = R_NilValue, source, text;
  761. ParseStatus status;
  762. #if DEBUGMODE
  763. yydebug = 1;
  764. #endif
  765. R_ParseError = 0;
  766. R_ParseErrorMsg[0] = '\0';
  767. PushState();
  768. text = CAR(args); args = CDR(args);
  769. source = CAR(args); args = CDR(args);
  770. if(!isLogical(CAR(args)) || LENGTH(CAR(args)) != 1)
  771. error(_("invalid '%s' value"), "verbose");
  772. parseState.xxDebugTokens = asInteger(CAR(args)); args = CDR(args);
  773. parseState.xxVerbatimList = CAR(args); args = CDR(args);
  774. s = R_ParseLatex(text, &status, source);
  775. PopState();
  776. if (status != PARSE_OK) parseError(call, R_ParseError);
  777. return s;
  778. }