tree-sitter-language-mode-spec.js 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621
  1. /* eslint-disable no-template-curly-in-string */
  2. const fs = require('fs');
  3. const path = require('path');
  4. const dedent = require('dedent');
  5. const TextBuffer = require('text-buffer');
  6. const { Point } = TextBuffer;
  7. const TextEditor = require('../src/text-editor');
  8. const TreeSitterGrammar = require('../src/tree-sitter-grammar');
  9. const TreeSitterLanguageMode = require('../src/tree-sitter-language-mode');
  10. const Random = require('random-seed');
  11. const { getRandomBufferRange, buildRandomLines } = require('./helpers/random');
  12. const cGrammarPath = require.resolve('language-c/grammars/tree-sitter-c.cson');
  13. const pythonGrammarPath = require.resolve(
  14. 'language-python/grammars/tree-sitter-python.cson'
  15. );
  16. const jsGrammarPath = require.resolve(
  17. 'language-javascript/grammars/tree-sitter-javascript.cson'
  18. );
  19. const jsdocGrammarPath = require.resolve(
  20. 'language-javascript/grammars/tree-sitter-jsdoc.cson'
  21. );
  22. const htmlGrammarPath = require.resolve(
  23. 'language-html/grammars/tree-sitter-html.cson'
  24. );
  25. const ejsGrammarPath = require.resolve(
  26. 'language-html/grammars/tree-sitter-ejs.cson'
  27. );
  28. const rubyGrammarPath = require.resolve(
  29. 'language-ruby/grammars/tree-sitter-ruby.cson'
  30. );
  31. const rustGrammarPath = require.resolve(
  32. 'language-rust-bundled/grammars/tree-sitter-rust.cson'
  33. );
  34. describe('TreeSitterLanguageMode', () => {
  35. let editor, buffer;
  36. beforeEach(async () => {
  37. editor = await atom.workspace.open('');
  38. buffer = editor.getBuffer();
  39. editor.displayLayer.reset({ foldCharacter: '…' });
  40. atom.config.set('core.useTreeSitterParsers', true);
  41. atom.config.set('core.useExperimentalModernTreeSitter', false);
  42. });
  43. describe('highlighting', () => {
  44. it('applies the most specific scope mapping to each node in the syntax tree', async () => {
  45. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  46. parser: 'tree-sitter-javascript',
  47. scopes: {
  48. program: 'source',
  49. 'call_expression > identifier': 'function',
  50. property_identifier: 'property',
  51. 'call_expression > member_expression > property_identifier': 'method'
  52. }
  53. });
  54. buffer.setText('aa.bbb = cc(d.eee());');
  55. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  56. buffer.setLanguageMode(languageMode);
  57. expectTokensToEqual(editor, [
  58. [
  59. { text: 'aa.', scopes: ['source'] },
  60. { text: 'bbb', scopes: ['source', 'property'] },
  61. { text: ' = ', scopes: ['source'] },
  62. { text: 'cc', scopes: ['source', 'function'] },
  63. { text: '(d.', scopes: ['source'] },
  64. { text: 'eee', scopes: ['source', 'method'] },
  65. { text: '());', scopes: ['source'] }
  66. ]
  67. ]);
  68. });
  69. it('provides the grammar with the text of leaf nodes only', async () => {
  70. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  71. parser: 'tree-sitter-javascript',
  72. scopes: {
  73. program: 'source',
  74. 'call_expression > identifier': 'function',
  75. property_identifier: 'property',
  76. 'call_expression > member_expression > property_identifier': 'method'
  77. }
  78. });
  79. const original = grammar.idForScope.bind(grammar);
  80. let tokens = [];
  81. grammar.idForScope = function(scope, text) {
  82. if (text && tokens[tokens.length - 1] !== text) {
  83. tokens.push(text);
  84. }
  85. return original(scope, text);
  86. };
  87. buffer.setText('aa.bbb = cc(d.eee());');
  88. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  89. buffer.setLanguageMode(languageMode);
  90. expectTokensToEqual(editor, [
  91. [
  92. { text: 'aa.', scopes: ['source'] },
  93. { text: 'bbb', scopes: ['source', 'property'] },
  94. { text: ' = ', scopes: ['source'] },
  95. { text: 'cc', scopes: ['source', 'function'] },
  96. { text: '(d.', scopes: ['source'] },
  97. { text: 'eee', scopes: ['source', 'method'] },
  98. { text: '());', scopes: ['source'] }
  99. ]
  100. ]);
  101. expect(tokens).toEqual([
  102. 'aa',
  103. '.',
  104. 'bbb',
  105. '=',
  106. 'cc',
  107. '(',
  108. 'd',
  109. '.',
  110. 'eee',
  111. '(',
  112. ')',
  113. ';'
  114. ]);
  115. });
  116. it('can start or end multiple scopes at the same position', async () => {
  117. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  118. parser: 'tree-sitter-javascript',
  119. scopes: {
  120. program: 'source',
  121. call_expression: 'call',
  122. member_expression: 'member',
  123. identifier: 'variable',
  124. '"("': 'open-paren',
  125. '")"': 'close-paren'
  126. }
  127. });
  128. buffer.setText('a = bb.ccc();');
  129. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  130. buffer.setLanguageMode(languageMode);
  131. expectTokensToEqual(editor, [
  132. [
  133. { text: 'a', scopes: ['source', 'variable'] },
  134. { text: ' = ', scopes: ['source'] },
  135. { text: 'bb', scopes: ['source', 'call', 'member', 'variable'] },
  136. { text: '.ccc', scopes: ['source', 'call', 'member'] },
  137. { text: '(', scopes: ['source', 'call', 'open-paren'] },
  138. { text: ')', scopes: ['source', 'call', 'close-paren'] },
  139. { text: ';', scopes: ['source'] }
  140. ]
  141. ]);
  142. });
  143. it('can resume highlighting on a line that starts with whitespace', async () => {
  144. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  145. parser: 'tree-sitter-javascript',
  146. scopes: {
  147. 'call_expression > member_expression > property_identifier':
  148. 'function',
  149. property_identifier: 'member',
  150. identifier: 'variable'
  151. }
  152. });
  153. buffer.setText('a\n .b();');
  154. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  155. buffer.setLanguageMode(languageMode);
  156. expectTokensToEqual(editor, [
  157. [{ text: 'a', scopes: ['variable'] }],
  158. [
  159. { text: ' ', scopes: ['leading-whitespace'] },
  160. { text: '.', scopes: [] },
  161. { text: 'b', scopes: ['function'] },
  162. { text: '();', scopes: [] }
  163. ]
  164. ]);
  165. });
  166. it('correctly skips over tokens with zero size', async () => {
  167. const grammar = new TreeSitterGrammar(atom.grammars, cGrammarPath, {
  168. parser: 'tree-sitter-c',
  169. scopes: {
  170. primitive_type: 'type',
  171. identifier: 'variable'
  172. }
  173. });
  174. buffer.setText('int main() {\n int a\n int b;\n}');
  175. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  176. buffer.setLanguageMode(languageMode);
  177. expect(
  178. languageMode.tree.rootNode
  179. .descendantForPosition(Point(1, 2), Point(1, 6))
  180. .toString()
  181. ).toBe(
  182. '(declaration type: (primitive_type)' +
  183. ' declarator: (identifier) (MISSING ";"))'
  184. );
  185. expectTokensToEqual(editor, [
  186. [
  187. { text: 'int', scopes: ['type'] },
  188. { text: ' ', scopes: [] },
  189. { text: 'main', scopes: ['variable'] },
  190. { text: '() {', scopes: [] }
  191. ],
  192. [
  193. { text: ' ', scopes: ['leading-whitespace'] },
  194. { text: 'int', scopes: ['type'] },
  195. { text: ' ', scopes: [] },
  196. { text: 'a', scopes: ['variable'] }
  197. ],
  198. [
  199. { text: ' ', scopes: ['leading-whitespace'] },
  200. { text: 'int', scopes: ['type'] },
  201. { text: ' ', scopes: [] },
  202. { text: 'b', scopes: ['variable'] },
  203. { text: ';', scopes: [] }
  204. ],
  205. [{ text: '}', scopes: [] }]
  206. ]);
  207. });
  208. it("updates lines' highlighting when they are affected by distant changes", async () => {
  209. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  210. parser: 'tree-sitter-javascript',
  211. scopes: {
  212. 'call_expression > identifier': 'function',
  213. property_identifier: 'member'
  214. }
  215. });
  216. buffer.setText('a(\nb,\nc\n');
  217. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  218. buffer.setLanguageMode(languageMode);
  219. // missing closing paren
  220. expectTokensToEqual(editor, [
  221. [{ text: 'a(', scopes: [] }],
  222. [{ text: 'b,', scopes: [] }],
  223. [{ text: 'c', scopes: [] }],
  224. []
  225. ]);
  226. buffer.append(')');
  227. expectTokensToEqual(editor, [
  228. [{ text: 'a', scopes: ['function'] }, { text: '(', scopes: [] }],
  229. [{ text: 'b,', scopes: [] }],
  230. [{ text: 'c', scopes: [] }],
  231. [{ text: ')', scopes: [] }]
  232. ]);
  233. });
  234. it('allows comma-separated selectors as scope mapping keys', async () => {
  235. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  236. parser: 'tree-sitter-javascript',
  237. scopes: {
  238. 'identifier, call_expression > identifier': [
  239. { match: '^[A-Z]', scopes: 'constructor' }
  240. ],
  241. 'call_expression > identifier': 'function'
  242. }
  243. });
  244. buffer.setText(`a(B(new C))`);
  245. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  246. buffer.setLanguageMode(languageMode);
  247. expectTokensToEqual(editor, [
  248. [
  249. { text: 'a', scopes: ['function'] },
  250. { text: '(', scopes: [] },
  251. { text: 'B', scopes: ['constructor'] },
  252. { text: '(new ', scopes: [] },
  253. { text: 'C', scopes: ['constructor'] },
  254. { text: '))', scopes: [] }
  255. ]
  256. ]);
  257. });
  258. it('handles edits after tokens that end between CR and LF characters (regression)', async () => {
  259. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  260. parser: 'tree-sitter-javascript',
  261. scopes: {
  262. comment: 'comment',
  263. string: 'string',
  264. property_identifier: 'property'
  265. }
  266. });
  267. buffer.setText(['// abc', '', 'a("b").c'].join('\r\n'));
  268. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  269. buffer.setLanguageMode(languageMode);
  270. expectTokensToEqual(editor, [
  271. [{ text: '// abc', scopes: ['comment'] }],
  272. [],
  273. [
  274. { text: 'a(', scopes: [] },
  275. { text: '"b"', scopes: ['string'] },
  276. { text: ').', scopes: [] },
  277. { text: 'c', scopes: ['property'] }
  278. ]
  279. ]);
  280. buffer.insert([2, 0], ' ');
  281. expectTokensToEqual(editor, [
  282. [{ text: '// abc', scopes: ['comment'] }],
  283. [],
  284. [
  285. { text: ' ', scopes: ['leading-whitespace'] },
  286. { text: 'a(', scopes: [] },
  287. { text: '"b"', scopes: ['string'] },
  288. { text: ').', scopes: [] },
  289. { text: 'c', scopes: ['property'] }
  290. ]
  291. ]);
  292. });
  293. it('handles multi-line nodes with children on different lines (regression)', async () => {
  294. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  295. parser: 'tree-sitter-javascript',
  296. scopes: {
  297. template_string: 'string',
  298. '"${"': 'interpolation',
  299. '"}"': 'interpolation'
  300. }
  301. });
  302. buffer.setText('`\na${1}\nb${2}\n`;');
  303. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  304. buffer.setLanguageMode(languageMode);
  305. expectTokensToEqual(editor, [
  306. [{ text: '`', scopes: ['string'] }],
  307. [
  308. { text: 'a', scopes: ['string'] },
  309. { text: '${', scopes: ['string', 'interpolation'] },
  310. { text: '1', scopes: ['string'] },
  311. { text: '}', scopes: ['string', 'interpolation'] }
  312. ],
  313. [
  314. { text: 'b', scopes: ['string'] },
  315. { text: '${', scopes: ['string', 'interpolation'] },
  316. { text: '2', scopes: ['string'] },
  317. { text: '}', scopes: ['string', 'interpolation'] }
  318. ],
  319. [{ text: '`', scopes: ['string'] }, { text: ';', scopes: [] }]
  320. ]);
  321. });
  322. it('handles folds inside of highlighted tokens', async () => {
  323. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  324. parser: 'tree-sitter-javascript',
  325. scopes: {
  326. comment: 'comment',
  327. 'call_expression > identifier': 'function'
  328. }
  329. });
  330. buffer.setText(dedent`
  331. /*
  332. * Hello
  333. */
  334. hello();
  335. `);
  336. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  337. buffer.setLanguageMode(languageMode);
  338. editor.foldBufferRange([[0, 2], [2, 0]]);
  339. expectTokensToEqual(editor, [
  340. [
  341. { text: '/*', scopes: ['comment'] },
  342. { text: '…', scopes: ['fold-marker'] },
  343. { text: ' */', scopes: ['comment'] }
  344. ],
  345. [],
  346. [{ text: 'hello', scopes: ['function'] }, { text: '();', scopes: [] }]
  347. ]);
  348. });
  349. it('applies regex match rules when specified', async () => {
  350. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  351. parser: 'tree-sitter-javascript',
  352. scopes: {
  353. identifier: [
  354. { match: '^(exports|document|window|global)$', scopes: 'global' },
  355. { match: '^[A-Z_]+$', scopes: 'constant' },
  356. { match: '^[A-Z]', scopes: 'constructor' },
  357. 'variable'
  358. ]
  359. }
  360. });
  361. buffer.setText(`exports.object = Class(SOME_CONSTANT, x)`);
  362. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  363. buffer.setLanguageMode(languageMode);
  364. expectTokensToEqual(editor, [
  365. [
  366. { text: 'exports', scopes: ['global'] },
  367. { text: '.object = ', scopes: [] },
  368. { text: 'Class', scopes: ['constructor'] },
  369. { text: '(', scopes: [] },
  370. { text: 'SOME_CONSTANT', scopes: ['constant'] },
  371. { text: ', ', scopes: [] },
  372. { text: 'x', scopes: ['variable'] },
  373. { text: ')', scopes: [] }
  374. ]
  375. ]);
  376. });
  377. it('handles nodes that start before their first child and end after their last child', async () => {
  378. const grammar = new TreeSitterGrammar(atom.grammars, rubyGrammarPath, {
  379. parser: 'tree-sitter-ruby',
  380. scopes: {
  381. bare_string: 'string',
  382. interpolation: 'embedded',
  383. '"#{"': 'punctuation',
  384. '"}"': 'punctuation'
  385. }
  386. });
  387. // The bare string node `bc#{d}ef` has one child: the interpolation, and that child
  388. // starts later and ends earlier than the bare string.
  389. buffer.setText('a = %W( bc#{d}ef )');
  390. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  391. buffer.setLanguageMode(languageMode);
  392. expectTokensToEqual(editor, [
  393. [
  394. { text: 'a = %W( ', scopes: [] },
  395. { text: 'bc', scopes: ['string'] },
  396. { text: '#{', scopes: ['string', 'embedded', 'punctuation'] },
  397. { text: 'd', scopes: ['string', 'embedded'] },
  398. { text: '}', scopes: ['string', 'embedded', 'punctuation'] },
  399. { text: 'ef', scopes: ['string'] },
  400. { text: ' )', scopes: [] }
  401. ]
  402. ]);
  403. });
  404. describe('when the buffer changes during a parse', () => {
  405. it('immediately parses again when the current parse completes', async () => {
  406. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  407. parser: 'tree-sitter-javascript',
  408. scopes: {
  409. identifier: 'variable',
  410. 'call_expression > identifier': 'function',
  411. 'new_expression > identifier': 'constructor'
  412. }
  413. });
  414. buffer.setText('abc;');
  415. const languageMode = new TreeSitterLanguageMode({
  416. buffer,
  417. grammar,
  418. syncTimeoutMicros: 0
  419. });
  420. buffer.setLanguageMode(languageMode);
  421. await nextHighlightingUpdate(languageMode);
  422. await new Promise(process.nextTick);
  423. expectTokensToEqual(editor, [
  424. [
  425. { text: 'abc', scopes: ['variable'] },
  426. { text: ';', scopes: [] }
  427. ]
  428. ]);
  429. buffer.setTextInRange([[0, 3], [0, 3]], '()');
  430. expectTokensToEqual(editor, [
  431. [
  432. { text: 'abc()', scopes: ['variable'] },
  433. { text: ';', scopes: [] }
  434. ]
  435. ]);
  436. buffer.setTextInRange([[0, 0], [0, 0]], 'new ');
  437. expectTokensToEqual(editor, [
  438. [
  439. { text: 'new ', scopes: [] },
  440. { text: 'abc()', scopes: ['variable'] },
  441. { text: ';', scopes: [] }
  442. ]
  443. ]);
  444. await nextHighlightingUpdate(languageMode);
  445. expectTokensToEqual(editor, [
  446. [
  447. { text: 'new ', scopes: [] },
  448. { text: 'abc', scopes: ['function'] },
  449. { text: '();', scopes: [] }
  450. ]
  451. ]);
  452. await nextHighlightingUpdate(languageMode);
  453. expectTokensToEqual(editor, [
  454. [
  455. { text: 'new ', scopes: [] },
  456. { text: 'abc', scopes: ['constructor'] },
  457. { text: '();', scopes: [] }
  458. ]
  459. ]);
  460. });
  461. });
  462. describe('when changes are small enough to be re-parsed synchronously', () => {
  463. it('can incorporate multiple consecutive synchronous updates', () => {
  464. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  465. parser: 'tree-sitter-javascript',
  466. scopes: {
  467. property_identifier: 'property',
  468. 'call_expression > identifier': 'function',
  469. 'call_expression > member_expression > property_identifier':
  470. 'method'
  471. }
  472. });
  473. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  474. buffer.setLanguageMode(languageMode);
  475. buffer.setText('a');
  476. expectTokensToEqual(editor, [[{ text: 'a', scopes: [] }]]);
  477. buffer.append('.');
  478. expectTokensToEqual(editor, [[{ text: 'a.', scopes: [] }]]);
  479. buffer.append('b');
  480. expectTokensToEqual(editor, [
  481. [{ text: 'a.', scopes: [] }, { text: 'b', scopes: ['property'] }]
  482. ]);
  483. buffer.append('()');
  484. expectTokensToEqual(editor, [
  485. [
  486. { text: 'a.', scopes: [] },
  487. { text: 'b', scopes: ['method'] },
  488. { text: '()', scopes: [] }
  489. ]
  490. ]);
  491. buffer.delete([[0, 1], [0, 2]]);
  492. expectTokensToEqual(editor, [
  493. [{ text: 'ab', scopes: ['function'] }, { text: '()', scopes: [] }]
  494. ]);
  495. });
  496. });
  497. describe('injectionPoints and injectionPatterns', () => {
  498. let jsGrammar, htmlGrammar;
  499. beforeEach(() => {
  500. jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  501. scopeName: 'javascript',
  502. parser: 'tree-sitter-javascript',
  503. scopes: {
  504. comment: 'comment',
  505. property_identifier: 'property',
  506. 'call_expression > identifier': 'function',
  507. template_string: 'string',
  508. 'template_substitution > "${"': 'interpolation',
  509. 'template_substitution > "}"': 'interpolation'
  510. },
  511. injectionRegExp: 'javascript',
  512. injectionPoints: [
  513. HTML_TEMPLATE_LITERAL_INJECTION_POINT,
  514. JSDOC_INJECTION_POINT
  515. ]
  516. });
  517. htmlGrammar = new TreeSitterGrammar(atom.grammars, htmlGrammarPath, {
  518. scopeName: 'html',
  519. parser: 'tree-sitter-html',
  520. scopes: {
  521. fragment: 'html',
  522. tag_name: 'tag',
  523. attribute_name: 'attr'
  524. },
  525. injectionRegExp: 'html',
  526. injectionPoints: [SCRIPT_TAG_INJECTION_POINT]
  527. });
  528. });
  529. it('highlights code inside of injection points', async () => {
  530. atom.grammars.addGrammar(jsGrammar);
  531. atom.grammars.addGrammar(htmlGrammar);
  532. buffer.setText('node.innerHTML = html `\na ${b}<img src="d">\n`;');
  533. const languageMode = new TreeSitterLanguageMode({
  534. buffer,
  535. grammar: jsGrammar,
  536. grammars: atom.grammars
  537. });
  538. buffer.setLanguageMode(languageMode);
  539. expectTokensToEqual(editor, [
  540. [
  541. { text: 'node.', scopes: [] },
  542. { text: 'innerHTML', scopes: ['property'] },
  543. { text: ' = ', scopes: [] },
  544. { text: 'html', scopes: ['function'] },
  545. { text: ' ', scopes: [] },
  546. { text: '`', scopes: ['string'] }
  547. ],
  548. [
  549. { text: 'a ', scopes: ['string', 'html'] },
  550. { text: '${', scopes: ['string', 'html', 'interpolation'] },
  551. { text: 'b', scopes: ['string', 'html'] },
  552. { text: '}', scopes: ['string', 'html', 'interpolation'] },
  553. { text: '<', scopes: ['string', 'html'] },
  554. { text: 'img', scopes: ['string', 'html', 'tag'] },
  555. { text: ' ', scopes: ['string', 'html'] },
  556. { text: 'src', scopes: ['string', 'html', 'attr'] },
  557. { text: '="d">', scopes: ['string', 'html'] }
  558. ],
  559. [{ text: '`', scopes: ['string'] }, { text: ';', scopes: [] }]
  560. ]);
  561. const range = buffer.findSync('html');
  562. buffer.setTextInRange(range, 'xml');
  563. await nextHighlightingUpdate(languageMode);
  564. expectTokensToEqual(editor, [
  565. [
  566. { text: 'node.', scopes: [] },
  567. { text: 'innerHTML', scopes: ['property'] },
  568. { text: ' = ', scopes: [] },
  569. { text: 'xml', scopes: ['function'] },
  570. { text: ' ', scopes: [] },
  571. { text: '`', scopes: ['string'] }
  572. ],
  573. [
  574. { text: 'a ', scopes: ['string'] },
  575. { text: '${', scopes: ['string', 'interpolation'] },
  576. { text: 'b', scopes: ['string'] },
  577. { text: '}', scopes: ['string', 'interpolation'] },
  578. { text: '<img src="d">', scopes: ['string'] }
  579. ],
  580. [{ text: '`', scopes: ['string'] }, { text: ';', scopes: [] }]
  581. ]);
  582. });
  583. it('highlights the content after injections', async () => {
  584. atom.grammars.addGrammar(jsGrammar);
  585. atom.grammars.addGrammar(htmlGrammar);
  586. buffer.setText('<script>\nhello();\n</script>\n<div>\n</div>');
  587. const languageMode = new TreeSitterLanguageMode({
  588. buffer,
  589. grammar: htmlGrammar,
  590. grammars: atom.grammars
  591. });
  592. buffer.setLanguageMode(languageMode);
  593. expectTokensToEqual(editor, [
  594. [
  595. { text: '<', scopes: ['html'] },
  596. { text: 'script', scopes: ['html', 'tag'] },
  597. { text: '>', scopes: ['html'] }
  598. ],
  599. [
  600. { text: 'hello', scopes: ['html', 'function'] },
  601. { text: '();', scopes: ['html'] }
  602. ],
  603. [
  604. { text: '</', scopes: ['html'] },
  605. { text: 'script', scopes: ['html', 'tag'] },
  606. { text: '>', scopes: ['html'] }
  607. ],
  608. [
  609. { text: '<', scopes: ['html'] },
  610. { text: 'div', scopes: ['html', 'tag'] },
  611. { text: '>', scopes: ['html'] }
  612. ],
  613. [
  614. { text: '</', scopes: ['html'] },
  615. { text: 'div', scopes: ['html', 'tag'] },
  616. { text: '>', scopes: ['html'] }
  617. ]
  618. ]);
  619. });
  620. it('updates buffers highlighting when a grammar with injectionRegExp is added', async () => {
  621. atom.grammars.addGrammar(jsGrammar);
  622. buffer.setText('node.innerHTML = html `\na ${b}<img src="d">\n`;');
  623. const languageMode = new TreeSitterLanguageMode({
  624. buffer,
  625. grammar: jsGrammar,
  626. grammars: atom.grammars
  627. });
  628. buffer.setLanguageMode(languageMode);
  629. expectTokensToEqual(editor, [
  630. [
  631. { text: 'node.', scopes: [] },
  632. { text: 'innerHTML', scopes: ['property'] },
  633. { text: ' = ', scopes: [] },
  634. { text: 'html', scopes: ['function'] },
  635. { text: ' ', scopes: [] },
  636. { text: '`', scopes: ['string'] }
  637. ],
  638. [
  639. { text: 'a ', scopes: ['string'] },
  640. { text: '${', scopes: ['string', 'interpolation'] },
  641. { text: 'b', scopes: ['string'] },
  642. { text: '}', scopes: ['string', 'interpolation'] },
  643. { text: '<img src="d">', scopes: ['string'] }
  644. ],
  645. [{ text: '`', scopes: ['string'] }, { text: ';', scopes: [] }]
  646. ]);
  647. atom.grammars.addGrammar(htmlGrammar);
  648. await nextHighlightingUpdate(languageMode);
  649. expectTokensToEqual(editor, [
  650. [
  651. { text: 'node.', scopes: [] },
  652. { text: 'innerHTML', scopes: ['property'] },
  653. { text: ' = ', scopes: [] },
  654. { text: 'html', scopes: ['function'] },
  655. { text: ' ', scopes: [] },
  656. { text: '`', scopes: ['string'] }
  657. ],
  658. [
  659. { text: 'a ', scopes: ['string', 'html'] },
  660. { text: '${', scopes: ['string', 'html', 'interpolation'] },
  661. { text: 'b', scopes: ['string', 'html'] },
  662. { text: '}', scopes: ['string', 'html', 'interpolation'] },
  663. { text: '<', scopes: ['string', 'html'] },
  664. { text: 'img', scopes: ['string', 'html', 'tag'] },
  665. { text: ' ', scopes: ['string', 'html'] },
  666. { text: 'src', scopes: ['string', 'html', 'attr'] },
  667. { text: '="d">', scopes: ['string', 'html'] }
  668. ],
  669. [{ text: '`', scopes: ['string'] }, { text: ';', scopes: [] }]
  670. ]);
  671. });
  672. it('handles injections that intersect', async () => {
  673. const ejsGrammar = new TreeSitterGrammar(
  674. atom.grammars,
  675. ejsGrammarPath,
  676. {
  677. id: 'ejs',
  678. parser: 'tree-sitter-embedded-template',
  679. scopes: {
  680. '"<%="': 'directive',
  681. '"%>"': 'directive'
  682. },
  683. injectionPoints: [
  684. {
  685. type: 'template',
  686. language(node) {
  687. return 'javascript';
  688. },
  689. content(node) {
  690. return node.descendantsOfType('code');
  691. }
  692. },
  693. {
  694. type: 'template',
  695. language(node) {
  696. return 'html';
  697. },
  698. content(node) {
  699. return node.descendantsOfType('content');
  700. }
  701. }
  702. ]
  703. }
  704. );
  705. atom.grammars.addGrammar(jsGrammar);
  706. atom.grammars.addGrammar(htmlGrammar);
  707. buffer.setText('<body>\n<script>\nb(<%= c.d %>)\n</script>\n</body>');
  708. const languageMode = new TreeSitterLanguageMode({
  709. buffer,
  710. grammar: ejsGrammar,
  711. grammars: atom.grammars
  712. });
  713. buffer.setLanguageMode(languageMode);
  714. expectTokensToEqual(editor, [
  715. [
  716. { text: '<', scopes: ['html'] },
  717. { text: 'body', scopes: ['html', 'tag'] },
  718. { text: '>', scopes: ['html'] }
  719. ],
  720. [
  721. { text: '<', scopes: ['html'] },
  722. { text: 'script', scopes: ['html', 'tag'] },
  723. { text: '>', scopes: ['html'] }
  724. ],
  725. [
  726. { text: 'b', scopes: ['html', 'function'] },
  727. { text: '(', scopes: ['html'] },
  728. { text: '<%=', scopes: ['html', 'directive'] },
  729. { text: ' c.', scopes: ['html'] },
  730. { text: 'd', scopes: ['html', 'property'] },
  731. { text: ' ', scopes: ['html'] },
  732. { text: '%>', scopes: ['html', 'directive'] },
  733. { text: ')', scopes: ['html'] }
  734. ],
  735. [
  736. { text: '</', scopes: ['html'] },
  737. { text: 'script', scopes: ['html', 'tag'] },
  738. { text: '>', scopes: ['html'] }
  739. ],
  740. [
  741. { text: '</', scopes: ['html'] },
  742. { text: 'body', scopes: ['html', 'tag'] },
  743. { text: '>', scopes: ['html'] }
  744. ]
  745. ]);
  746. });
  747. it('handles injections that are empty', async () => {
  748. atom.grammars.addGrammar(jsGrammar);
  749. atom.grammars.addGrammar(htmlGrammar);
  750. buffer.setText('text = html');
  751. const languageMode = new TreeSitterLanguageMode({
  752. buffer,
  753. grammar: jsGrammar,
  754. grammars: atom.grammars
  755. });
  756. buffer.setLanguageMode(languageMode);
  757. expectTokensToEqual(editor, [[{ text: 'text = html', scopes: [] }]]);
  758. buffer.append(' ``;');
  759. expectTokensToEqual(editor, [
  760. [
  761. { text: 'text = ', scopes: [] },
  762. { text: 'html', scopes: ['function'] },
  763. { text: ' ', scopes: [] },
  764. { text: '``', scopes: ['string'] },
  765. { text: ';', scopes: [] }
  766. ]
  767. ]);
  768. buffer.insert(
  769. { row: 0, column: buffer.getText().lastIndexOf('`') },
  770. '<div>'
  771. );
  772. await nextHighlightingUpdate(languageMode);
  773. expectTokensToEqual(editor, [
  774. [
  775. { text: 'text = ', scopes: [] },
  776. { text: 'html', scopes: ['function'] },
  777. { text: ' ', scopes: [] },
  778. { text: '`', scopes: ['string'] },
  779. { text: '<', scopes: ['string', 'html'] },
  780. { text: 'div', scopes: ['string', 'html', 'tag'] },
  781. { text: '>', scopes: ['string', 'html'] },
  782. { text: '`', scopes: ['string'] },
  783. { text: ';', scopes: [] }
  784. ]
  785. ]);
  786. buffer.undo();
  787. await nextHighlightingUpdate(languageMode);
  788. expectTokensToEqual(editor, [
  789. [
  790. { text: 'text = ', scopes: [] },
  791. { text: 'html', scopes: ['function'] },
  792. { text: ' ', scopes: [] },
  793. { text: '``', scopes: ['string'] },
  794. { text: ';', scopes: [] }
  795. ]
  796. ]);
  797. });
  798. it('terminates comment token at the end of an injection, so that the next injection is NOT a continuation of the comment', async () => {
  799. const ejsGrammar = new TreeSitterGrammar(
  800. atom.grammars,
  801. ejsGrammarPath,
  802. {
  803. id: 'ejs',
  804. parser: 'tree-sitter-embedded-template',
  805. scopes: {
  806. '"<%"': 'directive',
  807. '"%>"': 'directive'
  808. },
  809. injectionPoints: [
  810. {
  811. type: 'template',
  812. language(node) {
  813. return 'javascript';
  814. },
  815. content(node) {
  816. return node.descendantsOfType('code');
  817. },
  818. newlinesBetween: true
  819. },
  820. {
  821. type: 'template',
  822. language(node) {
  823. return 'html';
  824. },
  825. content(node) {
  826. return node.descendantsOfType('content');
  827. }
  828. }
  829. ]
  830. }
  831. );
  832. atom.grammars.addGrammar(jsGrammar);
  833. atom.grammars.addGrammar(htmlGrammar);
  834. buffer.setText('<% // js comment %> b\n<% b() %>');
  835. const languageMode = new TreeSitterLanguageMode({
  836. buffer,
  837. grammar: ejsGrammar,
  838. grammars: atom.grammars
  839. });
  840. buffer.setLanguageMode(languageMode);
  841. expectTokensToEqual(editor, [
  842. [
  843. { text: '<%', scopes: ['directive'] },
  844. { text: ' ', scopes: [] },
  845. { text: '// js comment ', scopes: ['comment'] },
  846. { text: '%>', scopes: ['directive'] },
  847. { text: ' b', scopes: ['html'] }
  848. ],
  849. [
  850. { text: '<%', scopes: ['directive'] },
  851. { text: ' ', scopes: [] },
  852. { text: 'b', scopes: ['function'] },
  853. { text: '() ', scopes: [] },
  854. { text: '%>', scopes: ['directive'] }
  855. ]
  856. ]);
  857. });
  858. it('only covers scope boundaries in parent layers if a nested layer has a boundary at the same position', async () => {
  859. const jsdocGrammar = new TreeSitterGrammar(
  860. atom.grammars,
  861. jsdocGrammarPath,
  862. {
  863. scopeName: 'jsdoc',
  864. parser: 'tree-sitter-jsdoc',
  865. scopes: {},
  866. injectionRegExp: 'jsdoc',
  867. injectionPoints: []
  868. }
  869. );
  870. atom.grammars.addGrammar(jsGrammar);
  871. atom.grammars.addGrammar(jsdocGrammar);
  872. editor.setGrammar(jsGrammar);
  873. editor.setText('/**\n*/\n{\n}');
  874. expectTokensToEqual(editor, [
  875. [{ text: '/**', scopes: ['comment'] }],
  876. [{ text: '*/', scopes: ['comment'] }],
  877. [{ text: '{', scopes: [] }],
  878. [{ text: '}', scopes: [] }]
  879. ]);
  880. });
  881. it('reports scopes from shallower layers when they are at the start or end of an injection', async () => {
  882. await atom.packages.activatePackage('language-javascript');
  883. editor.setGrammar(atom.grammars.grammarForScopeName('source.js'));
  884. editor.setText('/** @babel */\n{\n}');
  885. expectTokensToEqual(editor, [
  886. [
  887. { text: '/** ', scopes: ['source js', 'comment block'] },
  888. {
  889. text: '@babel',
  890. scopes: ['source js', 'comment block', 'keyword control']
  891. },
  892. { text: ' *', scopes: ['source js', 'comment block'] },
  893. {
  894. text: '/',
  895. scopes: ['source js', 'comment block', 'meta delimiter slash']
  896. }
  897. ],
  898. [
  899. {
  900. text: '{',
  901. scopes: [
  902. 'source js',
  903. 'punctuation definition function body begin bracket curly'
  904. ]
  905. }
  906. ],
  907. [
  908. {
  909. text: '}',
  910. scopes: [
  911. 'source js',
  912. 'punctuation definition function body end bracket curly'
  913. ]
  914. }
  915. ]
  916. ]);
  917. });
  918. it('respects the `includeChildren` property of injection points', async () => {
  919. const rustGrammar = new TreeSitterGrammar(
  920. atom.grammars,
  921. rustGrammarPath,
  922. {
  923. scopeName: 'rust',
  924. parser: 'tree-sitter-rust',
  925. scopes: {
  926. identifier: 'variable',
  927. field_identifier: 'property',
  928. 'call_expression > field_expression > field_identifier':
  929. 'function',
  930. 'macro_invocation > identifier': 'macro'
  931. },
  932. injectionRegExp: 'rust',
  933. injectionPoints: [
  934. {
  935. type: 'macro_invocation',
  936. language() {
  937. return 'rust';
  938. },
  939. content(node) {
  940. return node.lastChild;
  941. },
  942. // The tokens within a `token_tree` are all parsed as separate
  943. // children of the `token_tree`. By default, when adding a language
  944. // injection for a node, the node's children's ranges would be
  945. // excluded from the injection. But for this injection point
  946. // (parsing token trees as rust code), we want to reparse all of the
  947. // content of the token tree.
  948. includeChildren: true
  949. }
  950. ]
  951. }
  952. );
  953. atom.grammars.addGrammar(rustGrammar);
  954. // Macro call within another macro call.
  955. buffer.setText('assert_eq!(a.b.c(), vec![d.e()]); f.g();');
  956. const languageMode = new TreeSitterLanguageMode({
  957. buffer,
  958. grammar: rustGrammar,
  959. grammars: atom.grammars
  960. });
  961. buffer.setLanguageMode(languageMode);
  962. // There should not be duplicate scopes due to the root layer
  963. // and for the injected rust layer.
  964. expectTokensToEqual(editor, [
  965. [
  966. { text: 'assert_eq', scopes: ['macro'] },
  967. { text: '!(', scopes: [] },
  968. { text: 'a', scopes: ['variable'] },
  969. { text: '.', scopes: [] },
  970. { text: 'b', scopes: ['property'] },
  971. { text: '.', scopes: [] },
  972. { text: 'c', scopes: ['function'] },
  973. { text: '(), ', scopes: [] },
  974. { text: 'vec', scopes: ['macro'] },
  975. { text: '![', scopes: [] },
  976. { text: 'd', scopes: ['variable'] },
  977. { text: '.', scopes: [] },
  978. { text: 'e', scopes: ['function'] },
  979. { text: '()]); ', scopes: [] },
  980. { text: 'f', scopes: ['variable'] },
  981. { text: '.', scopes: [] },
  982. { text: 'g', scopes: ['function'] },
  983. { text: '();', scopes: [] }
  984. ]
  985. ]);
  986. });
  987. it('notifies onDidTokenize listeners the first time all syntax highlighting is done', async () => {
  988. const promise = new Promise(resolve => {
  989. editor.onDidTokenize(event => {
  990. expectTokensToEqual(editor, [
  991. [
  992. { text: '<', scopes: ['html'] },
  993. { text: 'script', scopes: ['html', 'tag'] },
  994. { text: '>', scopes: ['html'] }
  995. ],
  996. [
  997. { text: 'hello', scopes: ['html', 'function'] },
  998. { text: '();', scopes: ['html'] }
  999. ],
  1000. [
  1001. { text: '</', scopes: ['html'] },
  1002. { text: 'script', scopes: ['html', 'tag'] },
  1003. { text: '>', scopes: ['html'] }
  1004. ]
  1005. ]);
  1006. resolve();
  1007. });
  1008. });
  1009. atom.grammars.addGrammar(jsGrammar);
  1010. atom.grammars.addGrammar(htmlGrammar);
  1011. buffer.setText('<script>\nhello();\n</script>');
  1012. const languageMode = new TreeSitterLanguageMode({
  1013. buffer,
  1014. grammar: htmlGrammar,
  1015. grammars: atom.grammars,
  1016. syncTimeoutMicros: 0
  1017. });
  1018. buffer.setLanguageMode(languageMode);
  1019. await promise;
  1020. });
  1021. });
  1022. });
  1023. describe('highlighting after random changes', () => {
  1024. let originalTimeout;
  1025. beforeEach(() => {
  1026. originalTimeout = jasmine.getEnv().defaultTimeoutInterval;
  1027. jasmine.getEnv().defaultTimeoutInterval = 60 * 1000;
  1028. });
  1029. afterEach(() => {
  1030. jasmine.getEnv().defaultTimeoutInterval = originalTimeout;
  1031. });
  1032. it('matches the highlighting of a freshly-opened editor', async () => {
  1033. jasmine.useRealClock();
  1034. const text = fs.readFileSync(
  1035. path.join(__dirname, 'fixtures', 'sample.js'),
  1036. 'utf8'
  1037. );
  1038. atom.grammars.loadGrammarSync(jsGrammarPath);
  1039. atom.grammars.assignLanguageMode(buffer, 'source.js');
  1040. buffer.getLanguageMode().syncTimeoutMicros = 0;
  1041. const initialSeed = Date.now();
  1042. for (let i = 0, trialCount = 10; i < trialCount; i++) {
  1043. let seed = initialSeed + i;
  1044. // seed = 1541201470759
  1045. const random = Random(seed);
  1046. // Parse the initial content and render all of the screen lines.
  1047. buffer.setText(text);
  1048. buffer.clearUndoStack();
  1049. await buffer.getLanguageMode().parseCompletePromise();
  1050. editor.displayLayer.getScreenLines();
  1051. // Make several random edits.
  1052. for (let j = 0, editCount = 1 + random(4); j < editCount; j++) {
  1053. const editRoll = random(10);
  1054. const range = getRandomBufferRange(random, buffer);
  1055. if (editRoll < 2) {
  1056. const linesToInsert = buildRandomLines(
  1057. random,
  1058. range.getExtent().row + 1
  1059. );
  1060. // console.log('replace', range.toString(), JSON.stringify(linesToInsert))
  1061. buffer.setTextInRange(range, linesToInsert);
  1062. } else if (editRoll < 5) {
  1063. // console.log('delete', range.toString())
  1064. buffer.delete(range);
  1065. } else {
  1066. const linesToInsert = buildRandomLines(random, 3);
  1067. // console.log('insert', range.start.toString(), JSON.stringify(linesToInsert))
  1068. buffer.insert(range.start, linesToInsert);
  1069. }
  1070. // console.log(buffer.getText())
  1071. // Sometimes, let the parse complete before re-rendering.
  1072. // Sometimes re-render and move on before the parse completes.
  1073. if (random(2)) await buffer.getLanguageMode().parseCompletePromise();
  1074. editor.displayLayer.getScreenLines();
  1075. }
  1076. // Revert the edits, because Tree-sitter's error recovery is somewhat path-dependent,
  1077. // and we want a state where the tree parse result is guaranteed.
  1078. while (buffer.undo()) {}
  1079. // Create a fresh buffer and editor with the same text.
  1080. const buffer2 = new TextBuffer(buffer.getText());
  1081. const editor2 = new TextEditor({ buffer: buffer2 });
  1082. atom.grammars.assignLanguageMode(buffer2, 'source.js');
  1083. // Verify that the the two buffers have the same syntax highlighting.
  1084. await buffer.getLanguageMode().parseCompletePromise();
  1085. await buffer2.getLanguageMode().parseCompletePromise();
  1086. expect(buffer.getLanguageMode().tree.rootNode.toString()).toEqual(
  1087. buffer2.getLanguageMode().tree.rootNode.toString(),
  1088. `Seed: ${seed}`
  1089. );
  1090. for (let j = 0, n = editor.getScreenLineCount(); j < n; j++) {
  1091. const tokens1 = editor.tokensForScreenRow(j);
  1092. const tokens2 = editor2.tokensForScreenRow(j);
  1093. expect(tokens1).toEqual(tokens2, `Seed: ${seed}, screen line: ${j}`);
  1094. if (jasmine.getEnv().currentSpec.results().failedCount > 0) {
  1095. console.log(tokens1);
  1096. console.log(tokens2);
  1097. debugger; // eslint-disable-line no-debugger
  1098. break;
  1099. }
  1100. }
  1101. if (jasmine.getEnv().currentSpec.results().failedCount > 0) break;
  1102. }
  1103. });
  1104. });
  1105. describe('folding', () => {
  1106. it('can fold nodes that start and end with specified tokens', async () => {
  1107. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1108. parser: 'tree-sitter-javascript',
  1109. folds: [
  1110. {
  1111. start: { type: '{', index: 0 },
  1112. end: { type: '}', index: -1 }
  1113. },
  1114. {
  1115. start: { type: '(', index: 0 },
  1116. end: { type: ')', index: -1 }
  1117. }
  1118. ]
  1119. });
  1120. buffer.setText(dedent`
  1121. module.exports =
  1122. class A {
  1123. getB (c,
  1124. d,
  1125. e) {
  1126. return this.f(g)
  1127. }
  1128. }
  1129. `);
  1130. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  1131. buffer.setLanguageMode(languageMode);
  1132. expect(editor.isFoldableAtBufferRow(0)).toBe(false);
  1133. expect(editor.isFoldableAtBufferRow(1)).toBe(true);
  1134. expect(editor.isFoldableAtBufferRow(2)).toBe(true);
  1135. expect(editor.isFoldableAtBufferRow(3)).toBe(false);
  1136. expect(editor.isFoldableAtBufferRow(4)).toBe(true);
  1137. expect(editor.isFoldableAtBufferRow(5)).toBe(false);
  1138. editor.foldBufferRow(2);
  1139. expect(getDisplayText(editor)).toBe(dedent`
  1140. module.exports =
  1141. class A {
  1142. getB (c,…) {
  1143. return this.f(g)
  1144. }
  1145. }
  1146. `);
  1147. editor.foldBufferRow(4);
  1148. expect(getDisplayText(editor)).toBe(dedent`
  1149. module.exports =
  1150. class A {
  1151. getB (c,…) {…}
  1152. }
  1153. `);
  1154. });
  1155. it('folds entire buffer rows when necessary to keep words on separate lines', async () => {
  1156. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1157. parser: 'tree-sitter-javascript',
  1158. folds: [
  1159. {
  1160. start: { type: '{', index: 0 },
  1161. end: { type: '}', index: -1 }
  1162. },
  1163. {
  1164. start: { type: '(', index: 0 },
  1165. end: { type: ')', index: -1 }
  1166. }
  1167. ]
  1168. });
  1169. buffer.setText(dedent`
  1170. if (a) {
  1171. b
  1172. } else if (c) {
  1173. d
  1174. } else {
  1175. e
  1176. }
  1177. `);
  1178. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  1179. buffer.setLanguageMode(languageMode);
  1180. // Avoid bringing the `else if...` up onto the same screen line as the preceding `if`.
  1181. editor.foldBufferRow(1);
  1182. editor.foldBufferRow(3);
  1183. expect(getDisplayText(editor)).toBe(dedent`
  1184. if (a) {…
  1185. } else if (c) {…
  1186. } else {
  1187. e
  1188. }
  1189. `);
  1190. // It's ok to bring the final `}` onto the same screen line as the preceding `else`.
  1191. editor.foldBufferRow(5);
  1192. expect(getDisplayText(editor)).toBe(dedent`
  1193. if (a) {…
  1194. } else if (c) {…
  1195. } else {…}
  1196. `);
  1197. });
  1198. it('can fold nodes of specified types', async () => {
  1199. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1200. parser: 'tree-sitter-javascript',
  1201. folds: [
  1202. // Start the fold after the first child (the opening tag) and end it at the last child
  1203. // (the closing tag).
  1204. {
  1205. type: 'jsx_element',
  1206. start: { index: 0 },
  1207. end: { index: -1 }
  1208. },
  1209. // End the fold at the *second* to last child of the self-closing tag: the `/`.
  1210. {
  1211. type: 'jsx_self_closing_element',
  1212. start: { index: 1 },
  1213. end: { index: -2 }
  1214. }
  1215. ]
  1216. });
  1217. buffer.setText(dedent`
  1218. const element1 = <Element
  1219. className='submit'
  1220. id='something' />
  1221. const element2 = <Element>
  1222. <span>hello</span>
  1223. <span>world</span>
  1224. </Element>
  1225. `);
  1226. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  1227. buffer.setLanguageMode(languageMode);
  1228. expect(editor.isFoldableAtBufferRow(0)).toBe(true);
  1229. expect(editor.isFoldableAtBufferRow(1)).toBe(false);
  1230. expect(editor.isFoldableAtBufferRow(2)).toBe(false);
  1231. expect(editor.isFoldableAtBufferRow(3)).toBe(false);
  1232. expect(editor.isFoldableAtBufferRow(4)).toBe(true);
  1233. expect(editor.isFoldableAtBufferRow(5)).toBe(false);
  1234. editor.foldBufferRow(0);
  1235. expect(getDisplayText(editor)).toBe(dedent`
  1236. const element1 = <Element…/>
  1237. const element2 = <Element>
  1238. <span>hello</span>
  1239. <span>world</span>
  1240. </Element>
  1241. `);
  1242. editor.foldBufferRow(4);
  1243. expect(getDisplayText(editor)).toBe(dedent`
  1244. const element1 = <Element…/>
  1245. const element2 = <Element>…
  1246. </Element>
  1247. `);
  1248. });
  1249. it('can fold entire nodes when no start or end parameters are specified', async () => {
  1250. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1251. parser: 'tree-sitter-javascript',
  1252. folds: [
  1253. // By default, for a node with no children, folds are started at the *end* of the first
  1254. // line of a node, and ended at the *beginning* of the last line.
  1255. { type: 'comment' }
  1256. ]
  1257. });
  1258. buffer.setText(dedent`
  1259. /**
  1260. * Important
  1261. */
  1262. const x = 1 /*
  1263. Also important
  1264. */
  1265. `);
  1266. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  1267. buffer.setLanguageMode(languageMode);
  1268. expect(editor.isFoldableAtBufferRow(0)).toBe(true);
  1269. expect(editor.isFoldableAtBufferRow(1)).toBe(false);
  1270. expect(editor.isFoldableAtBufferRow(2)).toBe(false);
  1271. expect(editor.isFoldableAtBufferRow(3)).toBe(true);
  1272. expect(editor.isFoldableAtBufferRow(4)).toBe(false);
  1273. editor.foldBufferRow(0);
  1274. expect(getDisplayText(editor)).toBe(dedent`
  1275. /**… */
  1276. const x = 1 /*
  1277. Also important
  1278. */
  1279. `);
  1280. editor.foldBufferRow(3);
  1281. expect(getDisplayText(editor)).toBe(dedent`
  1282. /**… */
  1283. const x = 1 /*…*/
  1284. `);
  1285. });
  1286. it('tries each folding strategy for a given node in the order specified', async () => {
  1287. const grammar = new TreeSitterGrammar(atom.grammars, cGrammarPath, {
  1288. parser: 'tree-sitter-c',
  1289. folds: [
  1290. // If the #ifdef has an `#else` clause, then end the fold there.
  1291. {
  1292. type: ['preproc_ifdef', 'preproc_elif'],
  1293. start: { index: 1 },
  1294. end: { type: ['preproc_else', 'preproc_elif'] }
  1295. },
  1296. // Otherwise, end the fold at the last child - the `#endif`.
  1297. {
  1298. type: 'preproc_ifdef',
  1299. start: { index: 1 },
  1300. end: { index: -1 }
  1301. },
  1302. // When folding an `#else` clause, the fold extends to the end of the clause.
  1303. {
  1304. type: 'preproc_else',
  1305. start: { index: 0 }
  1306. }
  1307. ]
  1308. });
  1309. buffer.setText(dedent`
  1310. #ifndef FOO_H_
  1311. #define FOO_H_
  1312. #ifdef _WIN32
  1313. #include <windows.h>
  1314. const char *path_separator = "\\";
  1315. #elif defined MACOS
  1316. #include <carbon.h>
  1317. const char *path_separator = "/";
  1318. #else
  1319. #include <dirent.h>
  1320. const char *path_separator = "/";
  1321. #endif
  1322. #endif
  1323. `);
  1324. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  1325. buffer.setLanguageMode(languageMode);
  1326. editor.foldBufferRow(3);
  1327. expect(getDisplayText(editor)).toBe(dedent`
  1328. #ifndef FOO_H_
  1329. #define FOO_H_
  1330. #ifdef _WIN32…
  1331. #elif defined MACOS
  1332. #include <carbon.h>
  1333. const char *path_separator = "/";
  1334. #else
  1335. #include <dirent.h>
  1336. const char *path_separator = "/";
  1337. #endif
  1338. #endif
  1339. `);
  1340. editor.foldBufferRow(8);
  1341. expect(getDisplayText(editor)).toBe(dedent`
  1342. #ifndef FOO_H_
  1343. #define FOO_H_
  1344. #ifdef _WIN32…
  1345. #elif defined MACOS…
  1346. #else
  1347. #include <dirent.h>
  1348. const char *path_separator = "/";
  1349. #endif
  1350. #endif
  1351. `);
  1352. editor.foldBufferRow(0);
  1353. expect(getDisplayText(editor)).toBe(dedent`
  1354. #ifndef FOO_H_…
  1355. #endif
  1356. `);
  1357. editor.foldAllAtIndentLevel(1);
  1358. expect(getDisplayText(editor)).toBe(dedent`
  1359. #ifndef FOO_H_
  1360. #define FOO_H_
  1361. #ifdef _WIN32…
  1362. #elif defined MACOS…
  1363. #else…
  1364. #endif
  1365. #endif
  1366. `);
  1367. });
  1368. it('does not fold when the start and end parameters match the same child', async () => {
  1369. const grammar = new TreeSitterGrammar(atom.grammars, htmlGrammarPath, {
  1370. parser: 'tree-sitter-html',
  1371. folds: [
  1372. {
  1373. type: 'element',
  1374. start: { index: 0 },
  1375. end: { index: -1 }
  1376. }
  1377. ]
  1378. });
  1379. buffer.setText(dedent`
  1380. <head>
  1381. <meta name='key-1', content='value-1'>
  1382. <meta name='key-2', content='value-2'>
  1383. </head>
  1384. `);
  1385. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  1386. buffer.setLanguageMode(languageMode);
  1387. // Void elements have only one child
  1388. expect(editor.isFoldableAtBufferRow(1)).toBe(false);
  1389. expect(editor.isFoldableAtBufferRow(2)).toBe(false);
  1390. editor.foldBufferRow(0);
  1391. expect(getDisplayText(editor)).toBe(dedent`
  1392. <head>…
  1393. </head>
  1394. `);
  1395. });
  1396. it('can target named vs anonymous nodes as fold boundaries', async () => {
  1397. const grammar = new TreeSitterGrammar(atom.grammars, rubyGrammarPath, {
  1398. parser: 'tree-sitter-ruby',
  1399. folds: [
  1400. // Note that this isn't how folds actually work in language-ruby. It's
  1401. // just to demonstrate the targeting of named vs anonymous nodes.
  1402. {
  1403. type: 'elsif',
  1404. start: { index: 1 },
  1405. // There are no double quotes around the `elsif` type. This indicates
  1406. // that we're targeting a *named* node in the syntax tree. The fold
  1407. // should end at the nested `elsif` node, not at the token that represents
  1408. // the literal string "elsif".
  1409. end: { type: ['else', 'elsif'] }
  1410. },
  1411. {
  1412. type: 'else',
  1413. // There are double quotes around the `else` type. This indicates that
  1414. // we're targeting an *anonymous* node in the syntax tree. The fold
  1415. // should start at the token representing the literal string "else",
  1416. // not at an `else` node.
  1417. start: { type: '"else"' }
  1418. }
  1419. ]
  1420. });
  1421. buffer.setText(dedent`
  1422. if a
  1423. b
  1424. elsif c
  1425. d
  1426. else
  1427. e
  1428. end
  1429. `);
  1430. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  1431. buffer.setLanguageMode(languageMode);
  1432. expect(languageMode.tree.rootNode.toString()).toBe(
  1433. '(program (if condition: (identifier) consequence: (then ' +
  1434. '(identifier)) ' +
  1435. 'alternative: (elsif condition: (identifier) consequence: (then ' +
  1436. '(identifier)) ' +
  1437. 'alternative: (else ' +
  1438. '(identifier)))))'
  1439. );
  1440. editor.foldBufferRow(2);
  1441. expect(getDisplayText(editor)).toBe(dedent`
  1442. if a
  1443. b
  1444. elsif c…
  1445. else
  1446. e
  1447. end
  1448. `);
  1449. editor.foldBufferRow(4);
  1450. expect(getDisplayText(editor)).toBe(dedent`
  1451. if a
  1452. b
  1453. elsif c…
  1454. else…
  1455. end
  1456. `);
  1457. });
  1458. it('updates fold locations when the buffer changes', () => {
  1459. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1460. parser: 'tree-sitter-javascript',
  1461. folds: [
  1462. {
  1463. start: { type: '{', index: 0 },
  1464. end: { type: '}', index: -1 }
  1465. }
  1466. ]
  1467. });
  1468. buffer.setText(dedent`
  1469. class A {
  1470. // a
  1471. constructor (b) {
  1472. this.b = b
  1473. }
  1474. }
  1475. `);
  1476. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  1477. buffer.setLanguageMode(languageMode);
  1478. expect(languageMode.isFoldableAtRow(0)).toBe(true);
  1479. expect(languageMode.isFoldableAtRow(1)).toBe(false);
  1480. expect(languageMode.isFoldableAtRow(2)).toBe(true);
  1481. expect(languageMode.isFoldableAtRow(3)).toBe(false);
  1482. expect(languageMode.isFoldableAtRow(4)).toBe(false);
  1483. buffer.insert([0, 0], '\n');
  1484. expect(languageMode.isFoldableAtRow(0)).toBe(false);
  1485. expect(languageMode.isFoldableAtRow(1)).toBe(true);
  1486. expect(languageMode.isFoldableAtRow(2)).toBe(false);
  1487. expect(languageMode.isFoldableAtRow(3)).toBe(true);
  1488. expect(languageMode.isFoldableAtRow(4)).toBe(false);
  1489. });
  1490. describe('when folding a node that ends with a line break', () => {
  1491. it('ends the fold at the end of the previous line', async () => {
  1492. const grammar = new TreeSitterGrammar(
  1493. atom.grammars,
  1494. pythonGrammarPath,
  1495. {
  1496. parser: 'tree-sitter-python',
  1497. folds: [
  1498. {
  1499. type: 'function_definition',
  1500. start: { type: ':' }
  1501. }
  1502. ]
  1503. }
  1504. );
  1505. buffer.setText(dedent`
  1506. def ab():
  1507. print 'a'
  1508. print 'b'
  1509. def cd():
  1510. print 'c'
  1511. print 'd'
  1512. `);
  1513. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1514. editor.foldBufferRow(0);
  1515. expect(getDisplayText(editor)).toBe(dedent`
  1516. def ab():…
  1517. def cd():
  1518. print 'c'
  1519. print 'd'
  1520. `);
  1521. });
  1522. });
  1523. it('folds code in injected languages', async () => {
  1524. const htmlGrammar = new TreeSitterGrammar(
  1525. atom.grammars,
  1526. htmlGrammarPath,
  1527. {
  1528. scopeName: 'html',
  1529. parser: 'tree-sitter-html',
  1530. scopes: {},
  1531. folds: [
  1532. {
  1533. type: ['element', 'script_element'],
  1534. start: { index: 0 },
  1535. end: { index: -1 }
  1536. }
  1537. ],
  1538. injectionRegExp: 'html'
  1539. }
  1540. );
  1541. const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1542. scopeName: 'javascript',
  1543. parser: 'tree-sitter-javascript',
  1544. scopes: {},
  1545. folds: [
  1546. {
  1547. type: ['template_string'],
  1548. start: { index: 0 },
  1549. end: { index: -1 }
  1550. },
  1551. {
  1552. start: { index: 0, type: '(' },
  1553. end: { index: -1, type: ')' }
  1554. }
  1555. ],
  1556. injectionRegExp: 'javascript',
  1557. injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT]
  1558. });
  1559. atom.grammars.addGrammar(htmlGrammar);
  1560. buffer.setText(
  1561. `a = html \`
  1562. <div>
  1563. c\${def(
  1564. 1,
  1565. 2,
  1566. 3,
  1567. )}e\${f}g
  1568. </div>
  1569. \`
  1570. `
  1571. );
  1572. const languageMode = new TreeSitterLanguageMode({
  1573. buffer,
  1574. grammar: jsGrammar,
  1575. grammars: atom.grammars
  1576. });
  1577. buffer.setLanguageMode(languageMode);
  1578. editor.foldBufferRow(2);
  1579. expect(getDisplayText(editor)).toBe(
  1580. `a = html \`
  1581. <div>
  1582. c\${def(…
  1583. )}e\${f}g
  1584. </div>
  1585. \`
  1586. `
  1587. );
  1588. editor.foldBufferRow(1);
  1589. expect(getDisplayText(editor)).toBe(
  1590. `a = html \`
  1591. <div>…
  1592. </div>
  1593. \`
  1594. `
  1595. );
  1596. editor.foldBufferRow(0);
  1597. expect(getDisplayText(editor)).toBe(
  1598. `a = html \`…\`
  1599. `
  1600. );
  1601. });
  1602. });
  1603. describe('.scopeDescriptorForPosition', () => {
  1604. it('returns a scope descriptor representing the given position in the syntax tree', async () => {
  1605. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1606. scopeName: 'source.js',
  1607. parser: 'tree-sitter-javascript',
  1608. scopes: {
  1609. program: 'source.js',
  1610. property_identifier: 'property.name',
  1611. comment: 'comment.block'
  1612. }
  1613. });
  1614. buffer.setText('foo({bar: baz});');
  1615. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1616. expect(
  1617. editor
  1618. .scopeDescriptorForBufferPosition([0, 'foo({b'.length])
  1619. .getScopesArray()
  1620. ).toEqual(['source.js', 'property.name']);
  1621. expect(
  1622. editor
  1623. .scopeDescriptorForBufferPosition([0, 'foo({'.length])
  1624. .getScopesArray()
  1625. ).toEqual(['source.js', 'property.name']);
  1626. // Drive-by test for .tokenForPosition()
  1627. const token = editor.tokenForBufferPosition([0, 'foo({b'.length]);
  1628. expect(token.value).toBe('bar');
  1629. expect(token.scopes).toEqual(['source.js', 'property.name']);
  1630. buffer.setText('// baz\n');
  1631. // Adjust position when at end of line
  1632. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1633. expect(
  1634. editor
  1635. .scopeDescriptorForBufferPosition([0, '// baz'.length])
  1636. .getScopesArray()
  1637. ).toEqual(['source.js', 'comment.block']);
  1638. });
  1639. it('includes nodes in injected syntax trees', async () => {
  1640. const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1641. scopeName: 'source.js',
  1642. parser: 'tree-sitter-javascript',
  1643. scopes: {
  1644. program: 'source.js',
  1645. template_string: 'string.quoted',
  1646. interpolation: 'meta.embedded',
  1647. property_identifier: 'property.name'
  1648. },
  1649. injectionRegExp: 'javascript',
  1650. injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT]
  1651. });
  1652. const htmlGrammar = new TreeSitterGrammar(
  1653. atom.grammars,
  1654. htmlGrammarPath,
  1655. {
  1656. scopeName: 'text.html',
  1657. parser: 'tree-sitter-html',
  1658. scopes: {
  1659. fragment: 'text.html',
  1660. script_element: 'script.tag'
  1661. },
  1662. injectionRegExp: 'html',
  1663. injectionPoints: [SCRIPT_TAG_INJECTION_POINT]
  1664. }
  1665. );
  1666. atom.grammars.addGrammar(jsGrammar);
  1667. atom.grammars.addGrammar(htmlGrammar);
  1668. buffer.setText(`
  1669. <div>
  1670. <script>
  1671. html \`
  1672. <span>\${person.name}</span>
  1673. \`
  1674. </script>
  1675. </div>
  1676. `);
  1677. const languageMode = new TreeSitterLanguageMode({
  1678. buffer,
  1679. grammar: htmlGrammar,
  1680. grammars: atom.grammars
  1681. });
  1682. buffer.setLanguageMode(languageMode);
  1683. const position = buffer.findSync('name').start;
  1684. expect(
  1685. languageMode.scopeDescriptorForPosition(position).getScopesArray()
  1686. ).toEqual([
  1687. 'text.html',
  1688. 'script.tag',
  1689. 'source.js',
  1690. 'string.quoted',
  1691. 'text.html',
  1692. 'property.name'
  1693. ]);
  1694. });
  1695. it('includes the root scope name even when the given position is in trailing whitespace at EOF', () => {
  1696. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1697. scopeName: 'source.js',
  1698. parser: 'tree-sitter-javascript',
  1699. scopes: {
  1700. program: 'source.js',
  1701. property_identifier: 'property.name'
  1702. }
  1703. });
  1704. buffer.setText('a; ');
  1705. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1706. expect(
  1707. editor.scopeDescriptorForBufferPosition([0, 3]).getScopesArray()
  1708. ).toEqual(['source.js']);
  1709. });
  1710. it('works when the given position is between tokens', () => {
  1711. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1712. scopeName: 'source.js',
  1713. parser: 'tree-sitter-javascript',
  1714. scopes: {
  1715. program: 'source.js',
  1716. comment: 'comment.block'
  1717. }
  1718. });
  1719. buffer.setText('a // b');
  1720. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1721. expect(
  1722. editor.scopeDescriptorForBufferPosition([0, 2]).getScopesArray()
  1723. ).toEqual(['source.js']);
  1724. expect(
  1725. editor.scopeDescriptorForBufferPosition([0, 3]).getScopesArray()
  1726. ).toEqual(['source.js', 'comment.block']);
  1727. });
  1728. });
  1729. describe('.syntaxTreeScopeDescriptorForPosition', () => {
  1730. it('returns a scope descriptor representing the given position in the syntax tree', async () => {
  1731. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1732. scopeName: 'source.js',
  1733. parser: 'tree-sitter-javascript'
  1734. });
  1735. buffer.setText('foo({bar: baz});');
  1736. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1737. expect(
  1738. editor
  1739. .syntaxTreeScopeDescriptorForBufferPosition([0, 6])
  1740. .getScopesArray()
  1741. ).toEqual([
  1742. 'source.js',
  1743. 'program',
  1744. 'expression_statement',
  1745. 'call_expression',
  1746. 'arguments',
  1747. 'object',
  1748. 'pair',
  1749. 'property_identifier'
  1750. ]);
  1751. buffer.setText('//bar\n');
  1752. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1753. expect(
  1754. editor
  1755. .syntaxTreeScopeDescriptorForBufferPosition([0, 5])
  1756. .getScopesArray()
  1757. ).toEqual(['source.js', 'program', 'comment']);
  1758. });
  1759. it('includes nodes in injected syntax trees', async () => {
  1760. const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1761. scopeName: 'source.js',
  1762. parser: 'tree-sitter-javascript',
  1763. scopes: {},
  1764. injectionRegExp: 'javascript',
  1765. injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT]
  1766. });
  1767. const htmlGrammar = new TreeSitterGrammar(
  1768. atom.grammars,
  1769. htmlGrammarPath,
  1770. {
  1771. scopeName: 'text.html',
  1772. parser: 'tree-sitter-html',
  1773. scopes: {},
  1774. injectionRegExp: 'html',
  1775. injectionPoints: [SCRIPT_TAG_INJECTION_POINT]
  1776. }
  1777. );
  1778. atom.grammars.addGrammar(jsGrammar);
  1779. atom.grammars.addGrammar(htmlGrammar);
  1780. buffer.setText(`
  1781. <div>
  1782. <script>
  1783. html \`
  1784. <span>\${person.name}</span>
  1785. \`
  1786. </script>
  1787. </div>
  1788. `);
  1789. const languageMode = new TreeSitterLanguageMode({
  1790. buffer,
  1791. grammar: htmlGrammar,
  1792. grammars: atom.grammars
  1793. });
  1794. buffer.setLanguageMode(languageMode);
  1795. const position = buffer.findSync('name').start;
  1796. expect(
  1797. editor
  1798. .syntaxTreeScopeDescriptorForBufferPosition(position)
  1799. .getScopesArray()
  1800. ).toEqual([
  1801. 'text.html',
  1802. 'fragment',
  1803. 'element',
  1804. 'script_element',
  1805. 'program',
  1806. 'raw_text',
  1807. 'expression_statement',
  1808. 'call_expression',
  1809. 'template_string',
  1810. 'fragment',
  1811. 'element',
  1812. 'template_substitution',
  1813. 'member_expression',
  1814. 'property_identifier'
  1815. ]);
  1816. });
  1817. });
  1818. describe('.bufferRangeForScopeAtPosition(selector?, position)', () => {
  1819. describe('when selector = null', () => {
  1820. it('returns the range of the smallest node at position', async () => {
  1821. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1822. scopeName: 'javascript',
  1823. parser: 'tree-sitter-javascript'
  1824. });
  1825. buffer.setText('foo({bar: baz});');
  1826. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1827. expect(editor.bufferRangeForScopeAtPosition(null, [0, 6])).toEqual([
  1828. [0, 5],
  1829. [0, 8]
  1830. ]);
  1831. expect(editor.bufferRangeForScopeAtPosition(null, [0, 8])).toEqual([
  1832. [0, 8],
  1833. [0, 9]
  1834. ]);
  1835. });
  1836. it('includes nodes in injected syntax trees', async () => {
  1837. const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1838. scopeName: 'javascript',
  1839. parser: 'tree-sitter-javascript',
  1840. scopes: {},
  1841. injectionRegExp: 'javascript',
  1842. injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT]
  1843. });
  1844. const htmlGrammar = new TreeSitterGrammar(
  1845. atom.grammars,
  1846. htmlGrammarPath,
  1847. {
  1848. scopeName: 'html',
  1849. parser: 'tree-sitter-html',
  1850. scopes: {},
  1851. injectionRegExp: 'html',
  1852. injectionPoints: [SCRIPT_TAG_INJECTION_POINT]
  1853. }
  1854. );
  1855. atom.grammars.addGrammar(jsGrammar);
  1856. atom.grammars.addGrammar(htmlGrammar);
  1857. buffer.setText(`
  1858. <div>
  1859. <script>
  1860. html \`
  1861. <span>\${person.name}</span>
  1862. \`
  1863. </script>
  1864. </div>
  1865. `);
  1866. const languageMode = new TreeSitterLanguageMode({
  1867. buffer,
  1868. grammar: htmlGrammar,
  1869. grammars: atom.grammars
  1870. });
  1871. buffer.setLanguageMode(languageMode);
  1872. const nameProperty = buffer.findSync('name');
  1873. const { start } = nameProperty;
  1874. const position = Object.assign({}, start, { column: start.column + 2 });
  1875. expect(
  1876. languageMode.bufferRangeForScopeAtPosition(null, position)
  1877. ).toEqual(nameProperty);
  1878. });
  1879. });
  1880. describe('with a selector', () => {
  1881. it('returns the range of the smallest matching node at position', async () => {
  1882. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1883. scopeName: 'javascript',
  1884. parser: 'tree-sitter-javascript',
  1885. scopes: {
  1886. property_identifier: 'variable.other.object.property',
  1887. template_string: 'string.quoted.template'
  1888. }
  1889. });
  1890. buffer.setText('a(`${b({ccc: ddd})} eee`);');
  1891. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  1892. expect(
  1893. editor.bufferRangeForScopeAtPosition('.variable.property', [0, 9])
  1894. ).toEqual([[0, 8], [0, 11]]);
  1895. expect(
  1896. editor.bufferRangeForScopeAtPosition('.string.quoted', [0, 6])
  1897. ).toEqual([[0, 2], [0, 24]]);
  1898. });
  1899. it('includes nodes in injected syntax trees', async () => {
  1900. const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1901. scopeName: 'javascript',
  1902. parser: 'tree-sitter-javascript',
  1903. scopes: {
  1904. property_identifier: 'variable.other.object.property'
  1905. },
  1906. injectionRegExp: 'javascript',
  1907. injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT]
  1908. });
  1909. const htmlGrammar = new TreeSitterGrammar(
  1910. atom.grammars,
  1911. htmlGrammarPath,
  1912. {
  1913. scopeName: 'html',
  1914. parser: 'tree-sitter-html',
  1915. scopes: {
  1916. element: 'meta.element.html'
  1917. },
  1918. injectionRegExp: 'html',
  1919. injectionPoints: [SCRIPT_TAG_INJECTION_POINT]
  1920. }
  1921. );
  1922. atom.grammars.addGrammar(jsGrammar);
  1923. atom.grammars.addGrammar(htmlGrammar);
  1924. buffer.setText(`
  1925. <div>
  1926. <script>
  1927. html \`
  1928. <span>\${person.name}</span>
  1929. \`
  1930. </script>
  1931. </div>
  1932. `);
  1933. const languageMode = new TreeSitterLanguageMode({
  1934. buffer,
  1935. grammar: htmlGrammar,
  1936. grammars: atom.grammars
  1937. });
  1938. buffer.setLanguageMode(languageMode);
  1939. const nameProperty = buffer.findSync('name');
  1940. const { start } = nameProperty;
  1941. const position = Object.assign({}, start, { column: start.column + 2 });
  1942. expect(
  1943. languageMode.bufferRangeForScopeAtPosition(
  1944. '.object.property',
  1945. position
  1946. )
  1947. ).toEqual(nameProperty);
  1948. expect(
  1949. languageMode.bufferRangeForScopeAtPosition(
  1950. '.meta.element.html',
  1951. position
  1952. )
  1953. ).toEqual(buffer.findSync('<span>\\${person\\.name}</span>'));
  1954. });
  1955. it('accepts node-matching functions as selectors', async () => {
  1956. const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  1957. scopeName: 'javascript',
  1958. parser: 'tree-sitter-javascript',
  1959. scopes: {},
  1960. injectionRegExp: 'javascript',
  1961. injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT]
  1962. });
  1963. const htmlGrammar = new TreeSitterGrammar(
  1964. atom.grammars,
  1965. htmlGrammarPath,
  1966. {
  1967. scopeName: 'html',
  1968. parser: 'tree-sitter-html',
  1969. scopes: {},
  1970. injectionRegExp: 'html',
  1971. injectionPoints: [SCRIPT_TAG_INJECTION_POINT]
  1972. }
  1973. );
  1974. atom.grammars.addGrammar(jsGrammar);
  1975. atom.grammars.addGrammar(htmlGrammar);
  1976. buffer.setText(`
  1977. <div>
  1978. <script>
  1979. html \`
  1980. <span>\${person.name}</span>
  1981. \`
  1982. </script>
  1983. </div>
  1984. `);
  1985. const languageMode = new TreeSitterLanguageMode({
  1986. buffer,
  1987. grammar: htmlGrammar,
  1988. grammars: atom.grammars
  1989. });
  1990. buffer.setLanguageMode(languageMode);
  1991. const nameProperty = buffer.findSync('name');
  1992. const { start } = nameProperty;
  1993. const position = Object.assign({}, start, { column: start.column + 2 });
  1994. const templateStringInCallExpression = node =>
  1995. node.type === 'template_string' &&
  1996. node.parent.type === 'call_expression';
  1997. expect(
  1998. languageMode.bufferRangeForScopeAtPosition(
  1999. templateStringInCallExpression,
  2000. position
  2001. )
  2002. ).toEqual([[3, 19], [5, 15]]);
  2003. });
  2004. });
  2005. });
  2006. describe('.getSyntaxNodeAtPosition(position, where?)', () => {
  2007. it('returns the range of the smallest matching node at position', async () => {
  2008. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  2009. scopeName: 'javascript',
  2010. parser: 'tree-sitter-javascript'
  2011. });
  2012. buffer.setText('foo(bar({x: 2}));');
  2013. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  2014. buffer.setLanguageMode(languageMode);
  2015. expect(languageMode.getSyntaxNodeAtPosition([0, 6]).range).toEqual(
  2016. buffer.findSync('bar')
  2017. );
  2018. const findFoo = node =>
  2019. node.type === 'call_expression' && node.firstChild.text === 'foo';
  2020. expect(
  2021. languageMode.getSyntaxNodeAtPosition([0, 6], findFoo).range
  2022. ).toEqual([[0, 0], [0, buffer.getText().length - 1]]);
  2023. });
  2024. });
  2025. describe('.commentStringsForPosition(position)', () => {
  2026. it('returns the correct comment strings for nested languages', () => {
  2027. const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  2028. scopeName: 'javascript',
  2029. parser: 'tree-sitter-javascript',
  2030. comments: { start: '//' },
  2031. injectionRegExp: 'javascript',
  2032. injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT]
  2033. });
  2034. const htmlGrammar = new TreeSitterGrammar(
  2035. atom.grammars,
  2036. htmlGrammarPath,
  2037. {
  2038. scopeName: 'html',
  2039. parser: 'tree-sitter-html',
  2040. scopes: {},
  2041. comments: { start: '<!--', end: '-->' },
  2042. injectionRegExp: 'html',
  2043. injectionPoints: [SCRIPT_TAG_INJECTION_POINT]
  2044. }
  2045. );
  2046. atom.grammars.addGrammar(jsGrammar);
  2047. atom.grammars.addGrammar(htmlGrammar);
  2048. const languageMode = new TreeSitterLanguageMode({
  2049. buffer,
  2050. grammar: htmlGrammar,
  2051. grammars: atom.grammars
  2052. });
  2053. buffer.setLanguageMode(languageMode);
  2054. buffer.setText(
  2055. `
  2056. <div>hi</div>
  2057. <script>
  2058. const node = document.getElementById('some-id');
  2059. node.innerHTML = html \`
  2060. <span>bye</span>
  2061. \`
  2062. </script>
  2063. `.trim()
  2064. );
  2065. const htmlCommentStrings = {
  2066. commentStartString: '<!--',
  2067. commentEndString: '-->'
  2068. };
  2069. const jsCommentStrings = {
  2070. commentStartString: '//',
  2071. commentEndString: undefined
  2072. };
  2073. expect(languageMode.commentStringsForPosition(new Point(0, 0))).toEqual(
  2074. htmlCommentStrings
  2075. );
  2076. expect(languageMode.commentStringsForPosition(new Point(1, 0))).toEqual(
  2077. htmlCommentStrings
  2078. );
  2079. expect(languageMode.commentStringsForPosition(new Point(2, 0))).toEqual(
  2080. jsCommentStrings
  2081. );
  2082. expect(languageMode.commentStringsForPosition(new Point(3, 0))).toEqual(
  2083. jsCommentStrings
  2084. );
  2085. expect(languageMode.commentStringsForPosition(new Point(4, 0))).toEqual(
  2086. htmlCommentStrings
  2087. );
  2088. expect(languageMode.commentStringsForPosition(new Point(5, 0))).toEqual(
  2089. jsCommentStrings
  2090. );
  2091. expect(languageMode.commentStringsForPosition(new Point(6, 0))).toEqual(
  2092. htmlCommentStrings
  2093. );
  2094. });
  2095. });
  2096. describe('TextEditor.selectLargerSyntaxNode and .selectSmallerSyntaxNode', () => {
  2097. it('expands and contracts the selection based on the syntax tree', async () => {
  2098. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  2099. parser: 'tree-sitter-javascript',
  2100. scopes: { program: 'source' }
  2101. });
  2102. buffer.setText(dedent`
  2103. function a (b, c, d) {
  2104. eee.f()
  2105. g()
  2106. }
  2107. `);
  2108. buffer.setLanguageMode(new TreeSitterLanguageMode({ buffer, grammar }));
  2109. editor.setCursorBufferPosition([1, 3]);
  2110. editor.selectLargerSyntaxNode();
  2111. expect(editor.getSelectedText()).toBe('eee');
  2112. editor.selectLargerSyntaxNode();
  2113. expect(editor.getSelectedText()).toBe('eee.f');
  2114. editor.selectLargerSyntaxNode();
  2115. expect(editor.getSelectedText()).toBe('eee.f()');
  2116. editor.selectLargerSyntaxNode();
  2117. expect(editor.getSelectedText()).toBe('{\n eee.f()\n g()\n}');
  2118. editor.selectLargerSyntaxNode();
  2119. expect(editor.getSelectedText()).toBe(
  2120. 'function a (b, c, d) {\n eee.f()\n g()\n}'
  2121. );
  2122. editor.selectSmallerSyntaxNode();
  2123. expect(editor.getSelectedText()).toBe('{\n eee.f()\n g()\n}');
  2124. editor.selectSmallerSyntaxNode();
  2125. expect(editor.getSelectedText()).toBe('eee.f()');
  2126. editor.selectSmallerSyntaxNode();
  2127. expect(editor.getSelectedText()).toBe('eee.f');
  2128. editor.selectSmallerSyntaxNode();
  2129. expect(editor.getSelectedText()).toBe('eee');
  2130. editor.selectSmallerSyntaxNode();
  2131. expect(editor.getSelectedBufferRange()).toEqual([[1, 3], [1, 3]]);
  2132. });
  2133. it('handles injected languages', async () => {
  2134. const jsGrammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  2135. scopeName: 'javascript',
  2136. parser: 'tree-sitter-javascript',
  2137. scopes: {
  2138. property_identifier: 'property',
  2139. 'call_expression > identifier': 'function',
  2140. template_string: 'string',
  2141. 'template_substitution > "${"': 'interpolation',
  2142. 'template_substitution > "}"': 'interpolation'
  2143. },
  2144. injectionRegExp: 'javascript',
  2145. injectionPoints: [HTML_TEMPLATE_LITERAL_INJECTION_POINT]
  2146. });
  2147. const htmlGrammar = new TreeSitterGrammar(
  2148. atom.grammars,
  2149. htmlGrammarPath,
  2150. {
  2151. scopeName: 'html',
  2152. parser: 'tree-sitter-html',
  2153. scopes: {
  2154. fragment: 'html',
  2155. tag_name: 'tag',
  2156. attribute_name: 'attr'
  2157. },
  2158. injectionRegExp: 'html'
  2159. }
  2160. );
  2161. atom.grammars.addGrammar(htmlGrammar);
  2162. buffer.setText('a = html ` <b>c${def()}e${f}g</b> `');
  2163. const languageMode = new TreeSitterLanguageMode({
  2164. buffer,
  2165. grammar: jsGrammar,
  2166. grammars: atom.grammars
  2167. });
  2168. buffer.setLanguageMode(languageMode);
  2169. editor.setCursorBufferPosition({
  2170. row: 0,
  2171. column: buffer.getText().indexOf('ef()')
  2172. });
  2173. editor.selectLargerSyntaxNode();
  2174. expect(editor.getSelectedText()).toBe('def');
  2175. editor.selectLargerSyntaxNode();
  2176. expect(editor.getSelectedText()).toBe('def()');
  2177. editor.selectLargerSyntaxNode();
  2178. expect(editor.getSelectedText()).toBe('${def()}');
  2179. editor.selectLargerSyntaxNode();
  2180. expect(editor.getSelectedText()).toBe('c${def()}e${f}g');
  2181. editor.selectLargerSyntaxNode();
  2182. expect(editor.getSelectedText()).toBe('<b>c${def()}e${f}g</b>');
  2183. editor.selectLargerSyntaxNode();
  2184. expect(editor.getSelectedText()).toBe(' <b>c${def()}e${f}g</b> ');
  2185. editor.selectLargerSyntaxNode();
  2186. expect(editor.getSelectedText()).toBe('` <b>c${def()}e${f}g</b> `');
  2187. editor.selectLargerSyntaxNode();
  2188. expect(editor.getSelectedText()).toBe('html ` <b>c${def()}e${f}g</b> `');
  2189. });
  2190. });
  2191. describe('.tokenizedLineForRow(row)', () => {
  2192. it('returns a shimmed TokenizedLine with tokens', () => {
  2193. const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, {
  2194. parser: 'tree-sitter-javascript',
  2195. scopes: {
  2196. program: 'source',
  2197. 'call_expression > identifier': 'function',
  2198. property_identifier: 'property',
  2199. 'call_expression > member_expression > property_identifier': 'method',
  2200. identifier: 'variable'
  2201. }
  2202. });
  2203. buffer.setText('aa.bbb = cc(d.eee());\n\n \n b');
  2204. const languageMode = new TreeSitterLanguageMode({ buffer, grammar });
  2205. buffer.setLanguageMode(languageMode);
  2206. expect(languageMode.tokenizedLineForRow(0).tokens).toEqual([
  2207. { value: 'aa', scopes: ['source', 'variable'] },
  2208. { value: '.', scopes: ['source'] },
  2209. { value: 'bbb', scopes: ['source', 'property'] },
  2210. { value: ' = ', scopes: ['source'] },
  2211. { value: 'cc', scopes: ['source', 'function'] },
  2212. { value: '(', scopes: ['source'] },
  2213. { value: 'd', scopes: ['source', 'variable'] },
  2214. { value: '.', scopes: ['source'] },
  2215. { value: 'eee', scopes: ['source', 'method'] },
  2216. { value: '());', scopes: ['source'] }
  2217. ]);
  2218. expect(languageMode.tokenizedLineForRow(1).tokens).toEqual([]);
  2219. expect(languageMode.tokenizedLineForRow(2).tokens).toEqual([
  2220. { value: ' ', scopes: ['source'] }
  2221. ]);
  2222. expect(languageMode.tokenizedLineForRow(3).tokens).toEqual([
  2223. { value: ' ', scopes: ['source'] },
  2224. { value: 'b', scopes: ['source', 'variable'] }
  2225. ]);
  2226. });
  2227. });
  2228. });
  2229. function nextHighlightingUpdate(languageMode) {
  2230. return new Promise(resolve => {
  2231. const subscription = languageMode.onDidChangeHighlighting(() => {
  2232. subscription.dispose();
  2233. resolve();
  2234. });
  2235. });
  2236. }
  2237. function getDisplayText(editor) {
  2238. return editor.displayLayer.getText();
  2239. }
  2240. function expectTokensToEqual(editor, expectedTokenLines) {
  2241. const lastRow = editor.getLastScreenRow();
  2242. // Assert that the correct tokens are returned regardless of which row
  2243. // the highlighting iterator starts on.
  2244. for (let startRow = 0; startRow <= lastRow; startRow++) {
  2245. // Clear the screen line cache between iterations, but not on the first
  2246. // iteration, so that the first iteration tests that the cache has been
  2247. // correctly invalidated by any changes.
  2248. if (startRow > 0) {
  2249. editor.displayLayer.clearSpatialIndex();
  2250. }
  2251. editor.displayLayer.getScreenLines(startRow, Infinity);
  2252. const tokenLines = [];
  2253. for (let row = startRow; row <= lastRow; row++) {
  2254. tokenLines[row] = editor
  2255. .tokensForScreenRow(row)
  2256. .map(({ text, scopes }) => ({
  2257. text,
  2258. scopes: scopes.map(scope =>
  2259. scope
  2260. .split(' ')
  2261. .map(className => className.replace('syntax--', ''))
  2262. .join(' ')
  2263. )
  2264. }));
  2265. }
  2266. // console.log('EXPECTED:', expectedTokenLines);
  2267. // console.log('ACTUAL:', tokenLines);
  2268. for (let row = startRow; row <= lastRow; row++) {
  2269. const tokenLine = tokenLines[row];
  2270. const expectedTokenLine = expectedTokenLines[row];
  2271. expect(tokenLine.length).toEqual(expectedTokenLine.length);
  2272. for (let i = 0; i < tokenLine.length; i++) {
  2273. expect(tokenLine[i]).toEqual(
  2274. expectedTokenLine[i],
  2275. `Token ${i}, startRow: ${startRow}`
  2276. );
  2277. }
  2278. }
  2279. }
  2280. // Fully populate the screen line cache again so that cache invalidation
  2281. // due to subsequent edits can be tested.
  2282. editor.displayLayer.getScreenLines(0, Infinity);
  2283. }
  2284. const HTML_TEMPLATE_LITERAL_INJECTION_POINT = {
  2285. type: 'call_expression',
  2286. language(node) {
  2287. if (
  2288. node.lastChild.type === 'template_string' &&
  2289. node.firstChild.type === 'identifier'
  2290. ) {
  2291. return node.firstChild.text;
  2292. }
  2293. },
  2294. content(node) {
  2295. return node.lastChild;
  2296. }
  2297. };
  2298. const SCRIPT_TAG_INJECTION_POINT = {
  2299. type: 'script_element',
  2300. language() {
  2301. return 'javascript';
  2302. },
  2303. content(node) {
  2304. return node.child(1);
  2305. }
  2306. };
  2307. const JSDOC_INJECTION_POINT = {
  2308. type: 'comment',
  2309. language(comment) {
  2310. if (comment.text.startsWith('/**')) return 'jsdoc';
  2311. },
  2312. content(comment) {
  2313. return comment;
  2314. }
  2315. };