LexCaml.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // Scintilla source code edit control
  2. /** @file LexCaml.cxx
  3. ** Lexer for Objective Caml.
  4. **/
  5. // Copyright 2005-2009 by Robert Roessler <robertr@rftp.com>
  6. // The License.txt file describes the conditions under which this software may be distributed.
  7. /* Release History
  8. 20050204 Initial release.
  9. 20050205 Quick compiler standards/"cleanliness" adjustment.
  10. 20050206 Added cast for IsLeadByte().
  11. 20050209 Changes to "external" build support.
  12. 20050306 Fix for 1st-char-in-doc "corner" case.
  13. 20050502 Fix for [harmless] one-past-the-end coloring.
  14. 20050515 Refined numeric token recognition logic.
  15. 20051125 Added 2nd "optional" keywords class.
  16. 20051129 Support "magic" (read-only) comments for RCaml.
  17. 20051204 Swtich to using StyleContext infrastructure.
  18. 20090629 Add full Standard ML '97 support.
  19. */
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <stdio.h>
  23. #include <stdarg.h>
  24. #include <assert.h>
  25. #include <ctype.h>
  26. #include "ILexer.h"
  27. #include "Scintilla.h"
  28. #include "SciLexer.h"
  29. #include "PropSetSimple.h"
  30. #include "WordList.h"
  31. #include "LexAccessor.h"
  32. #include "Accessor.h"
  33. #include "StyleContext.h"
  34. #include "CharacterSet.h"
  35. #include "LexerModule.h"
  36. // Since the Microsoft __iscsym[f] funcs are not ANSI...
  37. inline int iscaml(int c) {return isalnum(c) || c == '_';}
  38. inline int iscamlf(int c) {return isalpha(c) || c == '_';}
  39. static const int baseT[24] = {
  40. 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A - L */
  41. 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0,16 /* M - X */
  42. };
  43. #ifdef SCI_NAMESPACE
  44. using namespace Scintilla;
  45. #endif
  46. #ifdef BUILD_AS_EXTERNAL_LEXER
  47. /*
  48. (actually seems to work!)
  49. */
  50. #include <string>
  51. #include "WindowAccessor.h"
  52. #include "ExternalLexer.h"
  53. #undef EXT_LEXER_DECL
  54. #define EXT_LEXER_DECL __declspec( dllexport ) __stdcall
  55. #if PLAT_WIN
  56. #include <windows.h>
  57. #endif
  58. static void ColouriseCamlDoc(
  59. Sci_PositionU startPos, Sci_Position length,
  60. int initStyle,
  61. WordList *keywordlists[],
  62. Accessor &styler);
  63. static void FoldCamlDoc(
  64. Sci_PositionU startPos, Sci_Position length,
  65. int initStyle,
  66. WordList *keywordlists[],
  67. Accessor &styler);
  68. static void InternalLexOrFold(int lexOrFold, Sci_PositionU startPos, Sci_Position length,
  69. int initStyle, char *words[], WindowID window, char *props);
  70. static const char* LexerName = "caml";
  71. #ifdef TRACE
  72. void Platform::DebugPrintf(const char *format, ...) {
  73. char buffer[2000];
  74. va_list pArguments;
  75. va_start(pArguments, format);
  76. vsprintf(buffer,format,pArguments);
  77. va_end(pArguments);
  78. Platform::DebugDisplay(buffer);
  79. }
  80. #else
  81. void Platform::DebugPrintf(const char *, ...) {
  82. }
  83. #endif
  84. bool Platform::IsDBCSLeadByte(int codePage, char ch) {
  85. return ::IsDBCSLeadByteEx(codePage, ch) != 0;
  86. }
  87. long Platform::SendScintilla(WindowID w, unsigned int msg, unsigned long wParam, long lParam) {
  88. return ::SendMessage(reinterpret_cast<HWND>(w), msg, wParam, lParam);
  89. }
  90. long Platform::SendScintillaPointer(WindowID w, unsigned int msg, unsigned long wParam, void *lParam) {
  91. return ::SendMessage(reinterpret_cast<HWND>(w), msg, wParam,
  92. reinterpret_cast<LPARAM>(lParam));
  93. }
  94. void EXT_LEXER_DECL Fold(unsigned int lexer, Sci_PositionU startPos, Sci_Position length,
  95. int initStyle, char *words[], WindowID window, char *props)
  96. {
  97. // below useless evaluation(s) to supress "not used" warnings
  98. lexer;
  99. // build expected data structures and do the Fold
  100. InternalLexOrFold(1, startPos, length, initStyle, words, window, props);
  101. }
  102. int EXT_LEXER_DECL GetLexerCount()
  103. {
  104. return 1; // just us [Objective] Caml lexers here!
  105. }
  106. void EXT_LEXER_DECL GetLexerName(unsigned int Index, char *name, int buflength)
  107. {
  108. // below useless evaluation(s) to supress "not used" warnings
  109. Index;
  110. // return as much of our lexer name as will fit (what's up with Index?)
  111. if (buflength > 0) {
  112. buflength--;
  113. int n = strlen(LexerName);
  114. if (n > buflength)
  115. n = buflength;
  116. memcpy(name, LexerName, n), name[n] = '\0';
  117. }
  118. }
  119. void EXT_LEXER_DECL Lex(unsigned int lexer, Sci_PositionU startPos, Sci_Position length,
  120. int initStyle, char *words[], WindowID window, char *props)
  121. {
  122. // below useless evaluation(s) to supress "not used" warnings
  123. lexer;
  124. // build expected data structures and do the Lex
  125. InternalLexOrFold(0, startPos, length, initStyle, words, window, props);
  126. }
  127. static void InternalLexOrFold(int foldOrLex, Sci_PositionU startPos, Sci_Position length,
  128. int initStyle, char *words[], WindowID window, char *props)
  129. {
  130. // create and initialize a WindowAccessor (including contained PropSet)
  131. PropSetSimple ps;
  132. ps.SetMultiple(props);
  133. WindowAccessor wa(window, ps);
  134. // create and initialize WordList(s)
  135. int nWL = 0;
  136. for (; words[nWL]; nWL++) ; // count # of WordList PTRs needed
  137. WordList** wl = new WordList* [nWL + 1];// alloc WordList PTRs
  138. int i = 0;
  139. for (; i < nWL; i++) {
  140. wl[i] = new WordList(); // (works or THROWS bad_alloc EXCEPTION)
  141. wl[i]->Set(words[i]);
  142. }
  143. wl[i] = 0;
  144. // call our "internal" folder/lexer (... then do Flush!)
  145. if (foldOrLex)
  146. FoldCamlDoc(startPos, length, initStyle, wl, wa);
  147. else
  148. ColouriseCamlDoc(startPos, length, initStyle, wl, wa);
  149. wa.Flush();
  150. // clean up before leaving
  151. for (i = nWL - 1; i >= 0; i--)
  152. delete wl[i];
  153. delete [] wl;
  154. }
  155. static
  156. #endif /* BUILD_AS_EXTERNAL_LEXER */
  157. void ColouriseCamlDoc(
  158. Sci_PositionU startPos, Sci_Position length,
  159. int initStyle,
  160. WordList *keywordlists[],
  161. Accessor &styler)
  162. {
  163. // initialize styler
  164. StyleContext sc(startPos, length, initStyle, styler);
  165. Sci_PositionU chToken = 0;
  166. int chBase = 0, chLit = 0;
  167. WordList& keywords = *keywordlists[0];
  168. WordList& keywords2 = *keywordlists[1];
  169. WordList& keywords3 = *keywordlists[2];
  170. const bool isSML = keywords.InList("andalso");
  171. const int useMagic = styler.GetPropertyInt("lexer.caml.magic", 0);
  172. // set up [initial] state info (terminating states that shouldn't "bleed")
  173. const int state_ = sc.state & 0x0f;
  174. if (state_ <= SCE_CAML_CHAR
  175. || (isSML && state_ == SCE_CAML_STRING))
  176. sc.state = SCE_CAML_DEFAULT;
  177. int nesting = (state_ >= SCE_CAML_COMMENT)? (state_ - SCE_CAML_COMMENT): 0;
  178. // foreach char in range...
  179. while (sc.More()) {
  180. // set up [per-char] state info
  181. int state2 = -1; // (ASSUME no state change)
  182. Sci_Position chColor = sc.currentPos - 1;// (ASSUME standard coloring range)
  183. bool advance = true; // (ASSUME scanner "eats" 1 char)
  184. // step state machine
  185. switch (sc.state & 0x0f) {
  186. case SCE_CAML_DEFAULT:
  187. chToken = sc.currentPos; // save [possible] token start (JIC)
  188. // it's wide open; what do we have?
  189. if (iscamlf(sc.ch))
  190. state2 = SCE_CAML_IDENTIFIER;
  191. else if (!isSML && sc.Match('`') && iscamlf(sc.chNext))
  192. state2 = SCE_CAML_TAGNAME;
  193. else if (!isSML && sc.Match('#') && isdigit(sc.chNext))
  194. state2 = SCE_CAML_LINENUM;
  195. else if (isdigit(sc.ch)) {
  196. // it's a number, assume base 10
  197. state2 = SCE_CAML_NUMBER, chBase = 10;
  198. if (sc.Match('0')) {
  199. // there MAY be a base specified...
  200. const char* baseC = "bBoOxX";
  201. if (isSML) {
  202. if (sc.chNext == 'w')
  203. sc.Forward(); // (consume SML "word" indicator)
  204. baseC = "x";
  205. }
  206. // ... change to specified base AS REQUIRED
  207. if (strchr(baseC, sc.chNext))
  208. chBase = baseT[tolower(sc.chNext) - 'a'], sc.Forward();
  209. }
  210. } else if (!isSML && sc.Match('\'')) // (Caml char literal?)
  211. state2 = SCE_CAML_CHAR, chLit = 0;
  212. else if (isSML && sc.Match('#', '"')) // (SML char literal?)
  213. state2 = SCE_CAML_CHAR, sc.Forward();
  214. else if (sc.Match('"'))
  215. state2 = SCE_CAML_STRING;
  216. else if (sc.Match('(', '*'))
  217. state2 = SCE_CAML_COMMENT, sc.Forward(), sc.ch = ' '; // (*)...
  218. else if (strchr("!?~" /* Caml "prefix-symbol" */
  219. "=<>@^|&+-*/$%" /* Caml "infix-symbol" */
  220. "()[]{};,:.#", sc.ch) // Caml "bracket" or ;,:.#
  221. // SML "extra" ident chars
  222. || (isSML && (sc.Match('\\') || sc.Match('`'))))
  223. state2 = SCE_CAML_OPERATOR;
  224. break;
  225. case SCE_CAML_IDENTIFIER:
  226. // [try to] interpret as [additional] identifier char
  227. if (!(iscaml(sc.ch) || sc.Match('\''))) {
  228. const Sci_Position n = sc.currentPos - chToken;
  229. if (n < 24) {
  230. // length is believable as keyword, [re-]construct token
  231. char t[24];
  232. for (Sci_Position i = -n; i < 0; i++)
  233. t[n + i] = static_cast<char>(sc.GetRelative(i));
  234. t[n] = '\0';
  235. // special-case "_" token as KEYWORD
  236. if ((n == 1 && sc.chPrev == '_') || keywords.InList(t))
  237. sc.ChangeState(SCE_CAML_KEYWORD);
  238. else if (keywords2.InList(t))
  239. sc.ChangeState(SCE_CAML_KEYWORD2);
  240. else if (keywords3.InList(t))
  241. sc.ChangeState(SCE_CAML_KEYWORD3);
  242. }
  243. state2 = SCE_CAML_DEFAULT, advance = false;
  244. }
  245. break;
  246. case SCE_CAML_TAGNAME:
  247. // [try to] interpret as [additional] tagname char
  248. if (!(iscaml(sc.ch) || sc.Match('\'')))
  249. state2 = SCE_CAML_DEFAULT, advance = false;
  250. break;
  251. /*case SCE_CAML_KEYWORD:
  252. case SCE_CAML_KEYWORD2:
  253. case SCE_CAML_KEYWORD3:
  254. // [try to] interpret as [additional] keyword char
  255. if (!iscaml(ch))
  256. state2 = SCE_CAML_DEFAULT, advance = false;
  257. break;*/
  258. case SCE_CAML_LINENUM:
  259. // [try to] interpret as [additional] linenum directive char
  260. if (!isdigit(sc.ch))
  261. state2 = SCE_CAML_DEFAULT, advance = false;
  262. break;
  263. case SCE_CAML_OPERATOR: {
  264. // [try to] interpret as [additional] operator char
  265. const char* o = 0;
  266. if (iscaml(sc.ch) || isspace(sc.ch) // ident or whitespace
  267. || (o = strchr(")]};,\'\"#", sc.ch),o) // "termination" chars
  268. || (!isSML && sc.Match('`')) // Caml extra term char
  269. || (!strchr("!$%&*+-./:<=>?@^|~", sc.ch)// "operator" chars
  270. // SML extra ident chars
  271. && !(isSML && (sc.Match('\\') || sc.Match('`'))))) {
  272. // check for INCLUSIVE termination
  273. if (o && strchr(")]};,", sc.ch)) {
  274. if ((sc.Match(')') && sc.chPrev == '(')
  275. || (sc.Match(']') && sc.chPrev == '['))
  276. // special-case "()" and "[]" tokens as KEYWORDS
  277. sc.ChangeState(SCE_CAML_KEYWORD);
  278. chColor++;
  279. } else
  280. advance = false;
  281. state2 = SCE_CAML_DEFAULT;
  282. }
  283. break;
  284. }
  285. case SCE_CAML_NUMBER:
  286. // [try to] interpret as [additional] numeric literal char
  287. if ((!isSML && sc.Match('_')) || IsADigit(sc.ch, chBase))
  288. break;
  289. // how about an integer suffix?
  290. if (!isSML && (sc.Match('l') || sc.Match('L') || sc.Match('n'))
  291. && (sc.chPrev == '_' || IsADigit(sc.chPrev, chBase)))
  292. break;
  293. // or a floating-point literal?
  294. if (chBase == 10) {
  295. // with a decimal point?
  296. if (sc.Match('.')
  297. && ((!isSML && sc.chPrev == '_')
  298. || IsADigit(sc.chPrev, chBase)))
  299. break;
  300. // with an exponent? (I)
  301. if ((sc.Match('e') || sc.Match('E'))
  302. && ((!isSML && (sc.chPrev == '.' || sc.chPrev == '_'))
  303. || IsADigit(sc.chPrev, chBase)))
  304. break;
  305. // with an exponent? (II)
  306. if (((!isSML && (sc.Match('+') || sc.Match('-')))
  307. || (isSML && sc.Match('~')))
  308. && (sc.chPrev == 'e' || sc.chPrev == 'E'))
  309. break;
  310. }
  311. // it looks like we have run out of number
  312. state2 = SCE_CAML_DEFAULT, advance = false;
  313. break;
  314. case SCE_CAML_CHAR:
  315. if (!isSML) {
  316. // [try to] interpret as [additional] char literal char
  317. if (sc.Match('\\')) {
  318. chLit = 1; // (definitely IS a char literal)
  319. if (sc.chPrev == '\\')
  320. sc.ch = ' '; // (...\\')
  321. // should we be terminating - one way or another?
  322. } else if ((sc.Match('\'') && sc.chPrev != '\\')
  323. || sc.atLineEnd) {
  324. state2 = SCE_CAML_DEFAULT;
  325. if (sc.Match('\''))
  326. chColor++;
  327. else
  328. sc.ChangeState(SCE_CAML_IDENTIFIER);
  329. // ... maybe a char literal, maybe not
  330. } else if (chLit < 1 && sc.currentPos - chToken >= 2)
  331. sc.ChangeState(SCE_CAML_IDENTIFIER), advance = false;
  332. break;
  333. }/* else
  334. // fall through for SML char literal (handle like string) */
  335. case SCE_CAML_STRING:
  336. // [try to] interpret as [additional] [SML char/] string literal char
  337. if (isSML && sc.Match('\\') && sc.chPrev != '\\' && isspace(sc.chNext))
  338. state2 = SCE_CAML_WHITE;
  339. else if (sc.Match('\\') && sc.chPrev == '\\')
  340. sc.ch = ' '; // (...\\")
  341. // should we be terminating - one way or another?
  342. else if ((sc.Match('"') && sc.chPrev != '\\')
  343. || (isSML && sc.atLineEnd)) {
  344. state2 = SCE_CAML_DEFAULT;
  345. if (sc.Match('"'))
  346. chColor++;
  347. }
  348. break;
  349. case SCE_CAML_WHITE:
  350. // [try to] interpret as [additional] SML embedded whitespace char
  351. if (sc.Match('\\')) {
  352. // style this puppy NOW...
  353. state2 = SCE_CAML_STRING, sc.ch = ' ' /* (...\") */, chColor++,
  354. styler.ColourTo(chColor, SCE_CAML_WHITE), styler.Flush();
  355. // ... then backtrack to determine original SML literal type
  356. Sci_Position p = chColor - 2;
  357. for (; p >= 0 && styler.StyleAt(p) == SCE_CAML_WHITE; p--) ;
  358. if (p >= 0)
  359. state2 = static_cast<int>(styler.StyleAt(p));
  360. // take care of state change NOW
  361. sc.ChangeState(state2), state2 = -1;
  362. }
  363. break;
  364. case SCE_CAML_COMMENT:
  365. case SCE_CAML_COMMENT1:
  366. case SCE_CAML_COMMENT2:
  367. case SCE_CAML_COMMENT3:
  368. // we're IN a comment - does this start a NESTED comment?
  369. if (sc.Match('(', '*'))
  370. state2 = sc.state + 1, chToken = sc.currentPos,
  371. sc.Forward(), sc.ch = ' ' /* (*)... */, nesting++;
  372. // [try to] interpret as [additional] comment char
  373. else if (sc.Match(')') && sc.chPrev == '*') {
  374. if (nesting)
  375. state2 = (sc.state & 0x0f) - 1, chToken = 0, nesting--;
  376. else
  377. state2 = SCE_CAML_DEFAULT;
  378. chColor++;
  379. // enable "magic" (read-only) comment AS REQUIRED
  380. } else if (useMagic && sc.currentPos - chToken == 4
  381. && sc.Match('c') && sc.chPrev == 'r' && sc.GetRelative(-2) == '@')
  382. sc.state |= 0x10; // (switch to read-only comment style)
  383. break;
  384. }
  385. // handle state change and char coloring AS REQUIRED
  386. if (state2 >= 0)
  387. styler.ColourTo(chColor, sc.state), sc.ChangeState(state2);
  388. // move to next char UNLESS re-scanning current char
  389. if (advance)
  390. sc.Forward();
  391. }
  392. // do any required terminal char coloring (JIC)
  393. sc.Complete();
  394. }
  395. #ifdef BUILD_AS_EXTERNAL_LEXER
  396. static
  397. #endif /* BUILD_AS_EXTERNAL_LEXER */
  398. void FoldCamlDoc(
  399. Sci_PositionU, Sci_Position,
  400. int,
  401. WordList *[],
  402. Accessor &)
  403. {
  404. }
  405. static const char * const camlWordListDesc[] = {
  406. "Keywords", // primary Objective Caml keywords
  407. "Keywords2", // "optional" keywords (typically from Pervasives)
  408. "Keywords3", // "optional" keywords (typically typenames)
  409. 0
  410. };
  411. #ifndef BUILD_AS_EXTERNAL_LEXER
  412. LexerModule lmCaml(SCLEX_CAML, ColouriseCamlDoc, "caml", FoldCamlDoc, camlWordListDesc);
  413. #endif /* BUILD_AS_EXTERNAL_LEXER */